Javascript has two equality operators, == and === (and corresponding inequality operators != and !==). Most beginner javascript developers use either ==, as they don’t yet know about ===, or blindly use === for every comparison because they heard once, somewhere, that that was what you should do in javascript; without really understanding the differences between the two.

The difference between == and === are simple: == uses ‘type coercion’, which means that it can attempt to match two objects of different class, while === compares against both value and type. For example,

"1" == 1 // true

but

"1" === 1 // false

since javascript’s == comparison converts the string “1″ to a number, and then matches, whilst the === recognises that the string literal is not equivalent to the number. The results of == seem ok for this example, but it’s type conversions can produce some other unexpected results. for example:

"0" == false // true
"0" === false // false

1 == true // true
1 === true // false

undefined == null // true
undefined === null // false

On the whole it is advisable to use === for comparisons, but knowing the difference means that sometimes we can use this type coercion to our advantage. Just be sure to be smart about it, and preferably explain your reasoning in a short comment so as not to confuse others!

UPDATE: With the release of SignalR 4.0, some of the information in the article may be out of date

I recently had to implement an ASP.NET MVC application using long polling to handle asynchronous communication not only from client from server (as you might traditionally do using ajax), but also server to client. I began looking into long polling solutions, and soon stumbled across SignalR, which describes itself as an async signaling library for ASP.NET to help build real-time, multi-user interactive web applications, which was pretty much exactly what I needed!

SignalR is a really brilliant solution. It’s one downfall, however, is the lack of documentation. Scott Hanselman wrote a nice post that gives a nice overview, with a code snippet that shows how easy it can be to use SignalR, but unfortunately there isn’t really much else (except for that one snippet, which seemed to appear everywhere!). Looking through the samples is also helpful, but some things I had to puzzle out on my own, and so I wanted to share some of what I learned. I’m not going to bother giving ‘real world’ type examples, simply show the different types of client/server communication SignalR is capable of, the building blocks. Once you know how to send data/call functions client to server, and vice versa, it really isn’t much of a leap to work out how to put it all together…

So there are two ways to use SignalR: you can access it at a low level by overriding it’s PersistentConnection class, which gives you a lot of control over it; or you can let SignalR do all of the heavy lifting for you, by using the high level ‘Hubs’.

SignalR Hubs

It’s so easy to set up a hub in your application. First, use Nuget to grab SignalR and it’s dependencies. In the root of your application, add a class, MyHub.cs that implements the SignalR class Hub. On your page, include jQuery and jquery.signalR, and then:

<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
       $(function() {           var myConnection = $.connection.myHub;           $.connection.hub.start();       });
// ]]></script>

Rather awesomely, this is all you need to do to establish a connection between the client and server, which you can see if you crack open firebug. You’ll also notice that /signalr/hubs doesn’t actually exist in your project, which Resharper won’t like! This is really neat, as the hubs javascript is autogenerated by SignalR. Whilst we might have a connection established, it currently does nothing. Time to add some functionality.

Calling Server-side Functions from the Client

Everything with SignalR is basic, but this is probably the most basic of all. All you need to do is create the method in MyHub.cs, and then in your javascript simply call:

myConnection.voidFunction();

That really is it! If you build the solution and go to the source of /signalr/hubs, you’ll notice that it has been updated to include the new method. To pass some data, simply add values as you would in any other function:

myConnection.voidFunctionWithParams(1, "a string");

The methods don’t have to be void either. Say you have a function Increment:

public int Increment(int input) {
    return input++;
}

You call it simply by:

connection.returnInt(0)
          .done(function (returnedVal) {
              // Handle returned val (in this case, returnedVal = 1)
          });

As well as simple data types, you can also pass json to the server, and SignalR will automatically handle the conversion to objects. For example, if we have define a class MyObject:

public class MyObject {
    public int objId { get; set; }
    public string objVal { get; set; }
}

We can send it to the server like this:

var jsonMyObject = {
    "objId" : 1,
    "objVal" : "some text"
};
connection.receiveObject(jsonMyObject);

The reverse of this is true also, so returned objects from the server will be converted to their json equivalent.

Note: Static Variables

The hub class that you create will be instantiated at every request, so if you declare variables then they will be lost unless you make them static. This is useful for data that you want to persist, but not store in the database, as can be seen in the SignalR chat hub sample, which uses static collections to maintain the list of rooms.

Invoking client-side functions from the Server

So far I’ve only covered requests from client to server, which really is not a lot more useful than Ajax, albeit with some extra niceties such as object casting. The real usefulness of SignalR, however, comes with being able to call javascript functions from the server. I hope you won’t be surprised to learn, this is really easy to do! SignalR maintains a list of client side connections into the hub, rather conveniently named Clients. Client side functions must be defined in the initialisation code, for instance:

$(function() {
    var myConnection = $.connection.myHub;
    myConnection.alertMessage = function(stringParam) {
        alert(stringParam);
    };
    $.connection.hub.start();
});

This code simply creates an alert box that echoes the data passed to it, and is called by using

Clients.alertMessage("test");

Again, you can pass not only simple data types in here but C# objects and SignalR will handle the conversion. Taking this idea a little further we can pass in a list of MyObjects and iterate through them like this:

myConnection.receiveComplex = function(complexList) {
    complexList.each(function(index, complexObject) {
        var id = complexObject.objId;
        var value = complexObject.objVal;
    });
};

Invoking Client-side Functions from out of the Hub

Bouncing data back and forth between is cool, but the final useful thing you can do is to invoke javascript from outside the hub simply by:

var clients = Hub.GetClients();
clients.alertMessage("external test");

And there we have it! Asynchronous server/client messaging made easy!