在 Azure Mobile 计划作业中使用 CodeProject API
让我们尝试了解如何在 Windows Azure Mobile Services 的计划作业中使用 CodeProject API。
引言
注意 - 本文代码不包含任何对基于 Nuget 的库的引用。我删除它们是出于一个好理由,那就是,我真的对项目整体的压缩大小感到震惊。是的,它非常大。您需要做的是,下载并编译源代码,以便下载 Nuget 引用并编译项目。
在本文中,我将带您了解 Azure Mobile Scheduled Jobs 的基础知识;如何创建一个并进行测试以获得体验。
首先,让我们对 Azure Mobile 中的计划作业有一些基本的了解,然后我们可以继续通过利用 CodeProject API 来实现。
我将讨论以下主题
- 计划作业基础知识
- 创建 Azure Mobile Service
- 创建计划作业
- 通过 SMS 发送 CodeProject 通知
- 发布 Azure Mobile Service
- 创建计划作业
- 运行计划作业
- 验证计划作业响应
计划作业基础知识
计划作业是后台运行的任务。这些作业的运行基于您在计划过程中如何定义它们。有时您可能需要在 Azure Mobile Services 中执行后台操作;这时就需要用到 Scheduler,它可以方便地运行这些可以计划运行的后台任务。
您可以每隔一段时间(分钟、小时、天、月)运行一个特定任务,或按需运行。如果您问可以计划什么样的作业,您可以运行从最简单的到复杂的重复性作业。
可以在 Azure 内部或外部运行计划作业。一个很好的内部运行作业的例子是,假设您希望同步您的 Twitter 更新,或者您希望定期从提要中获取数据并更新到您的 Azure 存储中。
以下是可以使用计划作业的一些用例
- 定期收集数据并更新到 Azure。
- 日志清理。
- 运行作业以进行例行备份或数据归档。
- 运行一些应用程序维护任务。
背景
强烈建议阅读并理解下面提到的 CodeProject API Wrapper 文章,因为本项目使用了该 Wrapper。
https://codeproject.org.cn/Articles/878994/Csharp-CodeProject-API-Wrapper
创建 Azure Mobile Service
创建一个 Azure 移动项目并部署和测试。
1) 登录 Windows Azure 门户,点击“新建”,然后导航到“Mobile services” -> “创建”。
2) 输入 URL,然后选择或创建一个数据库,尽管我们不在此项目中为此使用 SQL Azure 数据库。选择 .NET 作为后端,然后继续创建 Azure Mobile Service。
3) 您应该看到类似以下的屏幕。您可以选择 HTML/JavaScript 选项,并通过点击“创建新的 HTML 应用”链接下载代码。
下载并打开解决方案后,您应该会看到一个移动服务的基本框架。我们关心的是计划作业的代码。您可以复制我在示例项目下载中提供的所有文件。复制计划作业的源文件,然后复制并打开示例项目的 web.config,并将 appsettings 复制粘贴到您的项目中。
注意 – App settings 包含所有客户端 ID 和密钥(CodeProject 测试密钥),因此您可以开始测试。
创建计划作业
让我们创建一个简单的作业,该作业向 CodeProject API 发送 HTTP 请求以获取文章并根据我的 API 进行通知,并进行服务日志记录。
public class CodeProjectMyArticlesJob : ScheduledJob { // The server base address private const string baseUrl = "https://api.codeproject.com/"; // this will hold the Access Token returned from the server. static string _accessToken; /// <summary> /// Just Log the articles that we are reading through. /// </summary> /// <returns></returns> public async override Task ExecuteAsync() { try { _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"]; var codeProjectApiWrapper = new CodeProjectApiWrapper(baseUrl, _accessToken); var articles = await codeProjectApiWrapper.GetMyArticles(); // My Articles foreach (var article in articles) { Services.Log.Info(string.Format("Title: {0}", article.title)); foreach (var author in article.authors) { Services.Log.Info(string.Format("Authors: {0}", author.name)); } } } catch (Exception ex) { Services.Log.Info(ex.ToString()); } } }
以下是 Azure Mobile Services 中日志的截图。
以下代码片段将向 CodeProject API 发送 HTTP GET 请求,并获取基于您的 CodeProject 帐户的特定帐户访问令牌的所有通知。
public class CodeProjectMyNotificationJob: ScheduledJob { // The server base address private const string baseUrl = "https://api.codeproject.com/"; // this will hold the Access Token returned from the server. static string _accessToken; /// <summary> /// Just Log in if there’s any new Notifications. /// </summary> /// <returns></returns> public async override Task ExecuteAsync() { try { _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"]; var codeProjectApiWrapper = new CodeProjectApiWrapper(baseUrl, _accessToken); // My Notifications Services.Log.Info("Reading all my Notifications"); var notificationRoot = await codeProjectApiWrapper.GetMyNotifications(); var notifications = notificationRoot.notifications; if (notifications.Count == 0) Services.Log.Info("There are no new Notifications"); else { foreach (var notification in notifications) { Services.Log.Info(string.Format("Subject: {0}", notification.subject)); Services.Log.Info(string.Format("Notification Date: {0}", notification.notificationDate)); } } } catch (Exception ex) { Services.Log.Info(ex.ToString()); } } }
这是 CodeProject 通知在主网站中显示的快照,并且在 Azure Mobile 服务日志中也显示了相同的内容。
通过 SMS 发送 CodeProject 通知
现在,让我们稍微修改一下之前的通知代码,为每个通知发送带有主题行的 SMS。
为了在计划程序中正确发送 SMS,我们将使用 Twilio SMS 库。请参阅我之前关于物联网设备 VOIP 和 SMS/MMS 解决方案的文章,以更深入地了解 Twilio。
https://codeproject.org.cn/Articles/877833/VOIP-and-SMS-MMS-solution-for-IOT-devices
让我们构建一个小型计划程序,它可以读取 CodeProject 通知并触发 SMS。请注意,我们在这里使用与之前几乎相同的逻辑。我们只是想发送 SMS,而不是仅仅进行服务日志记录。
以下是发送 SMS 的步骤。
- 安装 Twilio C# 客户端库。您可以在 Nuget 包管理器中搜索“Twilio”并进行安装。
- 更新配置文件,以包含 Twilio 帐户 SID、令牌等。要使用 Twilio 发送 SMS,您需要设置一个专用的 Twilio 号码,或者可以迁移您的号码。因此,我们有一个名为“TwilioNumber”的应用程序配置键。然后,您还需要一个用于发送 SMS 的号码的键。
- 使用 Account SID 和 Account Key 创建 TwilioRestClient 实例。
- 发送 SMS 的代码只需一行,通过调用 TwilioRestClient 实例的 SendMessage 方法,传入发件人号码、收件人号码以及要发送的消息(我们将消息编码为通知日期和通知主题行)。
public class CodeProjectMyNotificationWithTwilioSmsJob: ScheduledJob { // The server base address private const string BaseUrl = "https://api.codeproject.com/"; // this will hold the Access Token returned from the server. static string _accessToken; /// <summary> /// Just Log in if there’s any new Notifications. /// </summary> /// <returns></returns> public async override Task ExecuteAsync() { try { _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"]; // set our AccountSid and AuthToken string accountSid = ConfigurationManager.AppSettings["AccountSid"]; string authToken = ConfigurationManager.AppSettings["AuthToken"]; string smsToSendNumber = ConfigurationManager.AppSettings["SmsToSendNumber"]; string twilioNumber = ConfigurationManager.AppSettings["TwilioNumber"]; // instantiate a new Twilio Rest Client with the Account SID and Token var twilioClient = new TwilioRestClient(accountSid, authToken); var codeProjectApiWrapper = new CodeProjectApiWrapper(BaseUrl, _accessToken); // My Notifications Services.Log.Info("Reading all my Notifications"); var notificationRoot = await codeProjectApiWrapper.GetMyNotifications(); var notifications = notificationRoot.notifications; if (notifications.Count == 0) Services.Log.Info("There are no new Notifications"); else { foreach (var notification in notifications) { var message = string.Format("{0} - {1}", notification.notificationDate, notification.subject); twilioClient.SendMessage( twilioNumber, // From number, must be an SMS-enabled Twilio number smsToSendNumber, // To number is the phone which you wish the SMS. message); // message content } } } catch (Exception ex) { Services.Log.Info(ex.ToString()); } } }
发布 Azure Mobile Service
您可以编译项目,一旦一切构建成功,就可以开始查看如何部署 Azure Mobile Service。
- 右键单击项目并选择“发布”选项,这将打开一个类似以下的窗口。选择发布目标的一种非常简单的方法是第一个选项。
2) 当您为发布目标选择第一个选项时,它会允许您登录 Windows Azure,以便您可以选择已创建的现有移动服务。
3) 当您在步骤 2 中单击“确定”按钮时,您将看到以下屏幕,其中显示了服务器和发布凭据的所有信息。您可以单击“验证连接”来检查一切是否正常且已准备好发布。
点击下一步按钮,会出现如下窗口。您无需执行任何操作,只需保留默认选择。
点击下一步,会出现最终窗口,您可以在其中预览将要发布的内容,然后点击发布按钮,这将发布您的 Azure Mobile Service。
创建计划作业
现在我们已经发布了 Azure Mobile Service,是时候创建计划作业并运行它们,然后查看结果了。
1) 在您的 Azure Mobile Service 中选择“Scheduler”选项。
2) 指定作业名称。作业名称就是您创建的计划作业类名,以“Job”结尾。例如,如果我们创建了一个名为“CodeProjectMyArticlesJob”的类,那么作业名称就应该是“CodeProjectMyArticles”。
选择“On demand”(按需)选项,以便我们可以手动运行并立即查看结果。
3) 您应该看到类似以下的屏幕,其中按需作业的状态设置为“Disabled”(禁用)。
运行计划作业
现在我们已经创建了一个计划作业,是时候运行了。只需点击下面的“Run Once”(立即运行)按钮,它将触发计划程序来运行作业。
验证计划作业响应
现在是时候验证服务日志以查看上述计划作业的输出,以获取 CodeProject My API 文章。您应该看到类似以下的输出。
服务日志目前显示了我发布在 CodeProject 上的所有文章。
关注点
我对新的 Scheduler 感到非常兴奋。现在我们有很多选项可以执行后台作业。当然,我每天都在 Azure 上玩和学习很多东西。
我只是惊叹于创建强大计划作业的简单性和易用性。好吧,我无话可说。我对新的 Azure 功能印象深刻。
历史
版本 1.0 - 发布了文章的初始版本,解释了什么是计划作业,如何在 Azure Mobile Service 中创建计划作业,以及如何在 Azure 上部署和运行它。- 2015/02/23