Writing...Data Services

Coding and writing about OData and now Windows Azure Mobile Services...

Notification Hubs Plus Mobile Services for Sending Windows Phone Notifications from a .NET Backend Service

Notification Hubs Plus Mobile Services for Sending Windows Phone Notifications from a .NET Backend Service

Rate This
  • Comments 1

On Thursday, the Windows Azure Mobile Services team released a brand new backend implementation that is based on ASP.NET Web API. There is currently support for Windows Store, Windows Phone and iOS clients using the new .NET backend. You can read about this on ScottGu’s blog, Geoff Cross' blog, Shiju Varghese's blog, and lots of other places.

At the same time as the .NET backend, Mobile Services also released integrated support for Windows Azure Notification Hubs, which you can read about from Elio on the Mobile Services team blog. This is all goodness all around, and we are working at getting both documented as fast as we can.

One minor disappointment for me in this sea of “win,” as a Windows Phone guy, is the apparent lack of support for using Notification Hubs to send notifications to Windows Phone from the .NET backend (Windows Phone, iOS, and Android are supported by Notification Hubs, just not yet from .NET backend mobile service). This is just not working at this point—bummer because this integration makes it so easy to do so. I’m not saying that you can’t do it from a .NET backend in Mobile Services…it’s just not quite as easy, and we don’t have it documented.

Until this support arrives, and to fill in the gap, here’s how to can do it by using the generic Notification Hubs client APIs until there is full support in .NET backend and everything can be done via the MobileServicesClient API.

Before you start

This tutorial is based on the Mobile Services quickstart. Before you start this tutorial, you must first complete either Get started with Mobile Services or Get started with data to create a .NET backend mobile service and connect your project to the mobile service. Oh, and you will need Visual Studio 2013 Professional or better to work with the .NET backend (sorry).

Obtain the integrated Notification Hub info for you mobile service

As I mentioned, every .NET backend mobile service now gets its own free Notification Hub. Mobile Services keeps this information for you, but we need it to be able to register a Windows Phone device since MobilsServiceClient.GetPush().RegisterNativeAsync() is not supported on Windows Phone. The .NET backend service already has this info.

  1. Log on to the Windows Azure Management Portal, click Mobile Services, and then click your mobile service.
  2. Click the Push tab, then click the Notification Hub link.
    image
    This takes you to the Notification Hub associated with your mobile service project.
  3. Make a note of the official name of your hub (usually mobile service name + “hub”), then click View Connection String and copy the  
    image

Update the app to register for notifications

Before your app can receive push notifications, you must register a notification channel.

  1. In Visual Studio, right-click the Windows Phone app project, click Manage NuGet Packages, search for WindowsAzure.Messaging.Managed, then click Install, accept the license terms, and click Close.
    image
    This installs the library that contains the Notification Hubs client (you won’t have to do this once Mobile Services supports Windows Phone and MPNS with Notification Hubs).

  2. Open the App.xaml.cs project file and add the following using statements:

    using Microsoft.Phone.Notification;
    using Microsoft.WindowsAzure.Messaging;
  3. Add the following AcquirePushChannel method to App class:

    public static HttpNotificationChannel CurrentChannel { get; private set; }
    
    private async void AcquirePushChannel()
    {
        CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
    
        if (CurrentChannel == null)
        {
            CurrentChannel = new HttpNotificationChannel("MyPushChannel");
            CurrentChannel.Open();
            CurrentChannel.BindToShellToast();
        }
    
        // Handle the event that is raised when a toast is received.
        CurrentChannel.ShellToastNotificationReceived +=
            new EventHandler<NotificationEventArgs>((o, args) =>
        {
            string message = "";
            foreach (string key in args.Collection.Keys)
            {
                message += args.Collection[key] + ": ";
            }
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Show the notification since toasts aren't 
                // displayed when the app is currently running.
                MessageBox.Show(message);
            });
        });
    
        // Create a new Notification Hub client.
        var hub = new NotificationHub("<your_hub_name>", 
    "<your_fullaccess_connection_string>"); // Create a new registration for a native MPNS notification. var result = await hub.RegisterNativeAsync( CurrentChannel.ChannelUri.ToString()); //// MobileServiceClient-driven registration is //// not yet supported for Windows Phone. //await MobileService.GetPush() // .RegisterNativeAsync(CurrentChannel.ChannelUri.ToString()); }

    In this code, you must replace <your_hub_name> and <your_fullaccess_connection_string> with the notification hub name and full access connection string from the previous section.

    This code retrieves the channel URI for the app if it exists. Otherwise, it will be created. The channel URI is then opened and bound for toast notifications. The ShellToastNotificationReceived handler is setup so that the app can receive and handle push notifications while running.

  4. In the Application_Launching event handler in App.xaml.cs, add the following call to the new AcquirePushChannel method:

    AcquirePushChannel();

    This makes sure that registration is requested every time that the app is loaded. In your app, you may only want to make this registration periodically to ensure that the registration is current.

  5. In Visual Studio, open the Package.appxmanifest file and make sure that Toast capable is set to Yes on the Application UI tab.
    image
    This makes sure that your app can raise toast notifications.

