Broadcast SQL Data Using SignalR in ASP.Net

This article explains how to get data from SQL Server and broadcast it using SignalR in ASP.NET.

As we all know SignalR is an ASP.Net server library for adding real-time functionality to a web application. This includes client libraries for JavaScript and other clients.

Getting Started

To get started with SignalR:

  • Start Visual Studio
  • Create a new website
  • Provide the name and location of website
  • Click "Next"

Install SignalR

Click "Tools" | "Library Package Manager" | "Package Manager Console" and run the command: "install-package Microsoft.AspNet.SignalR"

Or

Install using NuGet package Manager, right-click on "Project" and click on "Manage Nuget packages" and search for "SignalR" then click "Install".

 NuGet package Manager

This is the SQL Server database table design.

database table

Table Data

Table Data

Now add a new Hub class and add the following code:

Hub class

using System;

using System.Collections.Generic;
using
System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Hubs;

namespace SignalR_SQLServer_Notification_Hubs

{

    [HubName("notificationHub")]

    public class NotificationHub : Hub

    {

        Int16 totalNewMessages = 0;

        Int16 totalNewCircles = 0;

        Int16 totalNewJobs = 0;

        Int16 totalNewNotification = 0;

 

        [HubMethodName("sendNotifications")]

        public string SendNotifications()

        {

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))

            {

                string query = "SELECT  NewMessageCount, NewCircleRequestCount, NewNotificationsCount, NewJobNotificationsCount FROM [dbo].[Modeling_NewMessageNotificationCount] WHERE UserProfileId=" + "61764";

                connection.Open();

                using (SqlCommand command = new SqlCommand(query, connection))

                {                  

                    command.Notification = null;                

                    DataTable dt = new DataTable();

                    SqlDependency dependency = new SqlDependency(command);

                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)

                        connection.Open();                

                    var reader = command.ExecuteReader();

                    dt.Load(reader);

                    if (dt.Rows.Count > 0)

                    {

                        totalNewMessages = Int16.Parse(dt.Rows[0]["NewMessageCount"].ToString());

                        totalNewCircles = Int16.Parse(dt.Rows[0]["NewCircleRequestCount"].ToString());

                        totalNewJobs = Int16.Parse(dt.Rows[0]["NewJobNotificationsCount"].ToString());

                        totalNewNotification = Int16.Parse(dt.Rows[0]["NewNotificationsCount"].ToString());

                    }

                }  

            }

            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

            return context.Clients.All.RecieveNotification(totalNewMessages, totalNewCircles, totalNewJobs, totalNewNotification);

        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)

        {

            if (e.Type == SqlNotificationType.Change)

            {

                NotificationHub nHub = new NotificationHub();

                nHub.SendNotifications();

            }

        }

    }

}

Run application

Error in Application

Run Successfully

Now add a Startup class.

using System.Web;

using Microsoft.Owin;

using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR_SQLServer_Notification_MVC.Startup))]

namespace SignalR_SQLServer_Notification_MVC

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            app.MapSignalR();

        }

    }

}

UI

<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script>

<script src="~/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript" ></script>

<script src="~/signalr/hubs" type="text/javascript" ></script>

<script type="text/javascript">

    $(function () {       

        // Declare a proxy to reference the hub.          

        var notifications = $.connection.notificationHub;               

        // Create a function that the hub can call to broadcast messages.

        notifications.client.recieveNotification = function (totalNewMessages, totalNewCircles, totalNewJobs, totalNewNotifications) {

            // Add the message to the page.                    

            $('#spanNewMessages').text(totalNewMessages);

            $('#spanNewCircles').text(totalNewCircles);

            $('#spanNewJobNotifications').text(totalNewJobs);

            $('#spanNewNotifications').text(totalNewNotifications);          

        };

        // Start the connection.

        $.connection.hub.start().done(function () {

            notifications.server.sendNotifications();

        }).fail(function (e) {

            alert(e);

        });

        //$.connection.hub.start();

    });

</script>

<h1>New Notifications</h1>

<div>

   <b>You have <span id="spanNewMessages">0</span> New Message Notification.</b><br />

    <b>You have <span id="spanNewCircles">0</span> New Circles Notification.</b><br />

    <b>You have <span id="spanNewJobNotifications">0</span> New Job Notification.</b><br />

    <b>You have <span id="spanNewNotifications">0</span> New Notification.</b>

</div>

 

Run application

Run application



Raj Kumar

Raj Kumar is 2 time Microsoft MVP and 8 time C# Corner MVP. He is working as consultant with lots of hands on experience using ASP.NET, C#, MVC, Angular, Visual Basic .NET, SQL Server, WCF, HTML, JQuery, JavaScript's... Read more

View Previous Comments
 
Karina
Thanks for the excellent example, I didn't find another example SignalR + SQL Server + Asp.net Web
Apr 01, 2020Karina
vivek shandilya
Live data not changed when i inserted one row directly from sql please solve this issue
Oct 08, 2018vivek shandilya
1996 42 0
madhusudhan reddy
I am updating record in Database but its not displayed updated data to UI side and dependency_OnChange not working
Jun 15, 2018madhusudhan reddy
2007 31 0
madhusudhan reddy
Please help on this
Jun 15, 2018madhusudhan reddy
2007 31 0
Atta Rehman
keep it up brother
May 27, 2016Atta Rehman
1998 40 0
Rick Dowdall
Resolved the issue I posted above, a return is not required in the method
Sep 21, 2015Rick Dowdall
2025 13 461
Rick Dowdall
Cannot implicitly convert type 'System.Threading.Tasks.Task<object>' to 'string' on this line in the NotificationHub: context.Clients.All.ReceiveNotification(totalNewMessages, totalNewCircles...
Sep 21, 2015Rick Dowdall
2025 13 461
Rick Dowdall
I have followed the code listed in this tutorial and found a few bugs that I have resolved. I have one left that I have not found a solution for:
Sep 21, 2015Rick Dowdall
2025 13 461
عمق الظلام
solve the problem : return (string)context.Clients.All.RecevieNotification(totalNewMessages, totalNewCircles, totalNewJobs, totalNewNotification).Result; but i have another problem notifications.client.recieveNotification not work , whate should i do , please ?
Sep 16, 2015عمق الظلام
1994 44 0
Naimish Makwana
I got same error "'System.Threading.Tasks.Task<object>' to 'string'" Can any one help please
Aug 22, 2015Naimish Makwana
Shalin Bhavsar
Error got..Cannot implicitly convert type 'System.Threading.Tasks.Task<object>' to 'string'
Jun 10, 2015Shalin Bhavsar
1962 76 0