This project is read-only.

Detect record table change with MVC, SignalR, jQuery and SqlTableDependency

SqlTableDependency is a high-level C# component to used to audit, monitor and receive notifications on SQL Server's record table change.

For all Insert/Update/Delete operation on monitored table, TableDependency receive events containing values for the record inserted, changed or deleted, as well as the DML operation executed on the table, eliminating the need of an additional SELECT to update application’s data cache.

Let's assume a SQL Server database table containing stocks value modified constantly:

CREATE TABLE [dbo].[Stocks](
    [Code] [nvarchar](50) NULL,
    [Name] [nvarchar](50) NULL,
    [Price] [decimal](18, 0) NULL

We are going to map those table columns with the following model:

public class Stock
    public decimal Price { get; set; }
    public string Symbol { get; set; }
    public string Name { get; set; }        

Next, we install the NuGet package:

PM> Install-Package SqlTableDependency

Next step is to create a custom hub class, used from the SignalR infrastructure:

public class StockTickerHub : Hub
    private readonly StockTicker _stockTicker;

    public StockTickerHub() :


    public StockTickerHub(StockTicker stockTicker)
        _stockTicker = stockTicker;

    public IEnumerable<Stock> GetAllStocks()
        return _stockTicker.GetAllStocks();

We'll use the SignalR Hub API to handle server-to-client interaction. A StockTickerHub class that derives from the SignalR Hub class will handle receiving connections and method calls from clients. We can't put these functions in a Hub class, because Hub instances are transient. A Hub class instance is created for each operation on the hub, such as connections and calls from the client to the server. So the mechanism that keeps stock data, updates prices, and broadcasts the price updates that have to run in a separate class, which you'll name StockTicker:

public class StockTicker
    // Singleton instance
    private readonly static Lazy<StockTicker> _instance = new Lazy<StockTicker>(
        () => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));

    private static SqlTableDependency<Stock> _tableDependency;

    private StockTicker(IHubConnectionContext<dynamic> clients)
        Clients = clients;

        var mapper = new ModelToTableMapper<Stock>();
        mapper.AddMapping(s => s.Symbol, "Code");

        _tableDependency = new SqlTableDependency<Stock>(

        _tableDependency.OnChanged += SqlTableDependency_Changed;
        _tableDependency.OnError += SqlTableDependency_OnError;

    public static StockTicker Instance
            return _instance.Value;

    private IHubConnectionContext<dynamic> Clients

    public IEnumerable<Stock> GetAllStocks()
        var stockModel = new List<Stock>();

        var connectionString = ConfigurationManager.ConnectionStrings
        using (var sqlConnection = new SqlConnection(connectionString))
            using (var sqlCommand = sqlConnection.CreateCommand())
                sqlCommand.CommandText = "SELECT * FROM [Stocks]";

                using (var sqlDataReader = sqlCommand.ExecuteReader())
                    while (sqlDataReader.Read())
                        var code = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Code"));
                        var name = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Name"));
                        var price = sqlDataReader.GetDecimal(sqlDataReader.GetOrdinal("Price"));

                        stockModel.Add(new Stock { Symbol = code, Name = name, Price = price });

        return stockModel;

    void SqlTableDependency_OnError(object sender, ErrorEventArgs e)
        throw e.Error;

    /// <summary>
    /// Broadcast New Stock Price
    /// </summary>
    void SqlTableDependency_Changed(object sender, RecordChangedEventArgs<Stock> e)
        if (e.ChangeType != ChangeType.None)

    private void BroadcastStockPrice(Stock stock)

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
        if (!disposedValue)
            if (disposing)

            disposedValue = true;


    // This code added to correctly implement the disposable pattern.
    public void Dispose()


Now it's time to see the HTML page:

<!DOCTYPE html>
<html xmlns="">
    <title>SqlTableDependencly with SignalR</title>
    <h1>SqlTableDependencly with SignalR</h1>

    <div id="stockTable">
        <table border="1">
            <thead style="background-color:silver">
                <tr class="loading"><td colspan="3">loading...</td></tr>

    <script src="jquery-1.10.2.min.js"></script>
    <script src="jquery.color-2.1.2.min.js"></script>
    <script src="../Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="../signalr/hubs"></script>
    <script src="SignalR.StockTicker.js"></script>

and how we manage data returned from SignalR in our JavaScript code:

// Crockford's supplant method
if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;

$(function () {
    var ticker = $.connection.stockTicker; // the generated client-side hub proxy
    var $stockTable = $('#stockTable');
    var $stockTableBody = $stockTable.find('tbody');
    var rowTemplate = '<tr data-symbol="{Symbol}"><td>

    function formatStock(stock) {
        return $.extend(stock, {
            Price: stock.Price.toFixed(2)

    function init() {
        return ticker.server.getAllStocks().done(function (stocks) {

            $.each(stocks, function () {
                var stock = formatStock(this);

    // Add client-side hub methods that the server will call
    $.extend(ticker.client, {
        updateStockPrice: function (stock) {
            var displayStock = formatStock(stock);
            $row = $(rowTemplate.supplant(displayStock)),
            $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']').replaceWith($row);

    // Start the connection

In the end, we do not have to forget to register the SignalR route:

[assembly: OwinStartup(typeof(Stocks.Startup))]
namespace Stocks
    public static class Startup
        public static void Configuration(IAppBuilder app)
            // For more information on how to configure your application using OWIN startup, 
            // visit


Last edited Feb 3, 2017 at 7:45 PM by delbianco, version 10