SignalR Database update notifications in ASP.NET MVC using SQL Dependency

In this we will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC. You can download the source from the Github The following are the steps that we need to enable in the SQL Server first. Step 1: Enable Service Broker on the database The

In this we will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC.

You can download the source from the Github

The following are the steps that we need to enable in the SQL Server first.

Step 1: Enable Service Broker on the database

The following is the query that need to enable the service broker


Step 2: Add Connection string to the Web.Config file

<add name=&rdquo;DefaultConnection&rdquo; connectionString=&rdquo;Server=servername;Database=databasename;User Id=userid;Password=password;&rdquo; providerName=&rdquo;System.Data.SqlClient&rdquo; />

Step 3: Enable SQL Dependency

In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event

public class MvcApplication : System.Web.HttpApplication
        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        protected void Application_Start()
            //Start SqlDependency with application initialization

        protected void Application_End()
            //Stop SQL dependency

Step 4: Install SignalR from the nuget

Run the following command in the Package Manager Console

Install-Package Microsoft.AspNet.SignalR

Step 5: Create SignalR Hub Class

Create MessagesHub class in the Hubs folder

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

        public static void SendMessages()
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();


 Step 6: Get the  Data from the Repository

Create MessagesRepository to get the messages from the database when data is updated.

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

        public IEnumerable<Messages> GetAllMessages()
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                    command.Notification = null;

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

                    if (connection.State == ConnectionState.Closed)

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
            return messages;

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
            if (e.Type == SqlNotificationType.Change)

Step 7:  Register SignalR at startup class

Add the following code


Step 8:  View Page

Create div messagesTable that will append the table data from the database

<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>

Now Add the SignalR related scripts in the page.

