共用方式為


Quickstart: Adding push notifications for a mobile service (.NET backend)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This Quickstart walks you through enabling push notifications in a Windows Store app using Azure Mobile Services. Mobile Services makes it easy to send push notifications to your app by using the Windows Push Notification Services (WNS). To learn more, see the Mobile Services dev center. Microsoft Visual Studio 2013 makes it easy to enable push notifications in your Mobile Services app. This topic builds on the previous topic Quickstart: Adding a mobile service. When you are done, you will have added push notifications to your new mobile service and tested the app by sending a new notification.

This Quickstart applies to mobile services that use the .NET backend. If you are using the JavaScript backend, see Quickstart: Add push notifications (JavaScript backend).

Prerequisites

  • Visual Studio 2013 Update 3
  • An Azure subscription. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.
  • An active Windows Store account.
  • Complete the previous Quickstart: Adding a mobile service topic.

Add and configure push notifications in the app

First, use the Add Push Notification wizard in Visual Studio 2013 to register your app with the Windows Store, configure your mobile service to enable push notifications, and add code to your app to register a device channel.

Note  This topic assumes that a mobile service connection has already been added to the project, which was done in the previous topic. When a mobile service has not been connected, the Add Push Notification wizard creates this connection for you.

 

  1. In Visual Studio 2013, open Solution Explorer, open the shortcut menu for the project, choose Add then Push Notification.... This starts the Add Push Notification Wizard.

  2. Choose the Next button, sign in to your Windows Store account, then supply a name in Reserve a new name and choose Reserve. This creates a new app registration in the Windows Store.

  3. Choose the new registration in the App Name list, then choose the Next button.

  4. Select the mobile service that you created when you completed Quickstart: Adding a mobile service (.NET backend), choose the Next button, then choose Finish. This configures your mobile service to work with Windows Push Notification Services (WNS) to be able to send notifications to your app. If you have a JavaScript backend mobile service, see Quickstart: Add push notifications (JavaScript backend).

    Note  When your app isn't already configured to connect to the mobile service, the wizard also completes the same configuration tasks demonstrated in Quickstart: Adding a mobile service.

     

  5. (Optional) Expand Services, Mobile Services, your service name, and open the generated code file, push.register.*. Inspect the UploadChannel method that registers for push notifications.

    public async static void UploadChannel()
    {
        var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
        try
        {
            await App.myusernametodolist1234abcClient.GetPush().RegisterNativeAsync(channel.Uri);     
        }
        catch (Exception exception)
        {
            HandleRegisterException(exception);
        }
    }
    
    Public Shared Async Sub UploadChannel()
        Dim channel = Await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync()
        Try
            Await App.myusernametodolist1234abcClient.GetPush().RegisterNativeAsync(channel.Uri)
            Await App.myusernametodolist1234abcClient.InvokeApiAsync("notifyAllUsers", New JObject(new JProperty("toast", "Sample Toast")))
        Catch exception As Exception
            HandleRegisterException(exception)
        End Try
    End Sub
    

    A call to this method was also added by the wizard to the OnLaunched event handler in the App.xaml.cs, App.xaml.vb, or App.xaml.cpp code file. This ensures that registration of the device is attempted whenever the app is launched.

  6. The payload variable represents the XML for a certain type of toast notification that Windows Store apps use. For a complete description of the toast notification templates, see The toast template catalog.

In the following steps, you modify the mobile service to send push notifications, and then verify that they are received. These steps are the same as those in the readme file that appears in Visual Studio when you add a push notification. You will need some of the code from the readme.

