30 Days of Zumo.v2 (Azure Mobile Apps): Day 23 – Understanding Push Notifications

So far, I’ve covered local and remote development, enterprise authentication patterns, table controllers, offline sync and custom APIs. There is one big section of functionality I have not covered yet which is very mobile focused – push notifications. Classically, these are the little pop-up messages you get on your phone to tell you your friend has tagged you in a post, or your favorite news app has some juicy breaking news for you. Push notifications is an out-of-band mechanism that can be used to inform your mobile app that they need to do something. Just like authentication, there are more moving parts. Unfortunately, you don’t own one of them and there is little you can do to control it.

Registering Your Device

There are two distinct processes that you need to understand – registering your device and sending a push. Let’s take a look at registering your device first. There are four distinct steps to registering your device:


Step 1: Use a platform-specific push notification SDK to retrieve your unique device ID and send it to the platform notification service. The platform notification services are run by the major providers – Apple devices use APNS; Android devices use GCM and Microsoft devices use WNS. There are a handful of others as well. Registering with the platform notification service has absolutely nothing to do with Azure – it’s purely between you, your app and the platform provider.

Step 2: The platform notification service will register your device and send you a registration ID back – this could be a URI or a GUID. it depends on the provider. It’s best to assume this registration ID is an opaque blob that you shouldn’t look at. Device registration IDs are unique to the device – not the user logged into the device.

Step 3: Register the device with Azure Mobile Apps. Once you have configured an Azure App Service with a Notification Hub, a default push registration endpoint becomes available (for reference, it lives at /push/installations on your site). The Client SDK can be used to send the registration ID to that endpoint for processing.

Step 4: Azure Mobile Apps registers your device with Notification Hubs. Since you have configured a Notification Hub properly, Azure Mobile Apps will pass through the call to the Notification Hub for you. This is a security convenience – it means you don’t have to distribute a secret for your notification hub with your app (which would be a bad thing). Once this is done, Azure Mobile Apps will send the Notification Hubs installation ID back to confirm registration.

It sounds more complicated than it actually is – the code is minimal. Before I get there, however, I need to configure my Azure App Service with a Notification Hub.

Why use Notification Hubs?

You might be forgiven for wondering why you need notification hubs at all? After all, you can write a custom API to receive device registrations and store them “somewhere” and then interact with the Platform Notification Services directly, thus cutting out the middleman. To my mind there are three very basic reasons why you need Notification Hubs and will inevitably choose to use Notification Hubs:

  1. Cross-platform. At the end of the day, you don’t care whether your device is on Android, iOS or Windows when you are doing a push – you just want it to work. Aside from the registration process (which is always dictated by the PNS), Notification Hubs can isolate you from the actual logic you need to do individual pushes.

  2. Scale. Sure you can write a custom API to deal with device registrations and handle that complexity for yourself, and it feels tempting in small sites. However, the storage and upkeep of the registration database quickly becomes a nightmare. I haven’t even considered the batching and queueing mechanics required to push to more than a couple hundred users. Notification Hubs abstracts the scale architecture away from you, allowing you to concentrate on the code for your app.

  3. Tagging. Ok – so I’m not going to get to this one until the next post, but Notification Hubs builds in a great subscription model that allows you to push to a tag – any device subscribing to that tag gets the push to the tag. Don’t think that’s useful? How about push to user (tag) or push to AAD group (tag)? How about push to Interest (tag)? This is extremely useful.

Notification Hubs has a generous free tier to allow for development – you can have up to a million pushes per month, across 10 hubs and to 500 devices. Higher tiers are still cheap but handle up to 10 million devices at once.

Adding a Notification Hub

To add a notification hub, start at the Azure Portal and select your App Service, then:

  • Click on All Settings -> Push (under the MOBILE menu heading)
  • Click on Notification Hub then + Notification Hub:


  • Enter a (Unique) name for your notificaion hub – I use the same name as my app name.
  • Notification Hubs are collected into namespaces. Click on Or create new to create a new one and enter a suitable name:


  • Click on the blue OK button at the bottom, then the Create button (also at the bottom).

If you skip over to the Data Connections settings blade, you will notice you have two connections now – one for notifications and one for data. There are also two connection strings listed in the Application Settings blade.

Now that I have a notification hub, I need to configure the connections to the platform notification services. Each PNS has its own method of creating an application connection, and the methodology is rather robotic – just follow the Azure instructions for the appropriate PNS:

Its relatively commonplace to configure more than one provider. If you are just starting out, I’d recommend configuring GCM – it’s the easiest (and cheapest) to get started. For GCM, once you have your Project Number and API Key, you are done. Just cut-and-paste the API Key into the API Key for the GCM settings on the Notification Hub:


It’s a good idea to produce a Custom API that returns the push settings needed from the client. For example, you can have a custom API that reads the Project Number from an app setting that you define and returns it as part of a settings object. This ensures that your client configuration remains with you – if the project number needs to change, you can do it on the server rather than distributing a new client.

If you are using Google Authentication + GCM, then you can use the same project in the Google Developer Console.

Adding Push Registration to ASP.NET

The Node.js backend has push notifications “for free” – the registration endpoint is always there. You need to add the push registration to the ASP.NET backend. This is a one-time thing. Start by adding the Microsoft.Azure.Mobile.Server.Notifications NuGet Package (and dependencies, which include the Notification Hubs SDK); then adjust the startup code in the App_Start file:

            // Configure the Azure Mobile Apps section
            new MobileAppConfiguration()
                    new MobileAppTableConfiguration()