getAllMessages is a function that return the partialview data and bind it into the messagesTable div.
<script src="/Scripts/jquery.signalR-2.1.1.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;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
        }).fail(function (e) {

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

Step 9 : Create Partial View Page

Create a partial view _MessagesList.cshtml that returns all the messages.

@model IEnumerable<SignalRDbUpdates.Models.Messages>

    @Html.ActionLink("Create New", "Create")
<table class="table">
        <th>@Html.DisplayNameFor(model => model.MessageID)</th>
            @Html.DisplayNameFor(model => model.Message)
            @Html.DisplayNameFor(model => model.EmptyMessage)
            @Html.DisplayNameFor(model => model.MessageDate)

@foreach (var item in Model) {
            @Html.DisplayFor(modelItem => item.MessageID)
            @Html.DisplayFor(modelItem => item.Message)
            @Html.DisplayFor(modelItem => item.EmptyMessage)
            @Html.DisplayFor(modelItem => item.MessageDate)


Step 10: Set Up the Database

Create the database called blogdemos and run the following script

USE [BlogDemos]

/****** Object:  Table [dbo].[Messages]    Script Date: 10/16/2014 12:43:55 ******/


CREATE TABLE [dbo].[Messages](
	[MessageID] [int] IDENTITY(1,1) NOT NULL,
	[Message] [nvarchar](50) NULL,
	[EmptyMessage] [nvarchar](50) NULL,
	[Date] [datetime] NULL,
	[MessageID] ASC


ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]

Step 11: Run the project

When eve data is inserted into the table the dependency_OnChange method will fire.

Source Code

You can download the source from the Github


Visual Studio 2015 and Apache Cordova

During this article, we are going to learn what Apache Cordova is and in which way this tool is now integrated into Visual Studio 2015.

Visual Studio 2015 and Apache Cordova


Before starting, ask yourself these questions:

  • Which is the proportion of developers being professionnally skilled about web technologies today ?
  • Which is the proportion of developers having a native mobile expertise (crossplatform tools users excepted) ?
  • Which is the proportion of developers which can say they have skill for both web and native mobile ?
  • Which is, among them, the proportion of developers  also competent on multiple mobile platforms ?

The proportion corresponding to this last question is, due to learning time and professionnal profile, more than reduced. Indeed, job market do rarely recruit profiles that are extremly multipurpose just because they are more expensive, but can not perform more than one task at a time. The expertise of a consultant grows then in adequation with this hypothesis. Crossplatform tools like Apache Cordova tend to sensibly increase this last number.

Overview of crossplatform solutions

Between web browser and native mobile operating system, we can quote 3 major tools. Unity, thought to a development usually going to video game is the closest to native. It has the particularity to be very performant but, of course, requires a specific and relatively sharp learning. Xamarin, development tool based on the Mono Project, is much more affordable, especially with .NET developers. It help bringing the benefice of this framework on Microsoft’s foreign platformes. Cordova allow at last, thanks to an almost zero learning curve, to realise mobile and multiplatform applications using the same techniques as mobile oriented web development.






Some history

The Cordova project was during 3 years the PhoneGap project launched by the Adobe corporation, worldwide known for its software suite for multimedia processing: Photoshop, Illustrator, Premiere and After Effect to quote only a few. It was given to the Apache Software Foundation in October 2011 and was graduated top level project in October 2012.

Back in May 2014, Microsoft release the Update 2 of Visual Studio 2013. On this occasion, appears a brand new extension named “Multi-Device Hybrid App”. It allow a better integration of Apache Cordova into Visual Studio through a new project type and a dependencies installer. After this first release which receive a nice echo from in the Microsoft community, a second version appears, and with it new functionnalities, better integration…


More recently, in November 2014 on the occasion of the release of the Visual Studio 2015 Preview, the extension is revamped and renamed “Tools for Apache Cordova”. It is now directly available through the Visual Studio installer from an option. If it is chosen, it trigger a second installer which allow to choose precisely the dependencies you want to install : Ant, Android, Java, NodeJS, and many more.

What Cordova brings

Impossible for a classic website to solicit a customer through its smartphone bypassing the standard channels that are SMS and email. Cordova offers a new dimension to web developers practically inacessible until then: the functionnalities of the device which runs the application. Notifications, geolocalisation, vibrator, camera, storage, … All of these functionnalities, out of range of oriented mobile development and yet essential, allow to access the target of a product in a very much efficient manner.
To allow  using web technologies in a native environnement, Cordova will produce an application during the compilation process with 2 major things:
  • An application with a WebView component, integrated web browser
  • A series of ressources to embed the web application files

Very few code is necessary to integrate Cordova’s API to an existent web page, simply add a fictitious JavaScript file only available after compilation:

<script src="cordova.js"></script>

At last, it is possible to attach a specific event trigger to detect that the API is available and ready to be use:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() { /* INIT */ }

What’s new in Visual Studio

In order to promote crossplatform development using Cordova, Visual Studio add a new project type under the Javascript and TypeScript categories.

In addition to initialize your development with a basic file tree, the IDE also add two new emulators.

Android Emulator

The first one is brand new and is the new concurrent of its little brother : it is the Visual Studio’s Emulator for Android. It is now possible to run and debug our application on an Android emulator directly from Visual Studio, without launching the Android SDK’s emulator. Among the improvements, we notice a startup time that is extremely quicker than its counterpart. Also, it is possible to stimulate some of the APIs of the emulated device like the accelerometer or the GPS.

Ripple Emulator

The second, also a product of the Apache Foundation, is Ripple. It was originally a Chrome extension aimed to test and stimulate Cordova’s APIs in a sensibly quicker environnement. Visual Studio, in addition to open it in a Google Chrome window (interesting opening from Microsoft), do not stop there. It is possible, once you have launched the emulator, to edit the source code of the application and see the emulator update itself to absorbe the usual reset debug time.

Visual Studio should go further soon and propose to deploy for you the application on a physical device and allow you to debug it as simple as local. Currently, there is still an issue keeping the debug mode from activating on a physical device. But the application is indeed deployed and launched. This bug is a known issue, so we shouldn’t wait very long before it is resolved. Android, iOS and Windows Phone are now in the scope of web developers of any level, but not only.

It is important to notice that Cordova do not just target mobile applications. It is also possible to create Windows Store applications or Ubuntu.

Points of interest

Cordova faciliates greatly web developers work and allow to put a first feet  in the mobile development environnement without loosing his bearings. It is by the way possible to keep most of his work habits, especially everything about responsive design which allow to beneficiate of a much more flexible technique than “layout” definition for each desired resolution.

However, it is important to care more about animations, generally realized in JavaScript to be compatible on more web browsers. With a native application, this is not necessary anymore. You can target a specific OS version to insure prerequisites, what we can not on a client station potentially using IE 6 or 7. On the other hand, le CPU and the available RAM are not as important as on a computer yet.

So we should replace “inline” JavaScript animated (what Foundation do, for example) by CSS transitions. Moreover, it is preferable to use new CSS3 functionnalities to impact the GPU when this is relevant in order to avoid a “reflow” phenomenon. We can observe it when an element dimensions are changing, which can temporary slow down the browser during the computing of what this change can do on the rest of the page. For example, it will be much more efficient to use a transition on the “transform” instruction (via “translate”) rather than “top” and “left” coordinates. At last, if optimize his DOM and JavaScript can be seen as unnecessary on a computer, this is much more important on a mobile device.

For example, this CSS will work on more web browsers but will be inefficient:

.slide.inactive {   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 0;   
    left: -100%;   
} {   
    position: relative;   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 1;   
    left: 0;   

This one, on the contrary, will be less compatible but way more performant, since it will not trigger a reflow:

.slide.inactive {   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 0;   
    transform: translateX(-100%);   
    -webkit-transform: translateX(-100%);   
} {   
    position: relative;   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 1;   
    transform: translateX(0);   
    -webkit-transform: translateX(0);   

To go further, we should experiment specialized front-end frameworks like Iconic. It is interesting to notice one of their mantra:

Performance obsessed
Speed is important. So important that you only notice when it isn’t there. Ionic is built to perform and behave great on the latest mobile devices. With minimal DOM manipulation, zero jQuery, and hardware accelerated transitions, one thing is for sure: You’ll be impressed.

To finish, there is a GitHub repository where is hosted the source code of a Cordova « PowerPoint » like application.


Hướng dẫn cài đặt XAMARIN trên Visual Studio 2012

XAMARIN  là nền tản lập trình mới giúp lập trình viên phát triển code trên đa nền tản. Chỉ cần code 1 lần và Buil ra được 3 nền tản trên di động ( Android  – iOS – WinPhone )

Mình sẽ hướng dẫn các bạn cài đặt Xamarin để lập trình trên Visual Studio 2012
Bước 1: Vào trang chủ của Xamarin để download file cài đặt:


Click vào Download now


Chọn Just me ->  sao đó download

Bước 2: Bắt đầu cài đặt
Bạn nên tắt tùy chọn Automatically send troubleshooting information

Chọn Continue


Chọn Next


Check vào I agree to license Items


Chọn Next


Chọn I agree to license tems


Đợi download xong! 1.51Gb


Đợi xong quá trình cài đặt:


Sau khi check hết các icon là hoàn thành quá trình cài đặt:

Bước 3: Xem thành quả và tạo project
Mở Visual Studio 2012 -> chọn new project
+ Android

+ iOS


Chọn iPhone, iPad, . . .