Add push notifications to your Windows app

Overview

In this tutorial, you add push notifications to the Windows quick start project so that a push notification is sent to the device every time a record is inserted.

If you do not use the downloaded quick start server project, you will need the push notification extension package. See Work with the .NET backend server SDK for Azure Mobile Apps for more information.

Configure a Notification Hub

The Mobile Apps feature of Azure App Service uses Azure Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.

  1. In the Azure portal, go to App Services, and then select your app back end. Under Settings, select Push.

  2. To add a notification hub resource to the app, select Connect. You can either create a hub or connect to an existing one.

    Configure a hub

Now you have connected a notification hub to your Mobile Apps back-end project. Later you configure this notification hub to connect to a platform notification system (PNS) to push to devices.

Register your app for push notifications

You need to submit your app to the Microsoft Store, then configure your server project to integrate with Windows Push Notification Services (WNS) to send push.

  1. In Visual Studio Solution Explorer, right-click the UWP app project, click Store > Associate App with the Store....

    Associate app with Microsoft Store

  2. In the wizard, click Next, sign in with your Microsoft account, type a name for your app in Reserve a new app name, then click Reserve.

  3. After the app registration is successfully created, select the new app name, click Next, and then click Associate. This adds the required Microsoft Store registration information to the application manifest.

  4. Navigate to the Application Registration Portal and sign in with your Microsoft account. Click the Windows Store app you associated in the previous step.

  5. In the registration page, make a note of the value under Application secrets and the Package SID, which you will next use to configure your mobile app backend.

    Associate app with Microsoft Store

    Important

    The client secret and package SID are important security credentials. Do not share these values with anyone or distribute them with your app. The Application Id is used with the secret to configure Microsoft Account authentication.

App Center also has instructions for configuring UWP apps for push notifications.

Configure the backend to send push notifications

  1. In the Azure portal, select Browse All > App Services. Then select your Mobile Apps back end. Under Settings, select App Service Push. Then select your notification hub name.

  2. Go to Windows (WNS). Then enter the Security key (client secret) and Package SID that you obtained from the Live Services site. Next, select Save.

    Set the WNS key in the portal

Your back end is now configured to use WNS to send push notifications.

Update the server to send push notifications

Use the procedure below that matches your backend project type—either .NET backend or Node.js backend.

.NET backend project

  1. In Visual Studio, right-click the server project and click Manage NuGet Packages, search for Microsoft.Azure.NotificationHubs, then click Install. This installs the Notification Hubs client library.

  2. Expand Controllers, open TodoItemController.cs, and add the following using statements:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. In the PostTodoItem method, add the following code after the call to InsertAsync:

    // Get the settings for the server project.
    HttpConfiguration config = this.Configuration;
    MobileAppSettingsDictionary settings =
        this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
    // Get the Notification Hubs credentials for the Mobile App.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
    // Create the notification hub client.
    NotificationHubClient hub = NotificationHubClient
        .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
    // Define a WNS payload
    var windowsToastPayload = @"<toast><visual><binding template=""ToastText01""><text id=""1"">"
                            + item.Text + @"</text></binding></visual></toast>";
    try
    {
        // Send the push notification.
        var result = await hub.SendWindowsNativeNotificationAsync(windowsToastPayload);
    
        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter()
            .Error(ex.Message, null, "Push.SendAsync Error");
    }
    

    This code tells the notification hub to send a push notification after a new item is insertion.

  4. Republish the server project.

Node.js backend project

  1. Set up your backend project.

  2. Replace the existing code in the todoitem.js file with the following:

    var azureMobileApps = require('azure-mobile-apps'),
    promises = require('azure-mobile-apps/src/utilities/promises'),
    logger = require('azure-mobile-apps/src/logger');
    
    var table = azureMobileApps.table();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see https://aka.ms/nodejshubs
    logger.info('Running TodoItem.insert');
    
    // Define the WNS payload that contains the new item Text.
    var payload = "<toast><visual><binding template=\ToastText01\><text id=\"1\">"
                                + context.item.text + "</text></binding></visual></toast>";
    
    // Execute the insert.  The insert returns the results as a Promise,
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured
            if (context.push) {
                // Send a WNS native toast notification.
                context.push.wns.sendToast(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute()
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;
    

    This sends a WNS toast notification that contains the item.text when a new todo item is inserted.

  3. When editing the file on your local computer, republish the server project.

Add push notifications to your app

Next, your app must register for push notifications on start-up. When you have already enabled authentication, make sure that the user signs-in before trying to register for push notifications.

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

    using System.Threading.Tasks;
    using Windows.Networking.PushNotifications;
    
  2. In the same file, add the following InitNotificationsAsync method definition to the App class:

    private async Task InitNotificationsAsync()
    {
        // Get a channel URI from WNS.
        var channel = await PushNotificationChannelManager
            .CreatePushNotificationChannelForApplicationAsync();
    
        // Register the channel URI with Notification Hubs.
        await App.MobileService.GetPush().RegisterAsync(channel.Uri);
    }
    

    This code retrieves the ChannelURI for the app from WNS, and then registers that ChannelURI with your App Service Mobile App.

  3. At the top of the OnLaunched event handler in App.xaml.cs, add the async modifier to the method definition and add the following call to the new InitNotificationsAsync method, as in the following example:

    protected async override void OnLaunched(LaunchActivatedEventArgs e)
    {
        await InitNotificationsAsync();
    
        // ...
    }
    

    This guarantees that the short-lived ChannelURI is registered each time the application is launched.

  4. Rebuild your UWP app project. Your app is now ready to receive toast notifications.

Test push notifications in your app

  1. Right-click the Windows Store project, click Set as StartUp Project, then press the F5 key to run the Windows Store app.

    After the app starts, the device is registered for push notifications.

  2. Stop the Windows Store app and repeat the previous step for the Windows Phone Store app.

    At this point, both devices are registered to receive push notifications.

  3. Run the Windows Store app again, and type text in Insert a TodoItem, and then click Save.

    Note that after the insert completes, both the Windows Store and the Windows Phone apps receive a push notification from WNS. The notification is displayed on Windows Phone even when the app isn't running.

Next steps

Learn more about push notifications:

Consider continuing on to one of the following tutorials:

  • Add authentication to your app Learn how to authenticate users of your app with an identity provider.
  • Enable offline sync for your app Learn how to add offline support your app using an Mobile App backend. Offline sync allows end-users to interact with a mobile app—viewing, adding, or modifying data—even when there is no network connection.