Push Notification In Web Application Using Web API And PushContentStream

The push notification is the technology which allow the user engaged to the particular site or application. It can be any kind of chat, discussion or anything. It engage the users to the particular content or activity.

Introduction

Push Notification is the technology that allows the users to engage with the particular site or application. It can be any kind of chat, discussion or anything. It engages the users to the particular content or activity.

Push notification is the combination of two words. The term push is kind of information that is supplied by the server and notification is the action that is performed by the web through a script that is the information available to the user.

This article will demonstrate how you can subscribe to a data stream and receive data pushed at the same time on the server-side using Web API. In this demo, you as a client will subscribe to a service allowed by Web API and send the kind of chat message, that will be notified to the all the clients subscribed and you will see the messages of chat having numbers of client subscribed.

Let us have a brief introduction to the technology we used here to achieve the notification.

ConcurrentBag

It is nothing but the collection of values. It allows us to safely add and retrieve the result from a collection of values. This collection is useful when multiple threads access it.

StreamWriter

It is a class required to writes text data and files. It enables easy and efficient text output to the stream.

EventSource

It’s a web content’s interface to server-sent events. It opens a persistent connection to the HTTP server which sends events in text/event-stream format. Connection opens until we call EventSource.close() method.

Prerequisite

  1. Programming of C#.
  2. Knowledge of JavaScript and Jquery.

Implementation

  1. Open Visual Studio.
  2. Create a new project.
  3. Enter the project name and select location.

    ASP.NET

  4. Select Web API from the template.

    ASP.NET

  5. Add ChatMessage Class inside Models directory.
    1. namespace PushNotification1.Models  
    2. {  
    3.     public class ChatMessage  
    4.     {  
    5.         public string username { get; set; }  
    6.         public string text { get; set; }  
    7.         public string dt { get; set; }  
    8.     }  
    9. }  
  1. Add web API Controller name – ChatController.

    ASP.NET

    ASP.NET
  1. Write the below content inside ChatController.cs.
    1. using System;  
    2. using System.Collections.Concurrent;  
    3. using System.Diagnostics;  
    4. using System.IO;  
    5. using System.Linq;  
    6. using System.Management;  
    7. using System.Net;  
    8. using System.Net.Http;  
    9. using System.Threading.Tasks;  
    10. using System.Timers;  
    11. using System.Web.Http;  
    12. using Newtonsoft.Json;  
    13. using PushNotification1.Models;  
    14.   
    15. namespace PushNotification1.Controllers  
    16. {  
    17.     public class ChatController : ApiController  
    18.     {  
    19.   
    20.         private static ConcurrentBag<StreamWriter> clients;  
    21.         static ChatController()  
    22.         {  
    23.             clients = new ConcurrentBag<StreamWriter>();  
    24.         }  
    25.   
    26.         public async Task PostAsync(ChatMessage m)  
    27.         {  
    28.             m.dt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");  
    29.             await ChatCallbackMsg(m);  
    30.         }  
    31.         private async Task ChatCallbackMsg(ChatMessage m)  
    32.         {  
    33.             foreach (var client in clients)  
    34.             {  
    35.                 try  
    36.                 {  
    37.                     var data = string.Format("data:{0}|{1}|{2}\n\n", m.username, m.text, m.dt);  
    38.                     await client.WriteAsync(data);  
    39.                     await client.FlushAsync();  
    40.                     client.Dispose();  
    41.                 }  
    42.                 catch (Exception)  
    43.                 {  
    44.                     StreamWriter ignore;  
    45.                     clients.TryTake(out ignore);  
    46.                 }  
    47.             }  
    48.         }  
    49.   
    50.         [HttpGet]  
    51.         public HttpResponseMessage Subscribe(HttpRequestMessage request)  
    52.         {  
    53.             var response = request.CreateResponse();  
    54.             response.Content = new PushStreamContent((a, b, c) =>  
    55.             { OnStreamAvailable(a, b, c); }, "text/event-stream");  
    56.             return response;  
    57.         }  
    58.   
    59.         private void OnStreamAvailable(Stream stream, HttpContent content,  
    60.             TransportContext context)  
    61.         {  
    62.             var client = new StreamWriter(stream);  
    63.             clients.Add(client);  
    64.         }  
    65.     }  
    66. }  
  1. Create a JavaScript file named ChatScript.js under Scripts directory and write the below contents.
    1. $(document).ready(function () {  
    2.     $('#chatControl').hide();  
    3. });  
    4. var message = { username: '', text: '', dt: '' };  
    5. function setUser() {  
    6.     var username = document.getElementById("username").value;  
    7.     if (username == "" || username == undefined) {  
    8.         alert('please enter username');  
    9.         return;  
    10.     }  
    11.     else {  
    12.         message.username = username;  
    13.         $('#chatControl').show();  
    14.         $('#chatTemplate').empty();  
    15.         $('#start').hide();  
    16.         $('#message').text("Welcome to Just chat :" + message.username).css("font-weight""Bold");  
    17.     }  
    18. }  
    19. function Send() {  
    20.   
    21.     message.text = document.getElementById("push").value;  
    22.     $.ajax({  
    23.         url: "http://localhost:50536/api/Chat/",  
    24.         data: JSON.stringify(message),  
    25.         cache: false,  
    26.         type: 'POST',  
    27.         dataType: "json",  
    28.         contentType: 'application/json; charset=utf-8'  
    29.     });  
    30.     $("#push").val('');  
    31. }  
    32.   
    33. var source = new EventSource('http://localhost:50536/api/Chat/');  
    34.   
    35. source.onmessage = function (e) {  
    36.     var data = e.data.split('|');  
    37.     var username = $("<strong></strong>").text(data[0] + " : ");  
    38.     var text = $("<i></i>").text(data[1]);  
    39.     var dt = $("<div></div>").text(data[2]);  
    40.     var chatTemp = document.createElement("p");  
    41.     chatTemp.append(dt[0], username[0], text[0], document.createElement("br"));  
    42.     $('#chatTemplate').append(chatTemp);  
    43. };  
  1. Modify the content of Index.cs under Views\Home directory.
    1. <script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>  
    2. <script src="@Url.Content("~/Scripts/ChatScript.js")" type="text/javascript"></script>  
    3. <h2>Just Chat</h2>  
    4. <body style="background-color: chartreuse">  
    5. <div id="body">  
    6.     <section>  
    7.         <div id="chatTemplate">  
    8.         </div>  
    9.         <div id="start">  
    10.             <label for="username">Enter username to start chatting</label>  
    11.             <input type="text" id="username" />  
    12.             <input type="button" value="set user" onclick="setUser()" />  
    13.         </div>  
    14.         <div id="message"></div>  
    15.         <div id="chatControl">  
    16.             <textarea type="text" id="push"></textarea>  
    17.             <button id="pushbtn" onclick="Send()">Send</button>  
    18.         </div>  
    19.     </section>  
    20. </div>  
    21. </body>  

Let us run the application and see what we have achieved.

Note

  1. For testing purpose, open the same URL in three tabs.
  2. Enter three different names and click on "set user" for each tab.
  3. Send a message from any user. It will be broadcast to all the users in open tabbed that are subscribed for notification.
  4. You can see the below images for its working.

    ASP.NET

    Enter a Username and click on "set user".

    ASP.NET

    ASP.NET

    The same is set for other two users.

    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET
    ASP.NET