Part 3: Azure Mobile Services: What you need to know to get started with Notification Hub

This tutorial series takes you through how Azure Mobile Services provides Mobile-Backend-As-A-Service by discussing various features and basics of how to get started.

Part 1: How Azure Mobile Services enable your Cloud First Mobile First World
Part 2: Azure Mobile Services: What you need to know to get started with Storage Services



Push notifications have become an integral component of any modern mobile application. Notifications play a key role in building engagement for consumer apps and utility for enterprise apps. The most important features of Azure Notification Hub is aligned with the features of Mobile Services in general which include: easy to use, multiplatform support, scaled out infrastructure and most importantly can be integrated as an enhancement to any mobile backend (cloud or on-prem). In this post, I will discuss how Notification Hub can be integrated with your mobile backend and how it can be used with your app.



First things first, let us discuss the schematic representation (shown above) of how the process works. There are 3 main entities:

  • The App Backend: This can be any platform – .NET, PHP, Java, Node, etc.
  • The Platform Notification Service: This is platform specific: Apple Push Notification Service (APNS), Google Cloud Messaging (GCM) and Windows Push Notification Service (WPNS) 
  • Client App: This is your handheld device which can be IOS, Android, Windows Phone or Windows Store App.

As shown, the diagram looks fairly simplistic but it does quite a lot in the backend to abstract the complexity of it which is irrelevant to the business logic. For example: Multiple interfaces for multi platform support, scale-out features which require device token refresh and minimal latency for notification delivery is non-trivial and monitoring/tracking and aggregating the outcomes of millions of notification is quite challenging.

So the basic idea is to exchange tokens between the PNS, app backend and device (Step 1 & 2). Once a notification needs to be sent, the app backend sends it to the PNS(Step 3) and the PNS then relays it to the device (Step 4). This is broadcasting a notification to all registered users/devices. But often, that is not the only use case for notifications.

Getting Started with Notification Hub takes you through the entire series of steps to show you how the registration process takes place between the device, the PNS and the backend. It then takes you through the code that simply sends the notification to the user. Just for clarity, these are the simple code walk through after the registration process has taken place:

   1: // On App launch, the app needs to register to the notification hub and the following 3 lines of code does exactly that
   3: var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
   5: var hub = new NotificationHub("<hub name>", "<connection string with listen access>");              
   7: var result = await hub.RegisterNativeAsync(channel.Uri);

On the server backend, the following code will be used to send the notification:

   1: //In the Server backend, it is simply sending a broadcast notification to all registered devices
   3: NotificationHubClient hub = NotificationHubClient
   4:         .CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
   6: var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>";
   8: await hub.SendWindowsNativeNotificationAsync(toast);

In most cases, notifications is more than just a broadcast message. Think about a weather app, where a notification for a storm needs to be sent only to a fixed set of users in a geography, likewise in a news app where in you would want to send breaking news in a particular category to user interest groups. On the other spectrum, a chat app or an email app need notifications on a per user basis.

In order to accomplish these scenarios, users need to be segmented in the server side. In order to add a further degree of personalization, such as language preference, device versions, currency or metric preference, a level of filtering is required at the client/device end which will ensure the received notification be personalized as per user preference.

These can be accomplished by the use of tags (server side) and templates (client side) as described below.



Tags: Tags are essentially a means of segmenting users or interest groups. As seen in the diagram above, tags are essentially coded in the server side. Each notification that will be sent will be tagged to target specific users. There are essentially 2 key elements in this process:

    • Every time the app is launched, the app needs to be registered with the Notification Hub. During app registration, the tags are also registered along with the device handle which is stored in the PNS.
    • The App backend will tag a notification and send it to the PNS. The PNS matches the tag with the device handle and relays the notification to the segment of the users with the matching tag

Templates: Templates allow you to specify how the notification will be consumed by the client device. As you can see in the diagram above, some devices prefer to receive the message in Yen or Euro or Dollar and that is taken care at the client side using templates.

Let us have a look at how these are coded. We will begin with registering the tags from the client end.

   1: //This basically has 4 steps:
   2: //1. Create a notification hub
   3: //2. Request for a channel
   4: //3. Set tags
   5: //4. Register your channel and tags as the device handle
   7: NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(
   8:     "Endpoint=sb://<notificaiton hub name space>;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=<notification hub full key>",
   9:     "<notification hub name>"
  10: );
  12: // Get a Push Notification channel from the PushNotificationChannelManager
  13: var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
  15: // Set the tags
  16: string[] tagsToSubscribeTo = { "sports", "politics" };
  18: // Register with the Notification Hub, passing the push channel uri and the string array of tags
  19: await hub.RegisterNativeAsync(channel.Uri, tagsToSubscribeTo);

