Visual Studio から Console Projects を Azure WebJobs に発行できるようになったので、試してみました。Visual Studio 2013 Update 3 + Azure SDK 2.4 をインストールする必要があります。
以前の記事と同様に、WebJobs と SendGrid の SDK を使って、発生した例外のメッセージを Queue ストレージに追加すると、メールでアラートが送信され、Table ストレージにログを記録するシナリオで確認します。
WebJobs SDK のバージョンが 0.3.1-beta に更新されており、その間に名前空間やクラス名が変更される大きな変更がはいっているので、コードを書き直しました。新旧バージョンの変更点については、こちらのサイトが参考になります。
Console Projects の作成
Visual Studio のテンプレートから「Microsoft Azure WebJob」を選択し、コンソールアプリを作成します。NuGet から WebJobs と SendGrid の SDK をインストールします。
- Install-Package Microsoft.Azure.Jobs -Pre
- Install-Package Sendgrid
ジョブの作成
最新の WebJobs SDK では、SendAlert メソッドの引数に QueueTrigger と CloudTable を使います。キューから受け取ったメッセージを SendGrid でメール送信し、テーブルストレージにログを書き込みます。
#Program.cs public class ErrorLog : TableEntity { public string Message { get; set; } } class Program { static void Main() { new JobHost().RunAndBlock(); } public static void SendAlert([QueueTrigger("error")] string message, [Table("ErrorLog")] CloudTable table) { // SendGridを利用して、メールでアラート通知 var sendGridUserName = "username"; var sendGridPassword = "password"; var to = new List<string>(); to.Add("tony@gmail.com"); var from = "admin@gooner.com"; var smtpapi = new Header(); smtpapi.SetTo(to); var email = new SendGridMessage(); email.AddTo(from); email.From = new MailAddress(from, "システム管理者"); email.Subject = "アラート"; email.Text = message; email.Headers.Add("X-Smtpapi", smtpapi.JsonString()); var credentials = new NetworkCredential(sendGridUserName, sendGridPassword); var web = new Web(credentials); web.Deliver(email); // テーブルストレージにエラーログを書く var partitionKey = "error"; var rowKey = String.Format("{0:D19}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks); var operation = TableOperation.Insert(new ErrorLog { PartitionKey = partitionKey, RowKey = rowKey, Message = message }); table.Execute(operation); } }
接続文字列の名称も、AzureJobsDashboard と AzureJobsStorage に変更されていますので、注意してください。
#App.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="AzureJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx"/> <add name="AzureJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx"/> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" /> </startup> </configuration>
Azure WebJobs として発行する
プロジェクトを右クリックして、Azure WebJobs として発行します。WebJob 実行モードは、「継続的に実行」を選択します。
次に、Azure Web Sites のサイト名とリージョンを指定して、新規にサイトを立ち上げます。
上記の手順で Azure WebJobs が動作しますが、ひとつ注意点があります。Azure 管理ポータルから WebJobs の実行ログを見るためには、接続文字列に「AzureJobsDashboard」を追加する必要があります。
まとめ
Visual Studio からダイレクトに Azure WebJobs として発行できるので、コンソールアプリをビルドして zip ファイルに変換してポータルにアップロードする手間がなくなりました。Visual Studio と Azure SDK が統合されて、ますます便利になっていきますね。