Send and receive push notifications and debug on the local machine

  1. Choose the mobile service project node, and choose Add, New Scaffolded Item, and then choose the Microsoft Azure Mobile Services Custom Controller template.

  2. In the Add Controller dialog box, enter NotifyAllUsersController.

    A new file, NotifyAllUsersController.cs or NotifyAllUsersController.vb is added to the Controllers folder in the mobile service project. The file contains a class NotifyAllUsersController.

  3. Insert the following code into the NotifyAllUsersController class.

    public async Task Post(JObject data) {
        try 
        {
            string wnsToast = string.Format("("<?xml version=\"1.0\" encoding=\"utf-8\"?><toast><visual><binding template=\"ToastText01\"><text id=\"1\">{0}</text></binding></visual></toast>", data.GetValue("toast").Value());
            WindowsPushMessage message = new WindowsPushMessage();
            message.XmlPayload = wnsToast;
            await Services.Push.SendAsync(message);
        }
        catch (Exception e)
        {
            Services.Log.Error(e.ToString());
        }
    }
    
    Public Async Function Post(data As JObject) As Task
        Try
            Dim wnsToast As String = String.Format(("<?xml  version=""1.0"" encoding=""utf-8""?><toast><visual><binding template=""ToastText01""><text id=""1"">{0}</text></binding></visual></toast>", data.GetValue("toast").Value(Of String)())
            Dim message As New WindowsPushMessage()
            message.XmlPayload = wnsToast
            Await Services.Push.SendAsync(message)
        Catch e As Exception
            Services.Log.Error(e.ToString())
        End Try
    End Function
    
  4. To enable you to run and debug your service locally, add a connection string called MS_NotificationHubConnectionString in web.config.

    <add name="MS_NotificationHubconnectionString" connectionString="**your connection string**" />
    

    The connection string is in the readme that appears when you add push notifications. You can also find it by selecting the notification hub in Server Explorer, opening the Properties window, and copying the value in the Full Access Connection field. To get the connection string from the Azure management portal, choose the Service Bus button, choose the notification hub that Azure created for your mobile service (it's name is the name of your mobile service plus "hub"), choose the Connection Information button, and then choose the Copy button next to the Connection String text box. Use the Shared Access Signature (SAS) key, not the Access Control Services (ACS) key, if both are present. For more information about these options, see Service Bus Authentication and Authorization.

  5. Replace the MS_NotificationHubName key in the appSettings section in web.config with the following:

    <add key="MS_NotificationHubName" value="**your notification hub name**
    

    You can get the notification hub name by adding "Hub" to the mobile service name.

  6. The remaining steps are not required if you created a new mobile service project in the Push Notification Wizard. If you added push notifications to an existing mobile service, you should redirect the client app to use the local debug version of the service. Choose the mobile service project, open the shortcut menu, and choose Set As Startup Project. Then, start the service in the debugger (Keyboard: F5). Select the URL (for example, https://localhost:17470) and copy it to the clipboard.

  7. Open App.xaml.cs or App.xaml.vb, comment out the code that initializes the mobile service client, and replace it with code that references the URL you copied in the previous step. The resulting code should resemble the following:

    // https://go.microsoft.com/fwlink/p/?linkid=290993&clcid=0x409 
    public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient myusernametodolist1234abcClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://localhost:17470");
    
    //public static Microsoft.WindowsAzure.MobileServices.MobileServiceClient myusernametodolist1234abcClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
    //                            "https://yourmobileservicename.azure-mobile.net/",
    //                            "your client secret");
    
    ' https://go.microsoft.com/fwlink/p/?linkid=290990&clcid=0x409 
    Public Shared myusernametodolist1234abcClient As New Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
                "https://localhost:17470")
    
    ' Public Shared myusernametodolist1234abcClient As New Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
    '             "https://yourmobileservicename.azure-mobile.net/",
    '             "yourclientsecret")
    
  8. Add a line to the UploadChannel function in push.register.cs to invoke this custom controller.

    public async static void UploadChannel()
    {
        var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
        try
        {
            await App.myusernametodolist1234abcClient.GetPush().RegisterNativeAsync(channel.Uri);     
            await App.myusernametodolist1234abcClient.InvokeApiAsync("notifyAllUsers",
                new JObject(new JProperty("toast", "Sample Toast")));
        }
        catch (Exception exception)
        {
            HandleRegisterException(exception);
        }
    }
    
    Public Shared Async Sub UploadChannel()
        Dim channel = Await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync()
        Try
            Await App.myusernametodolist1234abcClient.GetPush().RegisterNativeAsync(channel.Uri)
            Await App.myusernametodolist1234abcClient.InvokeApiAsync("notifyAllUsers", New JObject(new JProperty("toast", "Sample Toast")))
        Catch exception As Exception
            HandleRegisterException(exception)
        End Try
    End Sub
    
  9. Open the shortcut menu for your client project, choose Set As Startup Project, and then start it in the debugger (Keyboard: F5).

    A push notification appears on the screen.

  10. (Optional) Use ALT+TAB keys to return to Visual Studio without closing down your app. If you want to test your app's response to push notifications by sending notifications interactively from Visual Studio, follow the steps in How to send push notifications from Visual Studio.

Summary and next steps

Now you know how to use Mobile Services to add push notification capabilities to your Windows Store app.

Next, consider learning how to use Mobile Services to add the following functionality to your apps:

Schedule recurring jobs in Mobile Services

Work with server scripts in Mobile Services