Skip to content

Latest commit

 

History

History
100 lines (81 loc) · 4.61 KB

app-service-mobile-dotnet-backend-configure-push-google.md

File metadata and controls

100 lines (81 loc) · 4.61 KB

Use the procedure 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. In the Controllers folder, open TodoItemController.cs and add the following using statements:

     using Microsoft.Azure.Mobile.Server.Config;
     using Microsoft.Azure.NotificationHubs;
    
  3. Replace the PostTodoItem method with the following code:

     public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
     {
         TodoItem current = await InsertAsync(item);
         // 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 a new Notification Hub client.
         NotificationHubClient hub = NotificationHubClient
         .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
         // Android payload
         var androidNotificationPayload = "{ \"data\" : {\"message\":\"" + item.Text + "\"}}";
    
         try
         {
             // Send the push notification and log the results.
             var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
    
             // 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");
         }
         return CreatedAtRoute("Tables", new { id = current.Id }, current);
     }
    
  4. Republish the server project.

Node.js backend project

  1. If you haven't already done so, download the quickstart project or else use the online editor in the Azure portal.

  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 http://aka.ms/nodejshubs
     logger.info('Running TodoItem.insert');
    
     // Define the GCM payload.
     var payload = {
         "data": {
             "message": context.item.text
         }
     };   
    
     // 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 GCM native notification.
                 context.push.gcm.send(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 GCM notification that contains the item.text when a new todo item is inserted.

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