Once the device registers its tags, let us send a push notification from the backend to specific tags:

   1: // Create a hub client using the DefaultFullSharedAccessSignature
   3: NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(
   4:     "Endpoint=sb://<your service bus name>;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=<your DefaultFullSharedAccessSignature>",
   5:     "<notification hub name>"
   6: );
   8: // Since we are using native notifications, we have to construct the payload in the format
   9: // the service is expecting. The example below is for sending a Toast notification on Windows 8
  10: string toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">{0}</text></binding></visual></toast>";
  12: // This call essentialy broadcasts a push notification to ALL Windows 8 devices that are registered with the service
  13: // and registered to receive "sports" notifications
  14: var payload = string.Format(toastTemplate, "Messi scored a goal against Brazil in the World Cup Finals");
  15: hub.SendWindowsNativeNotificationAsync(payload,"sports");

That's it, you are now able to successfully send notifications to specific users with specific tags. This process and the code is in this video here.

Now let us look at the personalization of the notification or how the notification should be consumed by the user using templates. Let us begin with the client end:

   1: //So, this is similar to the previous registration step as in tag, only difference being using a template registration rather than native registration
   2: //These templates are xml tokens. Essentially the idea is to tokenize the notification to personalize/localize the property received
   3: //Note: the backend has to only send $(News}_{0}) which is the property 
   4: // As in the previous case, categories are the tags that are registered for
   6: public async Task SubscribeToCategories(string locale, IEnumerable<string> categories)
   7: {
   8:     var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
   9:     var template = String.Format(@"<toast><visual><binding template=""ToastText01""><text id=""1"">$(News_{0})</text></binding></visual></toast>", locale);
  11:     await hub.RegisterTemplateAsync(channel.Uri, template, "newsTemplate", categories);
  12: }

Now that the client end has registered with templates, let us see how a notification will be send from the backend:

   1: //We need to have a platform agnostic dictionary where we define 3 properties
   2: //We send a Template notification rather than a native notification
   3: // Also note, once this notificaiton is received at the client, the property will filter out based on $(News_${0}) and display the notification in the localized/personalized format
   6: var hub = NotificationHubClient.CreateClientFromConnectionString("<connection string>", "<hub name>");
   7: var notification = new Dictionary<string, string>() {
   8:                         {"News_English", "World News in English!"},
   9:                         {"News_French", "World News in French!"},
  10:                         {"News_Mandarin", "World News in Mandarin!"}};
  11: await hub.SendTemplateNotificationAsync(notification, "World");

Again, this entire process is clearly explained in this video here.

Lets have a look at a few specific use cases for Tags:

  • Notify a single user: This is a special case for using tags. When the device registers itself with the notification hub, it also registers a user id. From the back end, when a notification is send particularly for a single user using the user id as a tag, this tag is matched with the device handle and the notification is send accordingly. This is used for email apps, chat apps, etc whenever there is a requirement of single user notification.
  • Notify in batches: Often broadcasting messages are compute intensive depending upon the number of users, which may cause a delay in sending the notifications and will also be expensive to ensure the requisite compute resources. In order to prevent this, the notifications can be send in batches. This can be implemented as a special case of using tags. Each device while registration can be assigned a tag with the batch number. The notification will be send to a batch at a time using the tag number. This reduces compute resource utilization, latency and more importantly reduces costs.
  • Geo-Targeting: This is a special usage of tags. Geo-Targeting is very popular these days in retail and weather apps. Promotional notifications can be sent based on proximity to stores and likewise, weather alerts can be sent based on geographic location. The basic idea is to use platform specific services such as reverse geo coding services from Bing, Google or Yahoo. The location is encoded in a tag and registered. Now the push notification is sent to the notification to the ‘geo’ tag.

Some best practices using Notification:

  • Use tags to define batch of users for broadcasting. This will ensure optimum use of compute resources
  • Use templates for personalization/localization rather than defining extensive tags to implement the same functionality
  • Be ethical and cognizant of battery consumption of client device due to geo-tagging or repeated registration
  • Use SignalR and Service Bus to extend push capabilities to support enterprise scenarios like deliver acknowledgement, end-to-end encryption, audit, etc


The basic idea of this post is to get you started on Push Notifications using Azure Mobile Services. We started by discussing how to send a broadcast notification across all devices, platforms, users. Then we discussed concepts of tags and templates which provide the level of abstraction allowing us to segment our users (using tags in the server end) and providing  the required level of personalization or localization (using templates in the client end). In the next tutorials we will discuss authentication using Azure Mobile Services. Stay tuned and reach out to me @AdarshaDatta.

Comments (0)

Skip to main content