Monday, January 27, 2014

Push notifications in Azure Mobile Services

In this post we will continue our journey of Azure Mobile services and will dig a bit deeper by exploring the push notification tactics. By push notifications, I mean the notification that server would send to its clients. For instance imagine an application that would update the user with the match score. There are two ways this can be done.

1. The client would query server every minute to get the recent updates.
2. The server would send the notification to client every time score changes.

The first process is resource intensive, and if the client is a mobile application, then the application will suck the battery drastically. The second process, however, is well and good and also do not have the above consequences to serve.

In this post we will see how we can implement the second process in a windows phone 8 application.

The Process

To send push notification from server to client, the server should know its client. There should be channel, that exists between client and server, that stay idle unless server has something that clients need to know.
In this post we will see that every time a device runs the application, the application acquires a channel (which is basically a URL), and execute an insert operation to insert the acquired channel in the database and withal send a “Hello” message to all the other clients which are already their in the database on calling an API method. So, let’s begin coding by creating the client application.

I suggest novices to read Consuming Azure Mobile Services before proceeding with this post.

The Client Code

In the new windows phone 8 application, after importing the Azure Mobile service package via nuget, create a static property of type HTTPNotificationChannel.

   1: public static HttpNotificationChannel CurrentChannel { get; private set; }

Following is the method that Create the new Channel if do not exists else use the previous channel to get the Channel URI.


   1: private async void AcquirePushChannel()
   2: {
   3:    try
   4:    {
   5:        CurrentChannel = HttpNotificationChannel.Find("Channel");
   6:  
   7:        if (CurrentChannel == null)
   8:        {
   9:            CurrentChannel = new HttpNotificationChannel("Channel");
  10:  
  11:            if (CurrentChannel.ConnectionStatus 
  12:                     != ChannelConnectionStatus.Disconnected)
  13:            {
  14:                CurrentChannel.Close();
  15:                CurrentChannel.Open();
  16:  
  17:            }
  18:  
  19:            if (!CurrentChannel.IsShellToastBound)
  20:            {
  21:                CurrentChannel.UnbindToShellToast();
  22:                CurrentChannel.BindToShellToast();
  23:            }
  24:  
  25:            
  26:            if (CurrentChannel.ChannelUri != null)
  27:            {
  28:                 //Do the insert table operation               
  29:            }
  30:        }
  31:    }
  32:    catch (Exception ex)
  33:    {
  34:    }            
  35: }

Inside the if condition, the channeluri is to be written in the database. If you have read the suggested post, you would have already realized how to insert the data in the database. So inserting the data into the table “registration”, the code would be like:


   1: var registration = new Registration 
   2:     { Handle = CurrentChannel.ChannelUri.ToString() };
   3: await registrationsTable.InsertAsync(registration);

Now on a button click, call the API method to send the Notification to all the clients.


   1: var response = 
   2:     await MobileService.InvokeApiAsync("sendnotification",HttpMethod.Get,null);

The CurrentChannel object has following events.


   1: private void InitializeHandlers()
   2: {
   3:     CurrentChannel.ErrorOccurred += CurrentChannel_ErrorOccurred;
   4:     CurrentChannel.ShellToastNotificationReceived += 
   5:                 CurrentChannel_ShellToastNotificationReceived;
   6:     CurrentChannel.HttpNotificationReceived += 
   7:                 CurrentChannel_HttpNotificationReceived;
   8:     CurrentChannel.ChannelUriUpdated += CurrentChannel_ChannelUriUpdated;
   9: }

The event ShellToastNotificationRecieved would hit when the app receives the notification which the server send.
 
The Server Code

In the Mobile service, create an API, sendnotification. For any query, read Creating Custom API in Azure Mobile Service. As you can see in the API call, we are calling the API as GET HTTP verb, so we need to write the code into the GET portion of the API.


   1: exports.get = function(request, response) {
   2:  
   3:     var registration = request.service.tables.getTable('registration');
   4:  
   5:     registration.read({
   6:  
   7:             success: function(registrationItems){
   8:  
   9:                 registrationItems.forEach(function(item){
  10:  
  11:                     push.mpns.sendToast(item.channel, {
  12:                                        text1:'Hello'
  13:                                    }, {
  14:                                         success: function () {
  15:                                             console.log("Push Sent.");
  16:                                         }
  17:                                     });
  18:  
  19:                 });
  20:  
  21:             }
  22:             
  23:         });
  24:  
  25: }


As the API call is made, we first get the table ‘registration’ where the entries of the clients are saved. If the read table is a success, we then loop through the entire data and send the message ‘Hello’ to each client using the uri in the ‘channel’.

I hope you would like the post.

Happy Coding!!!
Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top