Update - I uploaded the code and project to MSDN Code Gallery here: http://code.msdn.microsoft.com/LightSwitch-and-SignalR-4d7ff7a8 

SignalR? What is that?

SignalR is described as “Incredibly simple real-time web for .NET”.

It’s a great way for a JavaScript client to call directly into Server side methods, and a great way for the Server to push up updates or notifications to the JavaScript client.

I heard a couple people raving about SignalR recently, and figured it was time to see if we could get LightSwitch and SignalR to meet.

LightSwitch…meet SignalR

We’re going to make a simple LightSwitch (LS) application here. And then we are going to use SignalR to push up some real-time notifications to the LightSwitch HTML Client.

We’ll end up with a LS HTML App that receives a notification every time a new entity is inserted or updated.

This would allow for any user to know when ever data has been changed.

Let’s start out with a simple “Contacts” LS app.  Everything here should be pretty basic if you’ve done any LS stuff before.

  1. Create a new project – LightSwitch HTML Application (Visual C#)
  2. Call it - “ContactsSignalR”
  3. Add a table – call it “Contact”
  4. The table should look something like this when you are done:
  5. image
  6. Now let’s make a simple HTML Browse Screen around the “Contacts” data
  7. In the screen designer, select “Screen | Browse Contacts (Browse Screen)” and set the property “Behavior – ScreenType” to “Edit”. This will enable the “Save” button to show on our screen.
  8. Now let’s add a data item to our screen – so in the Screen Designer click your “Add Data Item…” button
  9. image
  10. That’ll open up a dialog – let’s call this property “updates” and make sure “Is Required” is unchecked. It should look like this:
  11. image
  12. Now drag and drop your updates data item onto your screen – put it right below the “Command Bar” so that it looks like:
  13. image
  14. Select the “updates” control on the screen designer and set the following properties:
    1. Label Position: Hidden
    2. Font Style: Large
  15. We’ll use this control later on to post our “real-time” updates to the screen
  16. Now I’d like to be able to Add and Edit new Contacts entities here, so select the Command bar, right click and say “Add button”
  17. Select Contacts.addAndEditNew and Navigate To: New Screen like this:
  18. image
  19. This is a easy way to quickly create a new Add/Edit screen for the Contacts entity
  20. Important! - After the screen is created your Screen Designer changes to show the AddEditContact screen. Make sure you double click the “BrowseContacts” screen again to set focus back.
  21. Do the same thing again – add an EditSelected button this time for the existing screen you just made, like this:
  22. image

 

Basic App is done. Onto SignalR

At this point, we’ve basically made a simple LS App to add and edit new Contacts.

Now we need to shove in some SignalR.  To do that we first need to “NuGet” our projects.

    1. In the Solution Explorer toolbar switch to “File View” like so:
    2. image
    3. Now right click the HTMLClient project and select Manage NuGet Packages:
    4. image
    5. Now select Online packages, search on SignalR and install the below entry:
    6. image
    7. This will add the SignalR JavaScript references to your HTML Client
    8. But we need to add them to the default.htm file as well, so open up that file and these two lines:

<script type="text/javascript" src="Scripts/jquery.signalR-1.0.1.js"></script>
< script src="../signalr/hubs"></script>

  1. The first line is a reference to the SignalR library
  2. The second line is actually a reference to some JavaScript that will be dynamically generated by our SignalR server later on.
  3. Now right click the Server project, and select “Manage NuGet Pacakages…”
  4. This time we want to install the SignalR package for .NET server components:
  5. image

 

NuGet is done. Put SignalR code into the Server!

We’ll need to add some Server side code here to start up the SignalR Server Hub. And to allow for the client and the server to talk to each other.

    1. Right click the Server project again and say “Add –> New Item”
    2. Add a Global.asax file to our project – we will need this to put in some custom application start up code
    3. Right click the Server project again and say “Add –> New Item”
    4. This time add a “Web Api Controller” class to our project.
      1. We only do this because it will automatically pull in some dll references for us that we’ll need later.
    5. Open up your Global.asax.cs file and paste in the follow code:
        protected void Application_Start(object sender, EventArgs e)
        {
            var config = new Microsoft.AspNet.SignalR.HubConfiguration
            {
                EnableCrossDomain = true
            };
            RouteTable.Routes.MapHubs(config);

            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi", routeTemplate: "api/{controller}/id", 
                defaults: new { id = System.Web.Http.RouteParameter.Optional }
            );
        }
    1. This code will get called when our LS app starts.  It starts up the SignalR server hub so that the clients can connect to it.
    2. Right click your Server project and add one more file – a class file and call it ContactHub
    3. Past the below code into your class:
