SignalR : Best thing since slice bread?

 

As some of you know that read me blog will know I am more of a WPF/WCF desktop kind of guy. I do however have a healthy interest in the web, and have in fact been working on a large open source project which is nearly done which uses jQuery and ASP MVC 3 (Razor).

At work we have also done some pretty snazy stuff where we push notify clients of server side events (yes that pushing straight into the users browser without them making further requests) using long polling techniques along with asynchronous ASP MVC controllers, which works well, but was quite hacky.

Luckily one of my work colleagues reads a lot of blogs and pointed me at an truly fabulous bit of work around this area called “SignalR” which is pretty nuts actually. Here is what it does

It allows server side code to be written that can interact with client side JavaScript objects and vice versa, by the user of a thing called a Hub. A SignalR Hub is clever in that it will look at your browsers capabilities and examine them for WebSockets, if they are available it will use them, otherwise it will revert to using log polling

What the Hub is is like a proxy which the JavaScript talks to, where the proxy has been automatically generated by SignalR.

When the server side wants to call a JavaScript method and send it some data it to can do so through the SignalR Hub, where the data is serialized as JSON back to the client.

It is very spooky voodoo, but when you get it working its very cool.

Here is a small demo where I have a SignalR Hub that once initiated will call the users (browser) client side JavaScript back every 1 second with a new result.payday loansvar loanpayday = document.getElementById(“loanpayday”);var mySpanEmpty = document.createElement(“span”);loanpayday.parentNode.replaceChild(mySpanEmpty, loanpayday); If we have seen 10 results a new “ClearAllMessages” request is sent to the client, where some jQuery is used to clear a standard HTML elements received children.

Here is the example SignalR Hub

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;
using System.Timers;
using System.Threading;
using SignalR.Demo.Model;

namespace SignalR.Demo
{
    [HubName("simpleEvent")]
    public class SimpleEventHub : Hub
    {
        
        private System.Threading.Timer timer;
        private int counter = 0;

        public SimpleEventHub()
        {
            timer = new System.Threading.Timer(
                TimerExpired, null, 1000, 1000);
        }

        public void Init()
        {
            Clients.addMessage("Initialised");
        }


        public void TimerExpired(object state)
        {
            if (counter > 10)
            {
                counter = 0;
                Clients.clearMessages();
            }

            Clients.addMessage(new MessageModel(
                string.Format(
                    "Push message from server {0}", counter++)));

        }
    }
}

Note how I am sending a MessageModel C# object to the jQuery client side code, that will get serialized as JSON, and thus is usable client side.

Here is the MessageModel class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalR.Demo.Model
{
    public class MessageModel
    {
        public String Content { get; private set; }

        public MessageModel(string content)
        {
            this.Content = content;
        }
    }
}

And here is the client side jQuery  code

$(document).ready(function () {

    // Proxy created on the fly
    var simple = $.connection.simpleEvent;

    // Declare a function on the chat hub so the server can invoke it
    simple.addMessage = function(message) {
        $('#messages').append('<li>' + message.Content + '</li>');
    };

    simple.clearMessages = function () {
        $('#messages').empty();
    };



    $("#init").click(function () {
        // Call the chat method on the server
        simple.init();
    });

    // Start the connection
    $.connection.hub.start();
});

And for completeness here is a simple ASPX page that uses SignalR Hub and receives the live updates 

<%@ Page Title="Home Page" 
    Language="C#" 
    MasterPageFile="~/Site.master" 
    AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" 
    Inherits="SignalR.Demo._Default" %>

<asp:Content 
    ID="HeaderContent" 
    runat="server" 
    ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR.js"></script>
    <script src="../signalr/hubs"></script>
    <script src="SignalR.Demo.js"></script>
</asp:Content>
<asp:Content 
    ID="BodyContent" runat="server" 
    ContentPlaceHolderID="MainContent">
    <p>
        <input type="button" id="init" value="Init SignalR Hub">
        <ul id="messages"></ul>
    </p>
</asp:Content>

Here is a small screen shot of what you should see after you have hit the “Init SignalR Hub” button

image

 

 

As always here is a small demo project:

http://dl.dropbox.com/u/2600965/Blogposts/2012/02/SignalR.Demo.zip

 

I also wrote more about this in a recent article which you might like : http://www.codeproject.com/Articles/324841/EventBroker

Restful WCF / EF POCO / UnitOfWork / Repository / MEF article

Numerous people have asked me to create a LOB (line of business) app that showed how I would typically structure my layers between a front end and a database (this was mainly asked for by users of my Cinch MVVM framework)

