This post was most recently updated on August 5th, 2024
Technologies Used:
- Visual Studio 2013 Express
- Sql Server 2008 R2 Express
- MVC 5 Nuget
- SqlDependency MSDN
- SignalR 2.0.1 Nuget
- Jquery 2.0.3 Nuget
- Toast Notifications
Script to Create Broker & Service:
create a user called “GeneralUser” with a password of “dbpassword” in your SQl Server logins. Run the following script in a Sql query pane, to create a message broker\service for your database.
Explanation of Code:
SqlDependency
The C# database listener code (below) when initialized, will create a unique database broker\service instance within the database. The Getlist(); method will retrieve the Data from the database and create a listener each time the respective database table is updated, new record inserted or deleted. I am caching the data with within an application variable, so that when a new client connects to the site, they do not have to query the database for the latest defects – this cache will be kept when a change is detected in the database as the method dependency_OnDataChangedDelegate() will be run – thus invalidating the cache
When the SqlDependency is created with the SqlDependency.Start(); command, a new (unique) queue and service objects are created within the database. If I had of provided a name in the start command as a parameter, the queue and service would can have been called this parameter name, instead of a GUID style naming convention.
SignalR Hub
There are two simple methods within the NotificationsHub class, one to push the newly edited database table data to the clients (all the connected clients in this case), and a method to retrieve cached data when a device connects for the first time (performance gain). You will notice that I have put a lock on the code that updates the cache, so that there are no conflicts between threads when performing the update.
JavaScript
This custom script will perform the connection to the SignalR class on the server and create the respective bindings for the controls and notifications. Put this code on master page.
<script src=”/Scripts/jquery-1.8.2.min.js” type=”text/javascript”></script>
<link href=”/Scripts/Toast/css/jquery.toastmessage.css” rel=”stylesheet” type=”text/css” />
<script src=”/Scripts/Toast/jquery.toastmessage.js” type=”text/javascript”></script>
<script src=”/Scripts/jquery.signalR-2.0.1.min.js” type=”text/javascript”></script>
<script type=”text/javascript”>
</script>