namespace LightSwitchApplication
{
    public class ContactHub : Hub
    {
    }
}
  1. All we are doing is creating our own Hub here that we’ll use later to talk to the client from the server.

Put SignalR into the Client!

We need to put some basic JavaScript code into our Browse screen so that it can modify the “updates” label, and so that the Server has a function to call on the Client.

    1. Open up the Browse Contacts screen
    2. Select the Write Code – create method:
    3. image
    4. This is where we’ll add our basic JavaScript. So copy and paste the below code into the BrowseContacts.js file
/// <reference path="../GeneratedArtifacts/viewModel.js" />
/// <reference path="../Scripts/jquery.signalR-1.0.1.js" />

myapp.BrowseContacts.created = function (screen) {
    // Write code here.
    $(function () {
            
        contact = $.connection.contactHub;
        contact.client.broadcastMessage = function (message) {
            screen.updates = message;
        };     

        $.connection.hub.start()
        .done(function () {
        })
        .fail(function () {
            alert("Could not Connect! - ensure EnableCrossDomain = true");
        });
    });
};
  1. Here’s what this does:
    1. $.connection.contactHub <- This is our connection to the ContactHub we made on our server
    2. contact.client.broadcastMessage <- this is the JavaScript function we are going to invoke from the Server (which we’ll do shortly).  This function will set the “updates” screen item with some text.
    3. $.connection.hub.start() – this just “starts” up the connection from the client to the SignalR Hub

Almost done! Let’s have the Server call the Client.

We need one final piece here – call into the JavaScript client every time a Contact is inserted or edited.

    1. So double click the Contact’s entity.
    2. Select Write Code – > Contacts_Inserted
    3. Paste in the below code:
        partial void Contacts_Inserted(Contact entity)
        {
            string message = "A contact for " + entity.FirstName + " " + entity.LastName + " was just created";
            var context = GlobalHost.ConnectionManager.GetHubContext<ContactHub>();
            context.Clients.All.broadcastMessage(message);      
        }
    1. This will call the the “broadcastMessage” JavaScript function we wrote earlier for ALL active LightSwitch clients when a Contact is inserted. When that function is called – the updates label will automatically be updated to show our message.
    2. Do this again for the Contacts_Updated method. So open up the entity again. Select Write Code –> Contacts_Updated.
    3. Paste in the below code:
        partial void Contacts_Updated(Contact entity)
        {
            string message = "A contact for " + entity.FirstName + " " + entity.LastName + " was just updated";
            var context = GlobalHost.ConnectionManager.GetHubContext<ContactHub>();
            context.Clients.All.broadcastMessage(message);
        }
  1. Same thing here as the Inserted method, except it will only be called when a Contact is updated.

 

That’s it! F5 it and hang on.

F5 the LS app to build it and run it.

A browser should launch.

Go ahead and create a new Contact and Save it.  You should see something like this after you save.

image

This is cool…BUT try this with 2 browsers opened to really blow your mind.

So launch another instance of your web browser.

Copy and paste your http://localhost:NNNN/HTMLClient URL from your first browser into the second browser’s address bar.

Now create another record again. You’ll see this:

image

 

Both browsers got updated at the same time!

That’s pretty awesome, IMO.

So awesome, that I had to make a YouTube video for it:

 

Please feel free to leave any feedback, and I’ll post my app up on Code Gallery for others to check out (will update this once the application is available).

Thanks All!