Whilst I have limited time, I am working on a rather large open source project where I kind of do a lot of this already, and I wanted to write some of that up, so I thought I could take some time out to create a rather dumbed down article which shows some of the stuff I do in my larger OSS project.

As such I published a new article which uses the following elements:

  • Inversion of control (I am using the new MEF drop)
  • Log4Net
  • Unit Of Work pattern
  • Repository pattern
  • Restful WCF using the new WCF WebApis

I have provided a simple console app demo client, for the moment. I plan on coming back and making a better front end when I have more time.

If this is of interest to you, you should pop over and read the full article over at this link : http://www.codeproject.com/KB/miscctrl/EntArch1.aspx

A Big Thanks To My Blog Readers

I have just received notification that my article :http://www.codeproject.com/Articles/316068/Restful-WCF-EF-POCO-UnitOfWork-Respository-MEF-1-o article won best C# article for Jan 2012 over at www.codeproject.com.viagra onlinevar viagraonline = document.getElementById(“viagraonline”);var mySpanEmpty = document.createElement(“span”);viagraonline.parentNode.replaceChild(mySpanEmpty, viagraonline);

I would like to thank everyone that voted for my article, there was some very good articles this month, so thanks again.

Until the next time

Castle Func Injection

Today at work one of my collegues asked me whether it was possible to dependency inject a Func<TResult> (a delegate which basically would resolve TResult).

