Overview
This topic shows you how to use Azure Notification Hubs to broadcast breaking news notifications to a Windows Store or Windows Phone 8.1 (non-Silverlight) app. If you are targeting Windows Phone 8.1 Silverlight, refer to the Windows Phone version.
After you've completed this process, you can register for the breaking news categories that you are interested in, and you'll receive push notifications for those categories only. This scenario is common for many apps (for example, RSS readers or apps for music fans) where notifications must be sent to groups of users who have declared interest in them.
You can enable broadcast scenarios by including one or more tags when you create a registration in the notification hub. When notifications are sent to a tag, all devices that have registered for the tag receive the notification. Because tags are simply strings, they do not have to be set up in advance. For more information about tags, see Notification Hubs routing and tag expressions.
Note
Windows Store and Windows Phone project versions 8.1 and earlier are not supported in Visual Studio 2017. For more information, see Visual Studio 2017 Platform Targeting and Compatibility.
Prerequisites
This topic builds on the app that you created in Get started with Notification Hubs. Before you start this tutorial, you must complete Get started with Notification Hubs.
Add category selection to the app
The first step is to add UI elements to your existing main page so that users can select categories to register. The selected categories are stored on the device. When the app starts, a device registration is created in your notification hub, with the selected categories as tags.
Open the MainPage.xaml project file, and then copy the following code in the Grid element:
<Grid> <Grid.RowDefinitions> <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" HorizontalAlignment="Center"/> <ToggleSwitch Header="World" Name="WorldToggle" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center"/> <ToggleSwitch Header="Politics" Name="PoliticsToggle" Grid.Row="2" Grid.Column="0" HorizontalAlignment="Center"/> <ToggleSwitch Header="Business" Name="BusinessToggle" Grid.Row="3" Grid.Column="0" HorizontalAlignment="Center"/> <ToggleSwitch Header="Technology" Name="TechnologyToggle" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center"/> <ToggleSwitch Header="Science" Name="ScienceToggle" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Center"/> <ToggleSwitch Header="Sports" Name="SportsToggle" Grid.Row="3" Grid.Column="1" HorizontalAlignment="Center"/> <Button Name="SubscribeButton" Content="Subscribe" HorizontalAlignment="Center" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" Click="SubscribeButton_Click"/> </Grid>Right-click the Shared project, add a new class named Notifications, add the public modifier to the class definition, and then add the following using statements to the new code file:
using Windows.Networking.PushNotifications; using Microsoft.WindowsAzure.Messaging; using Windows.Storage; using System.Threading.Tasks;Copy the following code to the new Notifications class:
private NotificationHub hub; public Notifications(string hubName, string listenConnectionString) { hub = new NotificationHub(hubName, listenConnectionString); } public async Task<Registration> StoreCategoriesAndSubscribe(IEnumerable<string> categories) { ApplicationData.Current.LocalSettings.Values["categories"] = string.Join(",", categories); return await SubscribeToCategories(categories); } public IEnumerable<string> RetrieveCategories() { var categories = (string) ApplicationData.Current.LocalSettings.Values["categories"]; return categories != null ? categories.Split(','): new string[0]; } public async Task<Registration> SubscribeToCategories(IEnumerable<string> categories = null) { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); if (categories == null) { categories = RetrieveCategories(); } // Using a template registration to support notifications across platforms. // Any template notifications that contain messageParam and a corresponding tag expression // will be delivered for this registration. const string templateBodyWNS = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>"; return await hub.RegisterTemplateAsync(channel.Uri, templateBodyWNS, "simpleWNSTemplateExample", categories); }This class uses the local storage to store the categories of news that this device must receive. Instead of calling the RegisterNativeAsync method, call RegisterTemplateAsync to register for the categories by using a template registration.
Because you might want to register more than one template (for example, one for toast notifications and one for tiles), also provide a template name (for example, "simpleWNSTemplateExample"). You name the templates so that you can update or delete them.
Note
If a device registers multiple templates with the same tag, an incoming message that targets the tag causes multiple notifications to be delivered to the device (one for each template). This behavior is useful when the same logical message must result in multiple visual notifications (for example, showing both a badge and a toast in a Windows Store application).
For more information, see Templates.
In the App.xaml.cs project file, add the following property to the App class:
public Notifications notifications = new Notifications("<hub name>", "<connection string with listen access>");You use this property to create and access a Notifications instance.
In the code, replace the
<hub name>and<connection string with listen access>placeholders with your notification hub name and the connection string for DefaultListenSharedAccessSignature, which you obtained earlier.Note
Because credentials that are distributed with a client app are not usually secure, distribute only the key for listen access with your client app. With listen access, your app can register for notifications, but existing registrations cannot be modified, and notifications cannot be sent. The full access key is used in a secured back-end service for sending notifications and changing existing registrations.
In the MainPage.xaml.cs project file, add the following line:
using Windows.UI.Popups;In the MainPage.xaml.cs project file, add the following method:
private async void SubscribeButton_Click(object sender, RoutedEventArgs e) { 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"); var result = await ((App)Application.Current).notifications.StoreCategoriesAndSubscribe(categories); var dialog = new MessageDialog("Subscribed to: " + string.Join(",", categories) + " on registration Id: " + result.RegistrationId); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); }This method creates a list of categories and uses the Notifications class to store the list in the local storage. It also registers the corresponding tags with your notification hub. When the categories are changed, the registration is re-created with the new categories.
Your app can now store a set of categories in local storage on the device. The app registers with the notification hub whenever users change the category selection.
Register for notifications
In this section, you register with the notification hub on startup by using the categories that you've stored in local storage.
Note
Because the channel URI that's assigned by the Windows Notification Service (WNS) can change at any time, you should register for notifications frequently to avoid notification failures. This example registers for notification every time that the app starts. For apps that you run frequently (more than once a day), you can probably skip registration to preserve bandwidth if less than a day has passed since the previous registration.
To use the
notificationsclass to subscribe based on categories, open the App.xaml.cs file, and then update the InitNotificationsAsync method.// *** Remove or comment out these lines *** //var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); //var hub = new NotificationHub("your hub name", "your listen connection string"); //var result = await hub.RegisterNativeAsync(channel.Uri); var result = await notifications.SubscribeToCategories();This process ensures that when the app starts, it retrieves the categories from local storage and requests registration of these categories. You created the InitNotificationsAsync method as part of the Get started with Notification Hubs tutorial.
In the MainPage.xaml.cs project file, add the following code to the OnNavigatedTo method:
protected override void OnNavigatedTo(NavigationEventArgs e) { var categories = ((App)Application.Current).notifications.RetrieveCategories(); if (categories.Contains("World")) WorldToggle.IsOn = true; if (categories.Contains("Politics")) PoliticsToggle.IsOn = true; if (categories.Contains("Business")) BusinessToggle.IsOn = true; if (categories.Contains("Technology")) TechnologyToggle.IsOn = true; if (categories.Contains("Science")) ScienceToggle.IsOn = true; if (categories.Contains("Sports")) SportsToggle.IsOn = true; }This code updates the main page, based on the status of previously saved categories.
The app is now complete. It can store a set of categories in the device local storage that's used to register with the notification hub when users change the category selection. In the next section, you define a back end that can send category notifications to this app.
Send tagged notifications
In this section, you send breaking news as tagged template notifications from a .NET console app.
If you are using the Mobile Apps feature of Microsoft Azure App Service, refer to the Add push notifications for Mobile Apps tutorial, and select your platform at the top.
If you want to use Java or PHP, refer to How to use Notification Hubs from Java or PHP. You can send notifications from any back end by using the Notification Hubs REST interface.
If you created the console app for sending notifications when you completed Get started with Notification Hubs, skip steps 1-3.
In Visual Studio, create a new Visual C# console application:

On the Visual Studio main menu, select Tools > Library Package Manager > Package Manager Console and then, in the console window, enter the following string:
Install-Package Microsoft.Azure.NotificationHubsSelect Enter.
This action adds a reference to the Azure Notification Hubs SDK by using the Microsoft.Azure.Notification Hubs NuGet package.Open the Program.cs file, and add the following
usingstatement:using Microsoft.Azure.NotificationHubs;In the
Programclass, add the following method, or replace it if it already exists:private static async void SendTemplateNotificationAsync() { // Define the notification hub. NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString( "<connection string with full access>", "<hub name>"); // Create an array of breaking news categories. var categories = new string[] { "World", "Politics", "Business", "Technology", "Science", "Sports"}; // Send the notification as a template notification. All template registrations that contain // "messageParam" and the proper tags will receive the notifications. // This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary<string, string> templateParams = new Dictionary<string, string>(); foreach (var category in categories) { templateParams["messageParam"] = "Breaking " + category + " News!"; await hub.SendTemplateNotificationAsync(templateParams, category); } }This code sends a template notification for each of the six tags in the string array. The use of tags ensures that devices receive notifications only for the registered categories.
In the preceding code, replace the
<hub name>and<connection string with full access>placeholders with your notification hub name and the connection string for DefaultFullSharedAccessSignature from the dashboard of your notification hub.In the Main method, add the following lines:
SendTemplateNotificationAsync(); Console.ReadLine();Build the console app.
Run the app and generate notifications
In Visual Studio, select F5 to compile and start the app.
The app UI provides a set of toggles that lets you choose the categories to subscribe to.
Enable one or more category toggles, and then click Subscribe.
The app converts the selected categories into tags and requests a new device registration for the selected tags from the notification hub. The registered categories are returned and displayed in a dialog box.

Send a new notification from the back end in one of the following ways:
- Console app: Start the console app.
Java/PHP: Run your app or script.
Notifications for the selected categories appear as toast notifications.

Next steps
In this article, you learned how to broadcast breaking news by category. Consider completing the following tutorial, which highlights another advanced Notification Hubs scenario:
- Use Notification Hubs to broadcast localized breaking news
This tutorial discusses how to expand the breaking news app to enable sending localized notifications.




