Mike Taulty's Blog
Bits and Bytes from Microsoft UK
Windows/Phone 8.1–Running Code in Response to Cloud Push Notifications

Blogs

Mike Taulty's Blog

Elsewhere

Archives

One of the features of Windows 8.0/8.1 apps is the ability to respond to a raw push notification delivered from the Windows Notification Service in the cloud.

You can read about raw push notifications on the developer centre (I dug out the link - http://msdn.microsoft.com/en-us/library/windows/apps/jj676791.aspx – to save you having to search around).

A raw notification is just a string up to around 5KB of data in size. When an app receives a raw notification, I think it can do one of two things;

  1. If the app was lucky enough to be actually running then it can register an event handler to receive the data from a raw notification as it hits the device.
  2. The app can register a background task which will run on receipt of the raw notification.

Of the two I think it’s fair to say that (2) is the only pragmatic approach unless you want some kind of UI like this in your app Winking smile

image

that second option though is a powerful thing - it effectively means that code running in the cloud can trigger the execution of code on a device.

That code running on the device might do something “quiet” like writing the received data into a file or it might take an active step like executing some web request to get new data from the cloud and it might combine this with something a bit more “invasive” like popping up a toast message to tell the user that something has happened.

I drew out an example scenario at one point that looked as below;

image

The idea here is that there’s a football app on the phone which has registered a background task to receive raw push notifications. In the cloud there’s some football service which is monitoring a game and sending raw push notifications to the app whenever there’s a goal scored in the game.

The app on the device can then choose (maybe based on a setting) to simply record the details of all of these goals in storage until the game ends and then (perhaps) notify the user that the game is over and their team won/lost having quietly recorded the details of 4 raw push notifications (goals) in the meantime;

image

What does it take to get this sort of thing up and running?

“Not too much” – here’s a quick step by step way of getting this working. There are perhaps 4 main steps if using Windows Azure;

  1. Creating a notification hub.
  2. Creating an app, associating it with the Store and configuring the notification hub to talk to WNS for it.
  3. Executing code on the client-side to register with that hub.
  4. Writing a background task to execute on receipt of a raw push notification and writing code to register that background task.
  5. Writing server-side logic to send raw notifications when something “interesting/relevant” to the user happens.

I’m going to miss out step 5 here but I thought I’d run through 1-4. It’s worth saying that Azure Mobile Services has ways of making this easier but I’ll work here without Mobile Services just for novelty Smile

Step 1 – Creating a Notification Hub

I can use the Azure Portal to create a notification hub;

image

and now I’ve got a hub called “mtaultyHub”. What I’m going to need from this hub are two things;

  1. I need to configure the hub to be able to speak to the Windows Notification Service in the cloud and to do that I’m going to need an app..
  2. I need to be able to configure the app to speak to the hub and to do that I’m going to need a connection string for the hub.

Step 2 I can gather from the hub’s dashboard page;

image

which launches up a dialog;

image

where I can copy out the connection string highlighted – I’ll need this in a moment.

Step 2- Create a New App, Associate with Store & Grab Identifiers

On the client side, I can make a new, blank Windows Phone 8.1 app in Visual Studio 2013 Update 2 RC and then I can associate it with the Windows Phone Store via the Visual Studio menu;

image

and that pops up a dialog where I can make a new app name or re-use an existing one;

image

and once the association is made I can navigate to http://dev.windowsphone.com and then to Dashboard;

image

and that leads to Apps and including my “Not Started” apps;

image

and if I navigate into that mtaultyTestHub app I have to get past the initial question;

image

and then I can scroll right to the bottom of that page and find this link;

image

and that gets me to this page;

image

and I can take the Package SID and the Client Secret and I can copy them across to the configuration page for my notification hub;

image

and that’s then configured the hub to be able to talk to WNS.

Step 3 – Run Client Side Code to Register with Notification Hub

I can then write some code in my phone app to obtain a push notification channel URI – e.g;

 private async void OnRegister(object sender, RoutedEventArgs e)
    {
      var channel = 
        await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
      
    }

and that gets me a channel (with a URI) for the app for the user on the device and I also need to send the URI to the notificaton hub to register this client as a possible recipient of push notifications. One way to do that is to add client-side SDK classes for Azure Notification Hubs from Nuget for which I used;

Install-Package WindowsAzure.Messaging.Managed

in the Nuget console. With that in place I can then expand out that previous code;

    private async void OnRegister(object sender, RoutedEventArgs e)
    {
      var channel = 
        await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

      NotificationHub hub = new NotificationHub(
        "mtaultyhub",
        "Endpoint=sb://mtaultyhub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=notIncluded");

      await hub.RegisterNativeAsync(channel.Uri, new string[] { "Group1", "MikeTaulty" });
    }

and then if I run this code, I have this particular client registered for push notifications from the hub. If I switch on “Toast Notifications” in my app’s manifest;

image

then I could use Visual Studio to send a quick test toast notification to see if things have registered correctly;

image

which raises this page in Visual Studio;

image

and pressing the “Send” button talks to the cloud which talks to the device which pops this toast in response (I’m doing this in the emulator);

image

and if I stop broadcasting and use a made-up tag like “Foo” then nothing happens down on the device;

image

whereas if I pass one of the tags that I associated with the registration;

image

then I see the toast down on the device and so I can feel comfy that things are working ok at least from the point of view of a toast notification but what about a raw notification activating a background task?

Step 3 – Writing a Background Task to Execute on Receipt of a Raw Push Notification

I need to write a background task – it’s important to make sure that you’re writing a Windows Runtime Component here rather than a .NET class library because background tasks need to be implemented as Windows Runtime Components.

I can add a project to my solution;

image

and then do a quick implementation of a background task which will just dump the received data out to the debugger;

namespace WindowsRuntimeComponent1
{
    public sealed class MyTask : IBackgroundTask
    {
      public void Run(IBackgroundTaskInstance taskInstance)
      {
        RawNotification rawNotification = taskInstance.TriggerDetails as RawNotification;

        if (rawNotification != null)
        {
          Debug.WriteLine(
            string.Format("Received from cloud: [{0}]",
            rawNotification.Content));
        }
      }
    }
}

and I can reference that project from my main app project and write a little code to register the background task;

      await BackgroundExecutionManager.RequestAccessAsync();

      // Get rid of existing registrations.
      foreach (var task in BackgroundTaskRegistration.AllTasks)
      {
        try
        {
          task.Value.Unregister(false);
        }
        catch // hack
        {
        }
      }
      BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
      builder.Name = "Push Task";
      builder.TaskEntryPoint = typeof(WindowsRuntimeComponent1.MyTask).FullName;
      builder.SetTrigger(new PushNotificationTrigger());
      builder.Register(); 

and update my manifest to make sure that this registration is going to be allowed;

image

and then I can run that code to get the background task register and then use the test page in Visual Studio to send a raw notification to the device;

image

and I see the debugger output;

image

and that all works quite nicely – we have the cloud able to deliver string data down to the device and the device able to respond to that notification by executing code which can pick up the payload sent as part of the push notification.

“All” that’s left is to come up with a proper scenario and a cloud-based service to run logic and deliver notifications as/when something of relevance to a user (or group of users) happens. Again, Azure Mobile Services can help in terms of implementing that cloud service and its logic.

I think this is a very powerful new capability for Windows Phone 8.1 development – the device able to pick up almost “real time” notifications from the cloud and act upon them.


Posted Thu, Apr 24 2014 3:14 PM by mtaulty