Azure Push Notification with Web API


Before explaining how to to push notification to hub using Web API, let us see what is azure push notifications hub provides.
Azure Notification Hubs provide an easy-to-use, multiplatform, scaled-out push infrastructure that enables you to send mobile push notifications from any backend (in the cloud or on-premises) to any mobile platform.
With Notification Hubs you can easily send cross-platform, personalized push notifications, abstracting the details of the different platform notification systems (PNS). With a single API call, you can target individual users or entire audience segments containing millions of users, across all their devices.
Step 1 : Create Push Notification Hub
  1. Log on to the Azure Portal, and then click +NEW at the top left of the screen.
  2. Click on New, then Web + Mobile. Scroll down if necessary and click Notification Hub.
  3. Add All the details and create the hub
  4. image
Step 2 : Add Keys
After creating the hub next you need to add keys for each mobile platform you support. Creating keys for each platform are described here
IOS
After you have created the keys, go
Notification Hub –> Settings->Notification Services_> Select the platform you want to add the key then save. Now your hub is ready to send send receive notifications
image
Step 3 : Register with notification Hub
Now we can write the Web API call which allows mobile app to call and register with the hub.
Push notifications are sent to tags. When registering mobile device need to send the device token and tags they want to register.
Ex:- Suppose you push notification related to specific user to inform some action. Then we should have a tag with user name.
Create a class which will be used as the request for the API Call

   public class NotificationRegistration  
   {  
     public string Platform { get; set; }  
     public string DeviceToken { get; set; }  
     public string[] Tags { get; set; }  
   }  


Then Create a class which handles push notifications of your application and add Nuget and  the following using statement
using Microsoft.Azure.NotificationHubs;
 
After that you need to create hub connection string. You can copy it from azure portal.
Go to Hub –> Settings –> Access Policies 
 
  public class PushNotificationService  
   {  
     static string connectionString = ConfigurationManager.AppSettings["HubConnectionString"];  
    static string name = ConfigurationManager.AppSettings["Hubname"];  
     private NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, name);  
     public PushNotificationService()  
     {  
     }  
     public async Task<HttpResponseMessage> Regsiter(NotificationRegistration notificationRegistration)  
     {  
       string registrationId =await GetRegistrationId(notificationRegistration.DeviceToken);  
       return await RegiterForTags(registrationId, notificationRegistration);  
     }  
     private async Task<HttpResponseMessage> RegiterForTags(string registrationId, NotificationRegistration notificationRegistration)  
     {  
       RegistrationDescription registration = null;  
       switch (notificationRegistration.Platform)  
       {  
         case "apns":  
           registration = new AppleRegistrationDescription(notificationRegistration.DeviceToken);  
           break;  
         case "gcm":  
           registration = new GcmRegistrationDescription(notificationRegistration.DeviceToken);  
           break;  
       }  
       registration.RegistrationId = registrationId;  
       registration.Tags = new HashSet<string>(notificationRegistration.Tags);  
       try  
       {  
         await hub.CreateOrUpdateRegistrationAsync(registration);  
       }  
       catch (MessagingException e)  
       {  
         ReturnGoneIfHubResponseIsGone(e);  
       }  
       return new HttpResponseMessage(HttpStatusCode.OK);  
     }  
     private static void ReturnGoneIfHubResponseIsGone(MessagingException e)  
     {  
       var webex = e.InnerException as WebException;  
       if (webex.Status == WebExceptionStatus.ProtocolError)  
       {  
         var response = (HttpWebResponse)webex.Response;  
         if (response.StatusCode == HttpStatusCode.Gone)  
           throw new HttpRequestException(HttpStatusCode.Gone.ToString());  
       }  
     }  
     private async Task<string> GetRegistrationId(string userName)  
     {  
       string newRegistrationId = null;  
       if (userName != null)  
       {  
         var registrations = await hub.GetRegistrationsByChannelAsync(userName, 100);  
         foreach (RegistrationDescription registration in registrations)  
         {  
           if (newRegistrationId == null)  
           {  
             newRegistrationId = registration.RegistrationId;  
           }  
           else  
           {  
             await hub.DeleteRegistrationAsync(registration);  
           }  
         }  
       }  
       if (newRegistrationId == null)  
         newRegistrationId = await hub.CreateRegistrationIdAsync();  
       return newRegistrationId;  
     }  
 }  