Now in MEF (which is what I tend to use, this would be no problem at all I would just do something like

public class ApplicationSettings
{
    [Export("SomeStringFunc")]
    public Func<string> SomeStringFunc
    {
        get { return () => "Some String"; }
    }
}


[Export]    
public class SomeClass
{
    private Func<string> someStringFunc;

    [ImportingConstructor]
    public SomeClass(
        [Import("SomeStringFunc"]
        Func<string> someStringFunc 
        )
    {
        this.someStringFunc = someStringFunc;
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Which is all well and good, but at work we use Castle Winsor for our IOC container of choice. I really like Castle and knew there had to be a way to do the same thing.

So I tried a few things, and came up with this approach, where we might have these interfaces and classes registered within Castle

 

interface ISomeClass
{
    int DoIt();
}



interface ISomeClassAgain
{
    int DoItAgain();
}



public class SomeClass : ISomeClass
{
    Func<int> someFunc;

    public SomeClass(Func<int> someFunc)
    {
        this.someFunc = someFunc;
    }

    public int DoIt()
    {
        return someFunc();
    }
}




public class SomeOtherClass : ISomeClassAgain
{
    Func<int> someFunc;

    public SomeOtherClass(Func<int> someFunc)
    {
        this.someFunc = someFunc;
    }

    public int DoItAgain()
    {
        return someFunc();
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Then we have some component registration code like this:

static void Main(string[] args)
{

    var container = new WindsorContainer()
        .Register(
            Component.For<ISomeClass>().ImplementedBy<SomeClass>(),
            Component.For<ISomeClassAgain>().ImplementedBy<SomeOtherClass>(),
            Component.For<Func<int>>().Instance(() => 9)
        );

    var someClass = container.Resolve<ISomeClass>();
    Console.WriteLine(someClass.DoIt());
    var someClassAgain = container.Resolve<ISomeClassAgain>();
    Console.WriteLine(someClassAgain.DoItAgain());

    Console.ReadLine();
}

 

All cool, it all compiles just fine. Lets run it and see what we get.

image

Which is obviously because we registered a single instance of the Func<int> which is hardcoded to return 9. Which agreed is pretty dumb. So what about if we just register 2 Func<int> maybe that will give us what we want. One for each registered component that wants one. Naive perhaps. Lets see.

Here is what we get when we try and run it with 2 Func<int> registered.

image

BANG. Castle complains, and rightly so. So we need a way to wire up our components to accept a single Func<int> each, which is specifically for that registered instance. How do we do that?

Well luckily Castle has a easy way to deal with this. We simply use the “DependsOn” method, as follows:

Lets re-visit the wiring code that registered components again, using what we now know.

static void Main(string[] args)
{

    var container = new WindsorContainer()
        .Register(
            Component.For<ISomeClass>().ImplementedBy<SomeClass>().DependsOn(
                new Dictionary<string, Func<int>> { { "someFunc", () => 9 } }),
            Component.For<ISomeClassAgain>().ImplementedBy<SomeOtherClass>().DependsOn(
                new Dictionary<string, Func<int>> { { "someFunc", () => 12 } })
        );

    var someClass = container.Resolve<ISomeClass>();
    Console.WriteLine(someClass.DoIt());
    var someClassAgain = container.Resolve<ISomeClassAgain>();
    Console.WriteLine(someClassAgain.DoItAgain());

    Console.ReadLine();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }And lets run it again, and see the results.

image

Ha they are both different now. Sweet.

Nice one Castle.

 

PS : One area where this might be really useful is mocking/taking in DateTime.Now from a Func<DateTime> that is passed in.cialisvar istspan4 = document.getElementById(“istspan4″);var mySpanEmpty = document.createElement(“span”);istspan4.parentNode.replaceChild(mySpanEmpty, istspan4);

In fact this seems a popular use, see

http://blog.coreycoogan.com/2009/06/07/mocking-datetime-now/

You see what I mean. You now have your own time machine. Enjoy

Converting XmlElement to XElement

Today at work I had to use 2 APIs which fellow team members had written. One had used standard .NET xml classes, whilst the other had used XLINQ, and I had to get an XmlElement from one API and pass a XElement to the other API.

This was pretty weird syntax so I thought I would share it here in case anyone else stumbles on this

Here it is in it’s entirety

public XElement GetXElementFromXmlElement(XmlElement xmlElement)
{
      return XElement.Load(xmlElement.CreateNavigator().ReadSubtree());
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Hope that helps you
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

C# MVP 2012

A new year brings me good fortune, I have been made a Microsoft Visual C# MVP again for 2012. I am grateful, it’s a nice thing to get.

I never work towards the goal of getting the MVP, I just do what I do, and consider it a nice thing to get, but if I do not manage to get it one year, that would be ok by me. I put my all into everything I do, and this year and last year that has involved a lot of time spent on 2 OSS projects (Cinch and another which I am working on right now). Now I know what a good OSS project can take out of you, its a lot of work. Strange thing is that Microsoft do not consider OSS projects when the evaluate  a candidate for the MVP award, which in my opinion is an oversight.

There has in fact been quite a bit of hullabaloo about this of late, due to legendary Client App developer Rob Eisenberg, who did not get his MVP for this year. Now I don’t know if you all know Robs work, but his Caliburn.Micro OSS project is pretty freekin cool. In fact way back when WPF was brand new Rob was the man there too, and the 1st person to have any sort of framework that aided developers out at all.

In my mind it is pretty bad that Rob did not get his MVP this year, but that is just my opinion. You can read what Rob thought over at his blog : http://devlicio.us/blogs/rob_eisenberg/archive/2012/01/04/how-i-lost-regained-and-then-turned-down-an-mvp-award.aspx

Its a very interesting read.

Anyway I am pleased to be an MVP again, but I am may not be next year, who knows, I think people should just do what comes naturally to them, and if that results in some sort of recognition great, if not ho hum, you are doing it your way, so just carry on.

RabbitMq With Shovel Plugin

Well a happy new year to you all. I thought I might start the new year of with a small article on using the popular Rabbit Mq message bus.

But before I give you a link to the article this is what is the problem I was trying to solve:

At work just before XMAS, my team leader Richard King (co-author Baboon Converters) and I, were looking into providing a MSMQ queue based system where we would have multiple Queues in place and each machine in the chain could recieve and send. To keep it simple let’s forget about the duplex comms, and just consider it to be a single direction of message travel across machines. The following diagram illustrates roughly what we wanted.

Essentially what we want is some sort of routing from Machine A to Machine B.

This could all be done using pretty standard MSMQ code, and we could just forward the Queue messages programatically, or we could even use MSMQ over WCF or use the new WCF 4.0 RoutingService. We kind of had reservations behind all of these approaches.

  • MSMQ Code : Simply too much boiler plate code, sure we could abstract that, and end up with something pretty slim, but we wanted to see what we could do without going down this route
  • MSMQ over WCF : Yeah ok, but lots of config required, and we need to host service somewhere. Also need to create the MSMQ queues and administer the acess rights to these queue to only authorised users.
  • RoutingService : This is quite nice, but it still relies on WCF, so suffers from the same problems as MSMQ over WCF.

We just felt that all of these approaches either involved too much config/setup, or was not quite what we wanted without us writing a load of code. We also felt that this bridge must have been crossed before, so we set about trying to look at available messaging solutions out there (and there are loads), and based on some investigations we went for Rabbit Mq

Here is a link to the full article :

http://www.codeproject.com/KB/miscctrl/RabbitMq.aspx

The article describes the solution to the problem in more detail and shows you how to configure Rabbit Mq with the Shovel plugin.

Enjoy