Publish this code before continuing.

Registering for Push – Apache Cordova Style

I don’t know why, but I prefer Apache Cordova development on the Mac. I’d been using the Visual Studio TACO (Tools for Apache Cordova), but a variety of problems with emulators and the Android SDK caused me to switch back to the Mac for this. One important aspect of doing push notifications on Apache Cordova is the binary image you use – either on the phone or on an emulator. Specifically, you must use an emulator that contains the Google APIs. You can do this in the AVD Manager.

To handle the device to PNS communication, I use a 3rd party plugin – phonegap-plugin-push. This is a fairly standard plugin and is used by most Apache Cordova applications that implement push notifications. To add the plugin to your project:

cordova plugin add phonegap-plugin-push --variable SENDER_ID=your-project-id
cordova plugin add cordova-plugin-device

You can also add it via the Plugins > Custom menu when the config.xml file is open within Visual Studio. Add the Git repository https://github.com/phonegap/phonegap-plugin-push. Note that the phonegap-plugin-push requires certain libraries from the Android SDK so ensure you follow the install instructions. There is a small amount of code needed to bring this in, and it’s all in my app initialization routine:

        // Register for push notifications
        if (typeof PushNotification === 'undefined') {
            console.log('Push Notification Service is unavailable');
        } else {
            console.log('Initializing Push');
            pnsHandler = PushNotification.init({
                android: { senderID: '121035973492' },
                ios: { alert: 'true', badge: 'true', sound: 'true' },
                wns: { }
            console.log('pnsHandler = ', pnsHandler);

            console.log('Registering Push Event Handlers');
            pnsHandler.on('registration', handlePushRegistration);
            pnsHandler.on('notification', handlePushNotification);
            pnsHandler.on('error', handleError);

The important thing to do here is replace the Android senderID with the one for your project. Using mine won’t work. This number isn’t the secret – the API key is the secret (and you should never check secrets into source code, of course). If you’ve followed my advice earlier, you will have to call the custom API to get this number. iOS/APNS and WNS depend on the application being registered and properly configured in the respective app stores for their functionality, so Android is the only one you need to specify something for. I’ve got two functions to write still – handlePushRegistration() is called when the PNS returns my registration ID and handlePushNotification() is called when I actually receive a push notification.

Note that the push notification service is only available after the onDeviceReady() event has fired. The initial check ensures the library is loaded.

Let’s check out registration first. I want to pass the registration ID to the client registration process:

     * Event Handler for Push Registration ID
     * @event
    function handlePushRegistration(data) {
        console.log('device model == ' + device.model);
        var pns = 'gcm'; // the default
        if (device.model === 'ios') pns = 'apns';
        if (device.model === 'windows') pns = 'wns';

        console.log('Registering with Notification Hub');
        client.push.register(pns, data.registrationId);

The client.push routines are pretty much always pass-throughs for the appropriate Notification Hub routines in the Notification Hubs SDK, so if you want to know what they return, reference the Notification Hubs SDK instead.

The various platform notification services all use a similar format for IDs, so I need to tell Notification Hubs who generated the registration ID. I’m doing this in a very basic way right now – most people use GCM. If you are on iOS or Windows specifically, then use the appropriate one.

Finally, let’s take a look at handling the actual notification:

     * Event Handler for Push Notification
     * @event
    function handlePushNotification(data) {
        console.log('handlePushNotification: data = ' + JSON.stringify(data));
        alert('PUSH NOTIFICATION:\n'+data.message);

Each push notification has a message, which could be encoded. All I do is print out the message. I’ll deal with some of the more esoteric things you can do with this later on.

Monitoring Registrations

You are probably thinking that the Azure Portal has some amazing things to see registrations so I know what is going on. Sadly, no it doesn’t. However, Visual Studio does have some really great tooling here. Just start up Visual Studio, find the Server Explorer, log into Azure and expand to find your notification hub. Double-click on it will get you a window with the current registrations in it:


You can also see that two tags are automatically added for me. The first is one based on the installation ID – this is an Azure Mobile App generated GUID that is unique to the app/device combination (but several users could be using the same app/device). The other tag is based on the authenticated user ID – it’s the “stable SID” – i.e. something that the IdP generates for me. I can use this to implement “push to user”. There is more to talk about here, but that’s for another time.

Sending a Test Push Notification

The other thing I can do with the Visual Studio tooling (but if you are on a mac, don’t worry – you can do this bit in the Azure Portal as well) is a test send. That’s “the other tab” in the registration monitor. To use it, just select a Message Type of Android default and hit send.


Almost immediately (but in reality, it could be a few minutes because of PNS delays), you will see the push notification alert on your application.

Wrap Up

We have only scratched the surface here with one app on one device type with one PNS, but we’ve covered a lot of ground. The Azure Tutorials do a good job of putting together specific push scenarios for each platform. Since there are a lot of details to cover, I recommend doing the tutorials for your platform. In the next post, I’m going to talk about tags and how to register for tags in both Node.js and ASP.NET backends. Until then, todays content is available from my GitHub repository.

One thought on “30 Days of Zumo.v2 (Azure Mobile Apps): Day 23 – Understanding Push Notifications

Comments are closed.