Tuesday, January 15, 2013

Brian Sullivan of Improving spoke on SignalR at the Austin .NET User Group last night.

Mr. Sullivan's talk on SignalR was very informative and it showed off a lot of how-to. For example one pulls SignalR out of NuGet like so:

install-package Microsoft.AspNet.SignalR -pre

 
 

Other things I learned included that WebSockets requires either Windows8 or WindowsServer2012 in tandem with both IIS8 and ASP.NET 4.5 and that with Forever Frame, the browser holding the iFrame is tricked into believing that the page within the iFrame never finishes loading so that the page within the iFrame may consistently load new scripts as part of "loading a page." Bigger yet, there is a new version of ASP.NET coming down the pipe to us soon, this per Brian Sullivan last night, and it will have SignalR already baked into it. Microsoft has an all-chips-in investment. Such is prudent, the equivalent power of SignalR already exists in Node.js. The trick is getting IIS to play catchup. There are two varieties of web-based SignalR APIs. The one I've seen before is called the persistence parsing API and it basically allows one to talk string variables back and forth to a server as part of what Scott Hanselman referred to a real-time updates. The other seemed to allow one to fire off C# code upon the click of the button or another act which could then ultimately fire off events back in jQuery! The second variety was called Hubs. To allow for Hubs to work, one has to install the Nuget package and put this in the RouteConfig:

routes.MapHubs();

 
 

I did not come out of the training with a comprehensive understanding of Hubs, but some of the C# code which would ultimately allow for reaching back to JavaScript looked as seen below. Please make note of inheritance from Hub and the call to .cardCreate(card); as cardCreate is a JavaScript method!

using System;
namespace SignalRKanban.Hubs
{
   using Microsoft.AspNet.SignalR.Hubs;
   using SignalRKanban.Models;
   public class KanbanHub : Hub
   {
      public void CreateCard()
      {
         var id = Guid.NewGuid();
         var card = new Card { Content = "", Lane = "1", ID = id };
         clients.All.cardCreate(card);
      }
   }
}

 
 

The jQuery side of things looks like so:

$(function () {
   var kanbanHub = $.connection.kanbanHub;
   
   KanbanBoard.prototype.createCard = function() {
      kanbanHub.server.createCard();
   }
   
   var vm = new KanbanBoard();
   ko.applyBindings(vm);
   
   kanbanHub.client.cardCreated = function (card) {
      vm.addNewCardToLane(card.ID, card.Content, card.Lane);
   }
   
   $.connection.hub.start();
   
});

 
 

A script tag needs to call out to ~/Scripts/jquery.signalR-1.0.0-rc1.mis.js and a second script tag will need to call out to ~/signalr/hubs for this to work in a view. Note that this whole thing assumes MVC4 and ASP.NET Web API.

No comments:

Post a Comment