This is part 1 of a 3 part series where we will get to know how Notification Hubs work and why they are a cool feature of Windows Azure.
You can get the source code of the projects in this blog post here: http://github.com/sabbour/notificationhubw8
Push Notifications you say?
Most users of mobile applications now expect to be notified when something of interest to them happens in the app, instead of having to regularly check. So if you are creating a mobile app, chances are you will need to use push notifications functionality sooner or later.
But real world apps have complex needs, whether you are pushing to multiple platforms, requiring personalization and localization of the pushed messages, handling different mobile app versions and most importantly scale.
Challenges of push notifications
Push notifications are not as trivial to implement as they may sound, an end-to-end solution requires a lot of backend code that you would have to write and maintain.
Platform dependency
Each push notification service (PNS) has different protocols (e.g., HTTP vs. TCP, xml payload vs. JSON payload) as well as different presentation formats and capabilities (tiles vs. toasts vs. badges).
Routing
A PNS provides you a way to send a message to a certain device, but doesn’t provide a way to do “broadcast” messages that reach multiple devices. If you need to send a message to multiple devices, such as a breaking news notification, or specific interest groups, such as people who are interested in “Sports” you would have to write that in your backend and maintain a registry associating device handles to interest groups/users.
Scale
Storing device handles (which expire), and broadcasting to millions of devices with low latency requires parallelization in both, the backend machines and the database, meaning high storage and machine costs.
Notification Hubs to the rescue!
Before diving into how Notification Hubs work (and diving into the code :) ) let’s compare how to send a push notification using your own backend vs using the Notification Hubs.
Push without Notification Hubs
- Client app requests a channel/unique identifier from the PNS.
- PNS replies with a unique identifier.
- Client sends its unique identifier to your application backend.
- Application backend stores/updates the unique identifier of the client.
- Application constructs a platform specific message, implements PNS protocol, contacts PNS to push a notification to the client.
Push with Notification Hubs
- Client app requests a channel/unique identifier from the PNS.
- PNS replies with a unique identifier.
- Client sends its unique identifier to the Notification Hub.
- Application contacts the Notification Hub to send push notifications.
- Notification Hub contacts the PNS to push a notification to the client.
Now why would the Notification Hubs scenario be better, you might ask:
- Application backend does not have to implement any PNS specific code, it uses the Notification Hub API to push messages.
- Application backend neither stores nor maintains device information, it is handled by the Notification Hub.
- Application can broadcast to millions of devices with a single call to the Notification Hub, instead of looping on the database and pushing one by one.
Let’s start!
Creating the Notification Hub
Login to the Windows Azure management portal, click on New, App Services, Service Bus, Notification Hub
Create a Windows 8 app
In Visual Studio, create a new Windows 8 application, then open the Package.appxmanifest file and turn on “Toast Capable”
In order to use push notifications, your app has to be associated with the Store. Right click on the project, go to Store, click on Associate App with the Store
Sign in with your store account then select an app (or reserve a new one) and continue with the wizard till the app is associated.
Configure the push notification settings in the Notification Hub
Go back to the management portal. and go to the Notification Hub configuration to enter the settings
You will need to get those from the Windows Store dev center under the Dashboard click Edit on your application name
Then go to Services
Then Live Services
Then Authenticating your service
Then pick the Package SID and Client Secret from the page, and put them back into the configuration on the portal
Back to the Windows 8 app
Now that the configuration for the Notification Hub is done, let’s write some code in the Windows 8 app to register with the Notification Hub.
- Add reference to WindowsAzure.Messaging.Managed NuGet to the project
- In App.xaml.cs, add instance of NotificationHub
- Get the ListenSharedAccessSignature connection string from the portal
- In OnLaunched() of App.xaml.cs, initialize the instance initialize the hub connection and get a push notification channel from the PushNotificationChannelManager then call RegisterNativeAsync and pass the channel URI
1: private NotificationHub hub;
1: hub = new NotificationHub("[notification hub name]", "Endpoint=sb://[servicebus name space].servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=[Your Listen Shared Access Key]");
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span id="lnum2" style="color: rgb(96, 96, 96);"> 2:</span> var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();</pre>
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;"><span id="lnum3" style="color: rgb(96, 96, 96);"> 3:</span> await hub.RegisterNativeAsync(channel.Uri);</pre>
Server side to push the notification
- Create an ASP.net MVC website, Web Foms website, Console app or a WPF app. I’ll create a console app.
- Add WindowsAzure.ServiceBus NuGet to the project
- Create a NotificationHubClient using the FullSharedAccessSignature connection string obtained from the portal
- Call SendWindowsNativeNotificationAsync to send the notification with the specified payload. In our case, we’re sending a Windows 8 toast notification. This will broadcast the message to all clients registered with this notification hub, with just one line of code!
1: NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span id="lnum2" style="color: rgb(96, 96, 96);"> 2:</span> <span style="color: rgb(0, 96, 128);">"Endpoint=sb://[service bus name space].servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=[notification hub full key]"</span>,</pre>
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;"><span id="lnum3" style="color: rgb(96, 96, 96);"> 3:</span> <span style="color: rgb(0, 96, 128);">"[notification hub name]"</span></pre>
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span id="lnum4" style="color: rgb(96, 96, 96);"> 4:</span> );</pre>
1: var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from server!</text></binding></visual></toast>";
<pre style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span id="lnum2" style="color: rgb(96, 96, 96);"> 2:</span> hub.SendWindowsNativeNotificationAsync(toast);</pre>
Closing
We’ve barely scratched the surface here, in my next post, I’ll show you how to use Tags and we will create a Breaking News application that will push news announcements to certain categories to millions of devices, just like how the Bing News app is doing it on its Windows Phone and Windows 8 apps with the Notification Hubs. Stay tuned!
Note: This post originally appeared on my MSDN blog at http://blogs.msdn.com/b/africaapps/archive/2013/09/23/windows-azure-notification-hubs-getting-started.aspx