Second Life of a Hungarian SharePoint Geek

March 31, 2014

How to Integrate SignalR 2.0 in SharePoint 2010

Filed under: SignalR, SP 2010 — Tags: , — Peter Holpar @ 23:54

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications.” as stated on the official site of SignalR.

Recently I needed to find a solution that supports push-like notifications for a SharePoint 2010 web-based administration tool that should run in the background but should send notifications occasionally to the user started the request. Most of the forum discussions suggested SignalR, and the information and samples I found about this library on the web (like the above-mentioned official site or these tutorials) were really convincing.

Probably the most difficult part of the SharePoint 2010SignalR integration is the different .NET Framework version they use (.NET Framework 3.5, that is Common Language Runtime (CLR) 2.0 vs. .NET Framework 4.5, that is CLR 4.0). To bridge this gap we should include some kind of out-of-process communication channel (typically HTTP-based) that mediates between the parties.

Unfortunately, most of the SharePoint-related samples are either jokes (like the April Fools post about SharePointR exactly 2 years ago), outdated (for example using SignalR 1.x, like this solution), and / or based on SharePoint 2013 (like the posts here, here or this CodePlex solution).

To to make a long story short, I decided to create my own implementation for SharePoint 2010 using SignalR 2.0, and base the implementation on a WCF service as opposed to this HTTP Handler-based solution.

Solution Architecture

My solution contains four projects:

TaskNotifierService is an IIS hosted WCF service that acts as the SignalR Hub as well. It is a CLR 4.0  process.

SPTaskNotifier is a SharePoint 2010 application (that means CLR 2.0). There is an event receiver in this project, that calls the WCF service in the TaskNotifierService if a new task is assigned to a user. There are some simple JavaScript functions as well that support the SignalR integration on the client side, like registering the client and displaying notifications if a task was assigned to the current user.

TaskNotifierTestWeb is a simple web application. The project is based on the .NET Framework 4.5, but it is irrelevant as we use only client side code in an .html page. The goal of the project is to simplify testing the JavaScript code that interacts with SignalR without involving the SharePoint deployment process (like IISRESET etc.).

TaskNotifierTestConsole is a console application based on the .NET Framework 4.5. Again, the framework version is not important, any version that supports WCF would be OK. This application can be used to send test messages to the WCF host, and thus test the code that creates the WCF client proxy and calls the WCF service methods. Using this project we can test the functionality without SharePoint as well. If your goal is just to send test messages, but you are not interested in the code itself, you can use the WCF Test Client of Visual Studio either (more about that later).

Below is the architecture of these components including the possible connections between them. The core and indispensable component is the TaskNotifierService. The other components are optional. For example you can use either the TaskNotifierTestConsole, the SPTaskNotifier or the WCF Test Client to sent messages (e.g. call the WCF service method) to the TaskNotifierService, and it will forward the messages to the adequate client, let it be either the TaskNotifierTestWeb or the SPTaskNotifier.

image

TaskNotifierService

We start our code review with the core component, the TaskNotifierService. We define the data and service contracts of our WCF service in this project.

The TaskNotification is the data contract of the communication. It includes the Title of the new task, the LoginName of the user the task is assigned to and the URL of the display form of the task item.

  1. [DataContract]
  2. public class TaskNotification
  3. {
  4.   // the login name of the user the task is assigned to
  5.   [DataMember]
  6.   public string LoginName { get; set; }
  7.  
  8.   // the url of the task display form
  9.   [DataMember]
  10.   public string Url { get; set; }
  11.  
  12.   // the title of the task
  13.   [DataMember]
  14.   public string Title { get; set; }
  15. }

The ITaskNotifierService interface is the service contract, including only a single method called TaskCreated. This method has a single parameter of type TaskNotification.

  1. [ServiceContract]
  2. public interface ITaskNotifierService
  3. {
  4.   [OperationContract]
  5.   void TaskCreated(TaskNotification taskNotification);
  6. }

