This topic shows you how to use the template feature of Azure Notification Hubs to broadcast breaking news notifications that have been localized by language and device. In this tutorial you start with the Windows Store app created in Use Notification Hubs to send breaking news. When complete, you will be able to register for categories you are interested in, specify a language in which to receive the notifications, and receive only push notifications for the selected categories in that language.
This tutorial walks you through these basic steps to enable this scenario:
- Template concepts
- The app user interface
- Building the Windows Store client app
- Send notifications from your back-end
There are two parts to this scenario:
- the Windows Store app allows client devices to specify a language, and to subscribe to different breaking news categories;
- the back-end broadcasts the notifications, using the tag and template feautres of Azure Notification Hubs.
Prerequisites
You must have already completed the Use Notification Hubs to send breaking news tutorial and have the code available, because this tutorial builds directly upon that code.
You also need Visual Studio 2012.
conceptsTemplate concepts
In Use Notification Hubs to send breaking news you built an app that used tags to subscribe to notifications for different news categories. Many apps, however, target multiple markets and require localization. This means that the content of the notifications themselves have to be localized and delivered to the correct set of devices. In this topic we will show how to use the template feature of Notification Hubs to easily deliver localized breaking news notifications.
Note: one way to send localized notifications is to create multiple versions of each tag. For instance, to support English, French, and Mandarin, we would need three different tags for world news: "world_en", "world_fr", and "world_ch". We would then have to send a localized version of the world news to each of these tags. In this topic we use templates to avoid the proliferation of tags and the requirement of sending multiple messages.
At a high level, templates are a way to specify how a specific device should receive a notification. The template specifies the exact payload format by referring to properties that are part of the message sent by your app back-end. In our case, we will send a locale-agnostic message containing all supported languages:
{
"News_English": "...",
"News_French": "...",
"News_Mandarin": "..."
}
Then we will ensure that devices register with a template that refers to the correct property. For instance, a Windows Store app that wants to receive a simple toast message will register for the following template:
<toast>
<visual>
<binding template=\"ToastText01\">
<text id=\"1\">$(News_English)</text>
</binding>
</visual>
</toast>
Templates are a very powerful feature you can learn more about in our Notification Hubs Guidance article. A reference for the template expression language is in our Notification Hubs How-To for Windows Store.
App uiThe app user interface
We will now modify the Breaking News app that you created in the topic Use Notification Hubs to send breaking news to send localized breaking news using templates.
In order to adapt your client apps to receive localized messages, you have to replace your native registrations (i.e. registrations that do you specify a template) with template registrations.
In your Windows Store app:
Change your MainPage.xaml to include a locale combobox:
<Grid Margin="120, 58, 120, 80"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" TextWrapping="Wrap" Text="Breaking News" FontSize="42" VerticalAlignment="Top"/>
<ComboBox Name="Locale" HorizontalAlignment="Left" VerticalAlignment="Center" Width="200" Grid.Row="1" Grid.Column="0">
<x:String>English</x:String>
<x:String>French</x:String>
<x:String>Mandarin</x:String>
</ComboBox>
<ToggleSwitch Header="World" Name="WorldToggle" Grid.Row="2" Grid.Column="0"/>
<ToggleSwitch Header="Politics" Name="PoliticsToggle" Grid.Row="3" Grid.Column="0"/>
<ToggleSwitch Header="Business" Name="BusinessToggle" Grid.Row="4" Grid.Column="0"/>
<ToggleSwitch Header="Technology" Name="TechnologyToggle" Grid.Row="2" Grid.Column="1"/>
<ToggleSwitch Header="Science" Name="ScienceToggle" Grid.Row="3" Grid.Column="1"/>
<ToggleSwitch Header="Sports" Name="SportsToggle" Grid.Row="4" Grid.Column="1"/>
<Button Content="Subscribe" HorizontalAlignment="Center" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" Click="Button_Click" />
</Grid>
App uiBuilding the Windows Store client app
- In your Notifications class, add a locale parameter to your StoreCategoriesAndSubscribe and SubscribeToCateoriesmethods.
public async Task StoreCategoriesAndSubscribe(string locale, IEnumerable<string> categories) { ApplicationData.Current.LocalSettings.Values["categories"] = string.Join(",", categories); ApplicationData.Current.LocalSettings.Values["locale"] = locale; await SubscribeToCategories(locale, categories); } public async Task SubscribeToCategories(string locale, IEnumerable<string> categories) { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var template = String.Format(@"<toast><visual><binding template=""ToastText01""><text id=""1"">$(News_{0})</text></binding></visual></toast>", locale); await hub.RegisterTemplateAsync(channel.Uri, template, "newsTemplate", categories); }
Note that instead of calling the RegisterNativeAsync method we call RegisterTemplateAsync: we are registering a specific notification format in which the template depends on the locale. We also provide a name for the template ("newsTemplate"), because we might want to register more than one template (for instance one for toast notifications and one for tiles) and we need to name them in order to be able to update or delete them.Note that if a device registers multiple templates with the same tag, an incoming message targeting that tag will result in multiple notifications delivered to the device (one for each template). This behavior is useful when the same logical message has to result in multiple visual notifications, for instance showing both a badge and a toast in a Windows Store application. - Add the following method to retrieve the stored locale:
public string RetrieveLocale() { var locale = (string) ApplicationData.Current.LocalSettings.Values["locale"]; return locale != null ? locale : "English"; }
- In your MainPage.xaml.cs, update your button click handler by retrieving the current value of the Locale combobox and providing it to the call to the Notifications class, as shown:
var locale = (string)Locale.SelectedItem; var categories = new HashSet<string>(); if (WorldToggle.IsOn) categories.Add("World"); if (PoliticsToggle.IsOn) categories.Add("Politics"); if (BusinessToggle.IsOn) categories.Add("Business"); if (TechnologyToggle.IsOn) categories.Add("Technology"); if (ScienceToggle.IsOn) categories.Add("Science"); if (SportsToggle.IsOn) categories.Add("Sports"); await ((App)Application.Current).Notifications.StoreCategoriesAndSubscribe(locale, categories); var dialog = new MessageDialog(String .Format("Locale: {0}; Subscribed to: {1}", locale, string.Join(",", categories))); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync();
- Finally, in your App.xaml.cs file, make sure to update your call to the Notifications singleton in the OnLaunched method:
Notifications.SubscribeToCategories(Notifications.RetrieveLocale(), Notifications.RetrieveCategories());
Send localized notificationsSend localized notifications from your back-end
In your back-end app, you now have to switch to sending template notifications instead of native payloads. This will simplify the back-end code as you will not have to send multiple payloads for the different platforms.
When you send template notifications you only need to provide a set of properties, in our case we will send the set of properties containing the localized version of the current news, for instance:
{
"News_English": "World News in English!",
"News_French": "World News in French!",
"News_Mandarin": "World News in Mandarin!"
}
This section shows how to send notifications in two different ways:
- using a console app
- using a Mobile Services script
The included code broadcasts to both Windows Store and iOS devices, since the backend can broadcast to any of the supported devices.
To send notifications using a C# console app
We will simply modify your SendNotificationAsync method by sending a single template notification.
var hub = NotificationHubClient.CreateClientFromConnectionString("<connection string>", "<hub name>");
var notification = new Dictionary<string, string>() {
{"News_English", "World News in English!"},
{"News_French", "World News in French!"},
{"News_Mandarin", "World News in Mandarin!"}};
await hub.SendTemplateNotificationAsync(notification, "World");
Note that this simple call will deliver the correct localized piece of news to all your devices, irrespective of the platform, as your Notification Hub builds and delivers the correct native payload to all the devices subscribed to a specific tag.
Mobile Services
In your Mobile Service scheduler, overwrite your script with:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<hub name>', '<connection string with full access>');
var notification = {
"News_English": "World News in English!",
"News_French": "World News in French!",
"News_Mandarin", "World News in Mandarin!"
}
notificationHubService.send('World', notification, function(error) {
if (!error) {
console.warn("Notification successful");
}
});
Note how in this case there is no need to send multiple notifications for different locales and platforms.
Source from
http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-windows-store-dotnet-send-localized-breaking-news/
No comments :
Post a Comment