1月に、マルチデバイス向けにPush通知を提供するWindows Azure通知ハブでご紹介したサービス バス通知ハブがアップデートされています。
従来のものと比べ、共有アクセスシークレット(SAS)キー長が長くなり、セキュリティ面で強化されただけでなく、APIも新しくなっています。
前回の記事から変更された点をご紹介します。
-
クライアント側の変更
通知を受け取るWindows ストアアプリの記述もいくつか変更になっています。
事前の準備として、最新版のライブラリをダウンロードしておきます。
さらに、通知ハブも新しく作り直す必要があります。
事前準備が完了したらコードの記述です。
最初に、以下の宣言を追加しておきます。
using Windows.Networking.PushNotifications;
そして、接続文字列の指定方法が変わっております。
接続文字列の指定は以下のように変更されています。
var cn =
ConnectionString.CreateUsingSharedAccessSecretWithListenAccess(
new Uri(“sb://yournamespace.servicebus.windows.net/”),
“==Relpace to your Listen Access Secret==”);
notificationHub = new
NotificationHub(“yourhubname”, cn);
今まではサービス バスの名前空間のみを指定しておりましたが、エンドポイントのURIを指定する形式に変更されています。
次に通知ハブの初期化も以下のように変更されています。
async Task InitializeNotificationsAsync(){
var channel = await
PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();await notificationHub.RefreshChannelUriAsync(channel.Uri);
await notificationHub.CreateTemplateRegistrationAsync(
BuildToastImageAndText02(), “yourtemplate”);
}
XmlDocument BuildToastImageAndText02(){
var template =
ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02);
var imgNode = template.SelectSingleNode(“//image[@id=’1′]”) as XmlElement;
if (imgNode != null) imgNode.Attributes[1].NodeValue = “$(img)”;
var textNode = template.SelectSingleNode(“//text[@id=’1′]”) as XmlElement;
if (textNode != null) textNode.InnerText = “$(caption)”;
var textNode2 = template.SelectSingleNode(“//text[@id=’2′]”) as XmlElement;
if (textNode2 != null) textNode2.InnerText = “$(msg)”;
return template;
}
ついでに、テンプレートも変えていますが、本質的ではありませんね。
これでクライアント側の変更は完了です。 -
送信側アプリケーションの変更
さて、続いてメッセージの送信側を変更しましょう。
送信側も最新のライブラリをNuGetより導入しておきましょう。
送信側の変更点は、基本的には接続文字列だけです。
以下に送信側アプリケーションのコードを示しておきます。
protected void btnSendMessage_Click(object sender, EventArgs e)
{
string connectionString =
ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(
new Uri(“sb://yournamespace.servicebus.windows.net/”)
, NotificationHubDescription.DefaultFullSasRuleName,
“==Relpace to your Full Access Secret==”);
var hubClient
= NotificationHubClient.CreateClientFromConnectionString(connectionString, ” yourhubname”);
hubClient.SendTemplateNotification(
CreateToastImageAndText02(“hogehoge.jpg”,
“Caption”, txtMessageBody.Text));
txtMessageBody.Text = “”;
}
private Dictionary<string, string>
CreateToastImageAndText02(string imgUri,string caption,string messagebody){
return new Dictionary<string, string>
{
{“img”,imgUri},
{“caption”,caption } ,
{“msg”,messagebody }
};
}
これで修正は完了です。
それではデバッグを実行して送信してみましょう。
送信のアプリで文字を入力し、送信ボタンをクリックします。
以下のようにメッセージが表示されます。
このように、日本語も通知されるようになりました。
ぜひ、この機会にご利用されてみてはいかがでしょう?
Comments are closed here.