SharePoint with SignalR

This sample application uses HTML5 web-sockets to keep multiple clients up to date about changes in a document library. This is achieved by running SignalR in process with SharePoint and having an event handler dispatch messages as changes occur. Getting SignalR to work nicely with SharePoint 2013 requires a few steps. Luckily, Google comes to the rescue and Maximilian Melcher has a nice write-up on whats required  on his blog 1).

Basically SignalR setup is done using an HttpHandlers init method and a virtual path provider is required as SharePoint doesn’t like other applications using paths starting with the tilde character. Once SignalR is up and running, dispatching events is pretty straight forward using the available connection from the GlobalHost.ConnectionManager.

        
public void Init(HttpApplication context)
{
    if (!routeAdded)
    {
        lock (padLock)
        {
            if (!routeAdded)
            {
                RouteTable.Routes.MapConnection("documents", "/relay");
                HostingEnvironment.RegisterVirtualPathProvider(new SignalRVirtualPathProvider());
                routeAdded = true;
            }
        }
    }
}
public override void ItemAdded(SPItemEventProperties properties)
{
    var listItem = properties.ListItem;
    var connection = GlobalHost.ConnectionManager.GetConnectionContext().Connection;
    connection.Broadcast(string.Join(",", new string[] { "Added", listItem.ParentList.ID.ToString(), listItem.ID.ToString(), listItem.Name }));
}

As the client is oblivious to what platform the server is running, getting the client to work with SharePoint is no different from working with any other server running SignalR. A client javascript is provided which makes the whole process from connecting to the server to receiving and sending data, just a few lines long.

var connection = $.connection('/relay');
connection.received(function (data) {
    var parts = data.split(',');
    var action = parts[0];

    switch(action)
    {
        case 'Added':
            $("#documents").append("
" + parts[3] + "
break; } });

The client does not have to be a web page. SignalR also provides a client side .NET library for interacting with the server

static void Main(string[] args)
{
    var connection = new Connection("http://www.server.no/relay");
    connection.Credentials = new NetworkCredential("authenticated", "user", "ASC");
    connection.Received += data => Console.WriteLine(data);
    Console.ReadKey();
}

Video showing two webpages reflecting changes in a documentlibrary

1) http://melcher.it/2012/12/signalr-in-sharepoint-2013-the-real-time-web-is-coming/

One thought on “SharePoint with SignalR

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>