The TaskNotifierService class implements the ITaskNotifierService interface. In the implementation of the TaskCreated method we first get an instance of the current ConnectionManager then get the hub context via its GetHubContext<TaskNotifierHub> method. Finally we collects the client connections using the contextfor the user the task was assigned to (taskNotification.LoginName) and call the addTaskMessage method of these connections including the task title and URL as parameters (taskNotification.Title and taskNotification.Url):

  1. using System;
  2. using System.Diagnostics;
  3. using Microsoft.AspNet.SignalR;
  4. using Microsoft.AspNet.SignalR.Infrastructure;
  5.  
  6. namespace TaskNotifierService
  7. {
  8.   // NOTE: In order to launch WCF Test Client for testing this service, please select TaskNotifierService.svc or TaskNotifierService.svc.cs at the Solution Explorer and start debugging.
  9.   // NOTE:  WCF Test Client issue with '\' in LoginName. Escape it as '\\', like 'domain\\user' instead of 'domain\user'
  10.   // http://connect.microsoft.com/VisualStudio/feedback/details/632374/wcf-test-client-sends-incorrect-null-value-as-string-type-value-for-wrongly-escaped-entered-values
  11.   public class TaskNotifierService : ITaskNotifierService
  12.   {
  13.     public void TaskCreated(TaskNotification taskNotification)
  14.     {
  15.       Debug.Print("Task with title '{0}' was created.", taskNotification.Title);
  16.       IConnectionManager connectionManager = GlobalHost.ConnectionManager;
  17.       var context = connectionManager.GetHubContext<TaskNotifierHub>();
  18.  
  19.       context.Clients.Group(taskNotification.LoginName.ToUpper()).addTaskMessage(taskNotification.Title, taskNotification.Url);
  20.     }
  21.   }
  22. }

Note: We call the ToUpper method on the LoginName to make it case-insensitive, see the same for the Context.User.Identity.Name in the OnConnected method of the TaskNotifierHub below.

Our TaskNotifierHub class is a subclass of a SignalR Hub class. Whenever a new client is connected to the hub, we determine the user name corresponding the connection and assign the connection ID to the group identified by the user name.

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNet.SignalR;
  4.  
  5. namespace TaskNotifierService
  6. {
  7.   [Authorize]
  8.   public class TaskNotifierHub : Hub
  9.   {
  10.     public override Task OnConnected()
  11.     {
  12.       string name = Context.User.Identity.Name.ToUpper();
  13.  
  14.       Groups.Add(Context.ConnectionId, name);
  15.  
  16.       return base.OnConnected();
  17.     }
  18.   }
  19. }

The Startup class is responsible for the startup of our service hub. In its Configuration method we set up the configuration settings that enable accessing the hub from an external web site (see CORS, Cross-Origin Resource Sharing) and finally start the SignalR pipeline.

  1. using Microsoft.AspNet.SignalR;
  2. using Microsoft.Owin;
  3. using Microsoft.Owin.Cors;
  4. using Owin;
  5.  
  6. [assembly: OwinStartup(typeof(TaskNotifierService.Startup))]
  7.  
  8. namespace TaskNotifierService
  9. {
  10.   public class Startup
  11.   {
  12.     public void Configuration(IAppBuilder app)
  13.     {
  14.       // Branch the pipeline here for requests that start with "/signalr"
  15.       app.Map("/signalr", map =>
  16.       {
  17.         // Setup the CORS middleware to run before SignalR.
  18.         // By default this will allow all origins. You can
  19.         // configure the set of origins and/or http verbs by
  20.         // providing a cors options with a different policy.
  21.         map.UseCors(CorsOptions.AllowAll);
  22.         var hubConfiguration = new HubConfiguration
  23.         {
  24.           // You can enable JSONP by uncommenting line below.
  25.           // JSONP requests are insecure but some older browsers (and some
  26.           // versions of IE) require JSONP to work cross domain
  27.           EnableJSONP = true
  28.         };
  29.         // Run the SignalR pipeline. We're not using MapSignalR
  30.         // since this branch already runs under the "/signalr"
  31.         // path.
  32.         map.RunSignalR(hubConfiguration);
  33.       });
  34.     }
  35.   }
  36. }

TaskNotifierTestConsole