Update the server to send push notifications

  1. In Visual Studio Solution Explorer, expand the Controllers folder in the mobile service project. Open TodoItemController.cs and update the PostTodoItem method definition with the following code.

    public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
    {
        // Define a native MPNS push notification.
        var payload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
            @"<wp:Notification xmlns:wp=""WPNotification""><wp:Toast>" +
            @"<wp:Text1>New Item</wp:Text1><wp:Text2>" + item.Text +
            @"</wp:Text2></wp:Toast></wp:Notification>";
    
        // Insert the new item.
        TodoItem current = await InsertAsync(item);
    
        // Get the notification hub name from the service settings.
        var hubName = Services.Settings.NotificationHubName;
    
        // Get the connection string for the notification hub
        // from the mobile service runtime settings.
        string hubConnectionString;
        if (Services.Settings.TryGetValue("MS_NotificationHubConnectionString", 
            out hubConnectionString))
        {
            // Create a new hubs client. 
            NotificationHubClient hub =
                NotificationHubClient.CreateClientFromConnectionString(
                hubConnectionString, hubName);
            var result = await hub.SendMpnsNativeNotificationAsync(payload);
            //// Log the result of the push notification.
            //Services.Log.Info(string.Format("Notification:{0} -state: {1}", 
            // result.TrackingId.ToString(), result.State.ToString()));
        }

        //// You should be able to just call this line of code, but there's a bug.
        // await Services.Push.HubClient.SendMpnsNativeNotificationAsync(payload);
    return CreatedAtRoute("Tables", new { id = current.Id }, current); }

    This code uses Notification Hubs to send a push notification (with the text of the inserted item) via MPNS after inserting a todo item. You can optionally log the result of the Send request, which is then viewable on the Logs tab of the mobile service in the Management Portal. This is actually pretty useful since it’s such a PITA to run Windows Phone against a local service.  

  2. Right-click the service project click Publish, then complete the publishing wizard.
    This republishes the mobile service project, as I find it’s easier to debug a Windows Phone against the live service than messing with setting-up firewall rules and all that, which you can do (Test the Windows Phone app with the service hosted locally).

  3. Back in the Windows Azure Management Portal, click Mobile Services, and then click your app.

  4. Click the Push tab, check Enable unauthenticated push notifications under MPNS, then click Save.
    image
    This enables the mobile service to connect to MPNS in unauthenticated mode to send push notifications.

Note:This tutorial uses MPNS in unauthenticated mode. In this mode, MPNS limits the number of notifications that can be sent to a device channel (something like 500/channel/day IICR). To remove this restriction, you must generate and upload a certificate by clicking Upload and selecting the certificate. For more information on generating the certificate, see Setting up an authenticated web service to send push notifications for Windows Phone.

Test push notifications in your app

  1. In Visual Studio, press the F5 key to deploy and run the app.

  2. In the app, enter the text "hello push" in the textbox, and then click Save.

    This sends an insert request to the mobile service to store the added item. At this point, one of two things happen:

    • When you are still in the app, the ShellToastNotificationReceived event is handled and a message is displayed that says “New item: hello push.” 
      image

    • If you quickly exit the app, you will see that a toast notification is received that says “hello push.”
      image

Hopefully, you all found this helpful and don’t have to wait to use .NET backend in Mobile Services with Notification Hubs in your Windows Phone apps. I will take these instructions down and point to the correct tutorial once the support for Windows Phone and Notification Hubs is added to .NET backend.

Cheers!

Glenn Gailey

Leave a Comment
  • Please add 6 and 2 and type the answer here:
  • Post
  • Thanks to Wesley McSwain for pointing out my missing using statement:

    using Microsoft.WindowsAzure.Messaging;

Page 1 of 1 (1 items)