Category Archives: Introduction

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

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.

What I’m Up To

So It’s been a while since I wrote an article and published a blog, and there is all this new shiny tech (Aka Windows 8 / WinRT) to look at. Thing is I am actually in the guts of writing a web based tool that I have had on the back burner for a while now.

So that is what I am up to, it will be good I feel, just taking a long time. I think some atricles will fall out of that, as there are some things I have found very little information available for that I have had to figure out myself, which I think may make some nice articles.

I think I will get some time to look into Win8 and WinRT at some point, but until now I need to share a very important link with you all.

If you only have time to check out one link on the internet today, make sure its this one:

Here is the link : http://i.imgur.com/nuR4V.jpg

Actually someone just alerted me to another one, check this out too http://28.media.tumblr.com/tumblr_lr8cuabOcC1qzhnmco1_500.gif

Task Parallel Library 6 of n

I have just published part 6 in my series of TPL articles, which is the final one. This time I talks about TaskCompletionSource and the new Async CTP and how to create your own awaitable types.

Read the article here : http://www.codeproject.com/KB/cs/Tasks6.aspx

Task Parallel Library 4 of n

I have just published the 4th in a series of articles on TPL. This time I talk about Parallel LINQ and how you can use it cancel it, partition it etc etc.

You can all about it over here :

http://www.codeproject.com/KB/threads/TPL4.aspx

Task Parallel Library 3 of n

I have just published the 3rd in a series of articles on TPL. This time I talk about Parallel.For/Parallel.Foreach and how you can use them/cancel them, partition them etc etc.

You can all about it over here :

http://www.codeproject.com/KB/cs/TPL3.aspx

OpenId With Forms Authentication

As some of you may know from reading some of my past articles/blogs, that I am not really a web man, but I had an idea a while back to create a tool that had to be web based, so I have been busy constructing this ASP .NET MVC web site in my spare time.

It is still ongoing, but one area that the web site needed was login/authentication, which is a pretty usual requirement on web sites. In fact ASP .NET has long supplied forms authentication for this purpose (as well as other options). Thing is, I did not really want to store username/passwords in my database, then I read about this protocol called OpenId, which is a protocol that numerous web sites adhere to already. And if you have an OpenId compliant login, my site could allow its users to use those credentials directly with the OpenId compliant web site validating them. They basically handle the login/authentication process and redirect back to the original calling site (my site).

This may sound quite nuts, but it is quite probable that you yourself are already in possession of an OpenId login, as there are many many OpenId compliant web sites out there. So it seemed to make sense to allow users to simply use their existing login credentials rather than for my site to ask them to create even more credentials.

So this is all well and good, so what is this article all about. Quite simple really, this article will demonstrate how to use OpenId with Forms Authentication (to store the Authentication cookie) within a ASP .NET MVC web site.

So I ended up creating a small demo project and explanatory atricle over at codeproject, which you can read using this link : http://www.codeproject.com/KB/miscctrl/OpenIdFormsAuth.aspx

I hope it helps you out