The second project, TaskNotifierTestConsole is a simple WCF client to test the WCF service hosted in IIS (see TaskNotifierService above), so a Service reference to the TaskNotifierService was added to this project.

  1. static void Main(string[] args)
  2. {
  3.   // TODO Update the login name to match the user's login name that is authenticated in the browser
  4.   SendTaskNotification("CONTOSO\\Administrator", "Test Task Title", "http://site/task&quot;);
  5. }

In the SendTaskNotification method we create a WCF proxy instance and call its TaskCreated method with the test parameters.

  1. private static void SendTaskNotification(string loginName, string title, string url)
  2. {
  3.   TaskNotifierServiceClient sc = TaskNotifierProxy;
  4.   sc.TaskCreated(new TaskNotification
  5.                         {
  6.                           LoginName = loginName,
  7.                           Title = title,
  8.                           Url = url
  9.                         });
  10. }

The configuration of the proxy (WCF bindings, etc.) are set from code, see TaskNotifierProxy property later at the TaskCreated event receiver of the SPTaskNotifier project. Of course, you could set the same values from a configuration file as well.

TaskNotifierTestWeb

The third project in the solution is the TaskNotifierTestWeb project. In this project we have a single page, default.htm that includes the communication JavaScript methods. We first include the references to the required JavaScript libraries, set up the hub URL, declare a proxy to reference the hub. Next a function is created that the hub can call to send notifications. In this case we simply append the information as a span to the current HTML page. Finally the connection is started.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Task Notifier Test Page</title>
  5. </head>
  6. <body>
  7.     <div class="container">
  8.         <ul id="discussion">
  9.         </ul>
  10.     </div>
  11.     <!–Script references. –>
  12.     <!–TODO: Update the URLs to match your current configuration –>
  13.     <!–Reference the jQuery library. –>
  14.     <script src="http://localhost:57800/Scripts/jquery-1.6.4.min.js&quot; ></script>
  15.     <!–Reference the SignalR library. –>
  16.     <script src="http://localhost:57800/Scripts/jquery.signalR-2.0.2.min.js"></script>
  17.     <!–Reference the autogenerated SignalR hub script. –>
  18.     <script src="http://localhost:57800/signalr/hubs"></script>
  19.     <!–Add script to update the page and send messages.–>
  20.     <script type="text/javascript">
  21.         $(function () {
  22.             $.connection.hub.url = "http://localhost:57800/signalr&quot;;
  23.             // Declare a proxy to reference the hub.
  24.             var taskNotifier = $.connection.taskNotifierHub;
  25.             // Create a function that the hub can call to send notifications.
  26.             taskNotifier.client.addTaskMessage = function (title, url) {
  27.                 var anchor = $('<a />').attr('href', url).attr('target', '_blank').text(title);
  28.                 var anchorText = $('<span />').append(anchor).html();
  29.                 var text = "A task called '" + anchorText + "' was assigned to you.";
  30.                 $('#discussion').append(text).append('<br />');
  31.             };
  32.             // Start the connection.
  33.             $.connection.hub.start();
  34.         });
  35.     </script>
  36. </body>
  37. </html>

Important, that Windows Authentication should be enabled for the web site, otherwise the hub cannot determine the user name on the client connection.

SPTaskNotifier

The SPTaskNotifier is a simple SharePoint project that includes an event receiver that is triggered whenever a new item is created in a Tasks list.

First, we register our event handler to all lists created from the Tasks list template:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  3.   <Receivers ListTemplateId="107">
  4.       <Receiver>
  5.         <Name>TaskCreated</Name>
  6.         <Type>ItemAdded</Type>
  7.         <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
  8.         <Class>SPTaskNotifier.TaskCreated</Class>
  9.         <SequenceNumber>10000</SequenceNumber>
  10.       </Receiver>
  11.   </Receivers>
  12. </Elements>

In the ItemAdded method of the TaskCreated class we determine the Title and the owner of the new task, as well as the URL of the display form, and call the SendTaskNotification method with this parameters.

  1. public override void ItemAdded(SPItemEventProperties properties)
  2. {
  3.   Debug.Print("SPTaskNotifier.TaskCreated started.");
  4.  
  5.   try
  6.   {
  7.     SPListItem task = properties.ListItem;
  8.     if (task != null)
  9.     {
  10.       SPFieldUserValue userFieldValue = new SPFieldUserValue(properties.Web, task[SPBuiltInFieldId.AssignedTo] as string);
  11.       if ((userFieldValue != null) && (userFieldValue.User != null))
  12.       {
  13.         string url = string.Format("{0}{1}?ID={2}", properties.Web.Url, properties.List.DefaultDisplayFormUrl, task.ID);
  14.         this.SendTaskNotification(userFieldValue.User.LoginName, task.Title, url);
  15.       }
  16.       else
  17.       {
  18.         Debug.Print("SPTaskNotifier.TaskCreated: No user assigned to task ID={0}", task.ID);
  19.       }
  20.     }
  21.     else
  22.     {
  23.       Debug.Print("SPTaskNotifier.TaskCreated: No task found");
  24.     }
  25.  
  26.     base.ItemAdded(properties);
  27.   }
  28.   catch (Exception ex)
  29.   {
  30.     Debug.Print("SPTaskNotifier.TaskCreated exception: {0}\r\n{1}", ex.Message, ex.InnerException);
  31.   }
  32.  
  33.   Debug.Print("SPTaskNotifier.TaskCreated finished.");
  34. }

The SendTaskNotification method is very similar to the version we saw in the case of the TaskNotifierTestConsole project above, but includes a few lines that help debugging and tracing.

  1. private void SendTaskNotification(string loginName, string title, string url)
  2. {
  3.   Debug.Print("SPTaskNotifier.SendTaskNotification started. loginName='{0}'; title='{1}'; url='{2}'",
  4.     loginName, title, url);
  5.  
  6.   TaskNotifierServiceClient sc = TaskNotifierProxy;
  7.  
  8.   sc.TaskCreated(new TaskNotification
  9.   {
  10.     LoginName = loginName,
  11.     Title = title,
  12.     Url = url
  13.   });
  14.  
  15.   Debug.Print("SPTaskNotifier.SendTaskNotification finished.");
  16. }

Since we call the TaskNotifierService, we should add a Service reference to this project as well. The WCF client proxy is configured dynamically from code.

  1. private static TaskNotifierServiceClient TaskNotifierProxy
  2. {
  3.   get
  4.   {
  5.     {
  6.       var binding = new BasicHttpBinding
  7.       {
  8.         Name = "taskNotifierBinding",
  9.         HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
  10.         MessageEncoding = WSMessageEncoding.Text,
  11.         UseDefaultWebProxy = true,
  12.         AllowCookies = false,
  13.         BypassProxyOnLocal = false,
  14.         Security =
  15.         {
  16.           Mode = BasicHttpSecurityMode.TransportCredentialOnly,
  17.           Transport =
  18.           {
  19.             ClientCredentialType = HttpClientCredentialType.None,
  20.             ProxyCredentialType = HttpProxyCredentialType.None
  21.           },
  22.           Message =
  23.           {
  24.             ClientCredentialType = BasicHttpMessageCredentialType.UserName
  25.           }
  26.         }
  27.       };
  28.  
  29.       // TODO update the URL to match your current configuration
  30.       EndpointAddress remoteAddress = new EndpointAddress("http://localhost:57800/TaskNotifierService.svc&quot;);
  31.  
  32.       TaskNotifierServiceClient client = new TaskNotifierServiceClient(binding, remoteAddress);
  33.       client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
  34.  
  35.       return client;
  36.     }
  37.   }
  38. }

The SharePoint project includes not only the event receiver, but two JavaScript files as well. We reference the first one, the TaskNotifierLoader.js from a CustomAction element.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  3.   <CustomAction Location="ScriptLink" ScriptSrc="/_layouts/SPTaskNotifier/TaskNotifierLoader.js" Sequence="900"/>
  4. </Elements>

TaskNotifierLoader.js support dynamic loading of the necessary jQuery and SignalR libraries as well as our other .js file, the TaskNotifier.js.

  1. // TODO update the URL to match your current configuration
  2. var hostURLSignalR = 'http://localhost:57800/&#039;;
  3.  
  4. // Script references.
  5. // Reference the jQuery library.
  6. document.write('<script type="text/javascript" src="' + hostURLSignalR + 'Scripts/jquery-1.6.4.min.js"></script>');
  7. // Reference the SignalR library.
  8. document.write('<script type="text/javascript" src="' + hostURLSignalR + 'Scripts/jquery.signalR-2.0.2.min.js"></script>');
  9. // Reference the autogenerated SignalR hub script.
  10. document.write('<script type="text/javascript" src="' + hostURLSignalR + 'signalr/hubs"></script>');
  11.  
  12. // load our custom script as well
  13. document.write('<script type="text/javascript" src="/_layouts/SPTaskNotifier/TaskNotifier.js"></script>');

TaskNotifier.js performs the same SignalR hub-related tasks as we saw at the default.htm of the  TaskNotifierTestWeb project above, but in this case we display the notification as a standard SharePoint status message.

  1. $(function () {
  2.     $.connection.hub.url = hostURLSignalR + "/signalr";
  3.     // Declare a proxy to reference the hub.
  4.     var taskNotifier = $.connection.taskNotifierHub;
  5.     // Create a function that the hub can call to broadcast messages.
  6.     taskNotifier.client.addTaskMessage = function (title, url) {
  7.         var anchor = $('<a />').attr('href', url).attr('target', '_blank').text(title);
  8.         var anchorText = $('<span />').append(anchor).html();
  9.         var text = "A task called '" + anchorText + "' was assigned to you.";
  10.         var statusId = SP.UI.Status.addStatus("New task:", text);
  11.         makeStatusClosable(statusId);
  12.     };
  13.     // Start the connection.
  14.     $.connection.hub.start();
  15. });
  16.  
  17. function makeStatusClosable(statusId) {
  18.     var status = $('#' + statusId);
  19.     $(status).html('<a title="Close status message" href="" onclick="javascript:SP.UI.Status.removeStatus(\'' + statusId + '\');javascript:return false;">x</a>&nbsp;' + $(status).html());
  20. }

Testing the Solution

Be sure you start the TaskNotifierService project first. As I mentioned, it is the core, without that the other components won’t work.

Next, you can start the UI components, that means opening either SharePoint or the test web project in the browser. If you start the UI first, the client can’t register itself at the SignalR hub so it won’t receive any notifications later.

You can test the SignalR hub and the web UI (either the test project or the SharePoint solution) using the WCF Test Client.

image

You can select the TaskCreated method, set the parameter values you would like to pass to the method, and invoke the method.

A few important things to note regarding this tool:

You should use a double backslash to separate the domain and user names in the LoginName parameter, as there is a bug in the WCF Test Client.

You might get an error message when you start the WCF Test Client:

Error: Cannot obtain Metadata

In this case you should read the full error message as it may have a rather trivial solution like the lack of free memory in this case:

Memory gates checking failed because the free memory (xxxxxxxx bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Here is a sample output of calling the TaskCreated method from the WCF Test Client with the parameters displayed on the screenshot above using the test web site (see TaskNotifierTestWeb project):

image

And the result of the same call in SharePoint:

image

Alternatively, you can test the functionality from the TaskNotifierTestConsole project as well. The following screenshots display the result of calling the TaskCreated method from the TaskNotifierTestConsole project in the case of the test web project:

image

And in the case of the SharePoint solution:

image

Note: The user can close the SharePoint status messages as described in my former post.

Of course, the main goal of this post and the sample is to illustrate, how to use SignalR 2.0 from SharePoint, so let’s see how it works. In this case, I suggest you to start two separate browser tabs, one for the Task list and an other one with an arbitrary page on the same SharePoint site. The reason of this is that when you create a new task, the page is reloaded and you might miss the notification. You should receive the notification in the other browser window.

So let’s create a new task and assign it to the current user.

image

A new status message will be displayed in the other browser tab.

image

Clicking on the hyperlink will open the display form of the task just created.

image

Hopefully you can apply the techniques illustrated here to add real-time functionality easily to your SharePoint applications via the SignalR libraries.

You can download the source code of the sample application from here.

1 Comment »

  1. The article is very useful, thanks so much

    Comment by Tiep Nguyen — April 3, 2014 @ 16:47


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: