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 clients. It provides a simple API in order to create a 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 take advantage of the web socket without thinking about a separate code path.

Implementation

Create a new ASP.NET MVC application.

Add a class named Message.cs in the Models folder and include the following properties to the class.

public class Message  
{  
    public int ID { get; set; }  
    public string Text { get; set; }  
    public DateTime DateTime { get; set; }  
}  

Create another class called MessageRepository.cs in the Models folder containing the following code.

public class MessageRepository  
{  
    readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  

    public List<Message> GetAllMessages()  
    {  
        var messages = new List<Message>();  
        using (var connection = new SqlConnection(_connString))  
        {  
            connection.Open();  
            using (var command = new SqlCommand(@"SELECT * FROM [dbo].[Message]", connection))  
            {  
                command.Notification = null;  

                var dependency = new SqlDependency(command);  
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  

                if (connection.State == ConnectionState.Closed)  
                    connection.Open();  

                var reader = command.ExecuteReader();  

                while (reader.Read())  
                {  
                    messages.Add(new Message  
                    {  
                        ID = (int)reader["ID"],  
                        Text = (string)reader["Text"],  
                        DateTime = Convert.ToDateTime(reader["DateTime"])  
                    });  
                }  
            }  
        }  
        return messages;  
    }  

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)  
    {  
        if (e.Type == SqlNotificationType.Change)  
        {  
            MessagesHub.SendMessages();  
        }  
    }  
}  

Add a folder and rename it to Hubs. Add a class called MessagesHub.cs in it.

public class MessagesHub : Hub  
{  
    private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();  

    [HubMethodName("sendMessages")]  
    public static void SendMessages()  
    {  
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();  
        context.Clients.All.updateMessages();  
    }  
}  

We have to install a Nuget package for SignalR using the Nuget Package Manager Console.

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

Nuget Package

Create a Partial View _MessagePreview.cshtml in the Views folder.

@model IEnumerable<ASP_MVC_SignalR_Example.Models.Message>  

<table class="table">  
    <thead>  
        <tr>  
            <th>ID</th>  
            <th>Message</th>  
            <th>Date</th>  
        </tr>  
    </thead>  
    <tbody>  
        @foreach (var item in Model)  
        {  
            <tr>  
                <td>@item.ID</td>  
                <td>@item.Text</td>  
            </tr>  
        }  
    </tbody>  
</table>  

Under HomeController write a method GetMessages() which will call the GetAllMessage() method from the MessageRepository class and return the partial view binding values.

public ActionResult GetMessages()  
{  
    var mRepository = new MessageRepository();  
    return PartialView("/Home/_MessagePreview.cshtml", mRepository.GetAllMessages());  
}  

Index.cshtml and JS configuration

@{  
    ViewBag.Title = "Home Page";  
}  

<h1>Server Broadcast SignalR Messages:</h1>  
<div class="row">  
    <div class="col-md-12">  
        <div id="messagesTable"></div>  
    </div>  
</div>  

@section Scripts {  
    <script src="/Scripts/jquery.signalR-2.2.0.js"></script>  
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>  
    <!--Reference the autogenerated SignalR hub script. -->  
    <script src="/signalr/hubs"></script>  
    <script type="text/javascript">  
        $(function () {  
            // Declare a proxy to reference the hub.  
            var notifications = $.connection.messagesHub;  

            //debugger;  
            // Create a function that the hub can call to broadcast messages.  
            notifications.client.updateMessages = function () {  
                getAllMessages();  
            };  

            // Start the connection.  
            $.connection.hub.start().done(function () {  
                alert("connection started");  
                getAllMessages();  
            }).fail(function (e) {  
                alert(e);  
            });  
        });  

        function getAllMessages()  
        {  
            var tbl = $('#messagesTable');  
            $.ajax({  
                url: '/home/GetMessages',  
                contentType: 'application/html; charset:utf-8',  
                type: 'GET',  
                dataType: 'html'  
            }).success(function (result) {  
                tbl.empty().html(result);  
            }).error(function () {  
                // Handle error  
            });  
        }  
    </script>  
}  

Output

Output


Similar Articles