Integration And Server Broadcast With SignalR 2

Introduction

The entire procedure demands several steps to finally trigger SignalR Hub. Before starting the implementation let’s learn something basic about SignalR.

What is SignalR?

SignalR is a library for ASP.NET developers that makes the process of real time web functionality simple. The definition of Real Time Web Functionality is the ability to have server code push content to connected client. It provides a simple API in order to create Remote Procedure Call (RPC).

SignalR and Web Socket

The new web socket transport is used by SignalR where available and falls back to older transport where necessary. The most important thing is that we can code our application to make advantage of web socket without thinking about a separate code path.

Implementation

  1. Create a new ASP.NET MVC application.

  2. Add a class named Message.cs in Models folder and include the following properties to the class.
    1. public class Message  
    2. {  
    3.    public int ID { getset; }  
    4.    public string Text { getset; }  
    5.    public DateTime DateTime { getset; }  
    6. }  
  3. Create another class called MessageRepository.cs in Models folder containing the following code.
    1. public class MessageRepository  
    2. {  
    3.     readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
    4.         public List<Message> GetAllMessages()  
    5.         {  
    6.             var messages = new List<Message>();  
    7.             using (var connection = new SqlConnection(_connString))  
    8.             {  
    9.                 connection.Open();  
    10.                 using (var command = new SqlCommand(@"SELECT * FROM [dbo].[Message]", connection))  
    11.                 {  
    12.                     command.Notification = null;  
    13.   
    14.                     var dependency = new SqlDependency(command);  
    15.                       
    16.                     dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  
    17.   
    18.                     if (connection.State == ConnectionState.Closed)  
    19.                         connection.Open();  
    20.                       
    21.                     var reader = command.ExecuteReader();  
    22.   
    23.                     while (reader.Read())  
    24.                     {  
    25.                         messages.Add(item: new Message { ID = (int)reader["ID"], Text = (string)reader["Text"], DateTime = Convert.ToDateTime(reader["DateTime"]) });  
    26.                     }  
    27.                 }  
    28.   
    29.             }  
    30.             return messages;  
    31.   
    32. }  
    33.   
    34. private void dependency_OnChange(object sender, SqlNotificationEventArgs e)  
    35. {  
    36.     {  
    37.      if (e.Type == SqlNotificationType.Change)  
    38.          {  
    39.              MessagesHub.SendMessages();  
    40.          }  
    41.   
    42.     }  
    43. }  
  4. Add a folder and rename it to Hubs. Add a class called MessagesHub.cs in it.
    1. public class MessagesHub : Hub  
    2. {  
    3.      private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();  
    4.   
    5.         [HubMethodName("sendMessages")]  
    6.         public static void SendMessages()  
    7.         {  
    8.             IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();  
    9.             context.Clients.All.updateMessages();  
    10.         }  
    11. }  
    We have to install a nuget package for SignalR using the Nuget Package Manager Console.

    PM> Install-Package Microsoft.AspNet.SignalR.Client.

    pakage manager console

  5. Create a Partial View _MessagePreview.cshtml in Views folder.
    1. @model IEnumerable<ASP_MVC_SignalR_Example.Models.Message>  
    2.   
    3. <table class="table">  
    4.     <thead>  
    5.         <tr>  
    6.             <th>ID</th>  
    7.             <th>Message</th>  
    8.             <th>Date</th>  
    9.         </tr>  
    10.     </thead>  
    11.     <tbody>  
    12.         @foreach (var item in Model)  
    13.         {  
    14.             <tr>  
    15.                 <td>@item.ID</td>  
    16.                 <td>@item.Text</td>  
    17.             </tr>  
    18.         }  
    19.     </tbody>  
    20. </table>  
  6. Under HomeController write a method GetMessages() which will call the GetAllMessage() method from the MessageRepository class and return the partial view binding values.
    1. public ActionResult GetMessages()  
    2. {  
    3.    var mRepository = new MessageRepository();  
    4.    return PartialView("/Home/_MessagePreview.cshtml", mRepository.GetAllMessages());  
    5. }  
  7. Index.cshtml and JS configuration:
    1. @{  
    2.     ViewBag.Title = "Home Page";  
    3. }  
    4.   
    5. <h1>Server Broadcast SignalR Messages:</h1>  
    6. <div class="row">  
    7.     <div class="col-md-12">  
    8.         <div id="messagesTable"></div>  
    9.     </div>  
    10. </div>  
    11. @section Scripts{  
    12.     <script src="/Scripts/jquery.signalR-2.2.0.js"></script>  
    13.     <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>  
    14.     <!--Reference the autogenerated SignalR hub script. -->  
    15.     <script src="/signalr/hubs"></script>  
    16.     <script type="text/javascript">  
    17.         $(function () {  
    18.         // Declare a proxy to reference the hub.  
    19.         var notifications = $.connection.messagesHub;  
    20.   
    21.         //debugger;  
    22.         // Create a function that the hub can call to broadcast messages.  
    23.         notifications.client.updateMessages = function () {  
    24.             getAllMessages()  
    25.   
    26.         };  
    27.         // Start the connection.  
    28.         $.connection.hub.start().done(function () {  
    29.             alert("connection started")  
    30.             getAllMessages();  
    31.         }).fail(function (e) {  
    32.             alert(e);  
    33.         });  
    34.     });  
    35.   
    36.   
    37.     function getAllMessages()  
    38.     {  
    39.         var tbl = $('#messagesTable');  
    40.         $.ajax({  
    41.             url: '/home/GetMessages',  
    42.             contentType: 'application/html ; charset:utf-8',  
    43.             type: 'GET',  
    44.             dataType: 'html'  
    45.         }).success(function (result) {  
    46.             tbl.empty().html(result);  
    47.         }).error(function () {  
    48.   
    49.         });  
    50.     }  
    51.     </script>  
    52.   
    53. }  

Output

Output

Up Next
    Ebook Download
    View all
    Learn
    View all