Then Create a web api call so your mobile application can make a request and register for the push notifications for each device

    [HttpPost]  
     public async Task<HttpResponseMessage> Regsiter(NotificationRegistration notificationRegistration)  
     {  
       return await new PushNotificationService().Regsiter(notificationRegistration);  
     }  


Step 4 : Deregister with notification Hub
Sometimes users turn off receiving push notifications also it is a practice we don’t send push notifications to the user it that user is logged out from our app from the given device. In such scenarios we have deregister from the notifications. As a practice regiter is called when user logs in and deregister is called when log out. These will fully depend on your application requirements.
 
For that create a method in PushNotificationSerice.cs for deregistrations
 
    public async Task<HttpResponseMessage> DeRegister(string deviceToken)  
     {  
       string registrationId = await GetRegistrationId(deviceToken);  
       if (registrationId == null)  
       {  
         return new HttpResponseMessage(HttpStatusCode.NotAcceptable);  
       }  
       await hub.DeleteRegistrationAsync(registrationId);  
       return new HttpResponseMessage(HttpStatusCode.OK);  
     }  
 
Then create a web API call for deregiter
 
  [HttpGet]  
     public async Task<HttpResponseMessage> DeRegister(string deviceToken)  
     {  
       return await new PushNotificationService().DeRegister(deviceToken);  
     }  
Step 5: Send Notification
Now your application is ready to send push notifications using azure push notification hub. You can use following code to send notifications
  public async Task<bool> SendNotification(SendNotificationRequest sendNotificationRequest)  
     {  
       string[] userTag = new string[1];  
       userTag[0] = sendNotificationRequest.Tag;  
       NotificationOutcome outcome = null;  
       //IOS  
       var alert = "{\"aps\":{\"alert\":\"" + sendNotificationRequest.Message + "\",\"content-available\":1,\"sound\":\"default\"}}";  
       outcome = await hub.SendAppleNativeNotificationAsync(alert, userTag);  
       // Android  
       var notif = "{ \"data\" : {\"message\":\"" + sendNotificationRequest.Message + "\"}}";  
       outcome = await hub.SendGcmNativeNotificationAsync(notif, userTag);  
       if (outcome != null)  
       {  
         if (!((outcome.State == NotificationOutcomeState.Abandoned) ||  
           (outcome.State == NotificationOutcomeState.Unknown)))  
         {  
           _notificationRepository.Create(new Domain.Entities.Notification  
           {  
             UserId = sendNotificationRequest.UserId,  
             Description = sendNotificationRequest.Message,  
             IconUrl = sendNotificationRequest.IconUrl  
           });  
           return true;  
         }  
       }  
       return false;  
     }  

Hope this helps

Happy Coding !!

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Thanks for posting your article, It would be helpful for me.

    Regards,
    Website Design & Development Company India | Jamure By Ranjit

    ReplyDelete
  4. If you've got an e-commerce website then push notifications will help improve your sales. If you're active on that website, it can help you to have quite a bit of visitors to your website.

    ReplyDelete
  5. Use social networking sites such as Facebook and Twitter to advertise. For more information on leads for your business, read me.

    ReplyDelete

  6. INDIGITALL also has an API, it has been developed with the latest technology to guarantee maximum effectiveness and simplify the process of creating and sending Notifications with an animated image, Segmented, Geolocated and many more functions, it is great. Here you can see the simple installation for your platform
    https://docs.indigitall.com/

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5