In my last post, Javascripts Number Type, I stated that ‘everything in javascript extends Object, which means that it can have functions’, and by this I meant that it doesn’t have primitives as we are used to in other languages, since they have methods against them. However, I’ve recently learned that that was incorrect, although there are tricks in the language to make it look that way.

Primitives and Wrapper Objects

There are five primitives in javascript: number, string, boolean, null and undefined. Of these, number, string and boolean have wrapper objects, which encapsulate the primitive and augment it with a number of useful methods.

Primitive Wrapper
var n = 10;
console.log(typeof n); // number
var n = new Number(10);
console.log(typeof n); // Object
var s = “string”;
console.log(typeof s); // string
var s = new String(“string”);
console.log(typeof s); // Object
var b = true;
console.log(typeof b); // boolean
var b = new Boolean(true);
console.log(typeof b); // Object

This means that we can create a string and use one of its native methods, toUpperCase(), to convert it to uppercase:

var s = new String("shout!");
console.log(s.toUpperCase()); // SHOUT!

Using Wrapper Methods on Primitives

The functions associated with number, string and Boolean aren’t news to most of us, we tend to use them all the time. However, how often do we ever declare a number using new Number() or a boolean with new Boolean()?
This is where javascript is sneaky. When you attempt to use a function on a primitive it is converted to a wrapper object, the function is invoked, and then it is converted back to a primitive. This means that you can do things such as:

console.log("WHISPER".toLowerCase()); // whisper
console.log();

One Final Gotcha…

We’ve seen that we can invoke the wrapper functions on a primitive, so why would you ever want to use the new ___() notation? Well there’s one case where explicitly declaring that you need an object is important, and that’s when you want to augment your number by adding new functions or properties to it. The problem is, javascript will happily let you try and add new properties without reporting any errors, but these will not actually be added.

var prim = true;
prim.sayYesOrNo = function () {
    if (this) { return "yes"; } else { return "no"; }
};
console.log(prim.sayYesOrNo()); // undefined

var wrap = new Boolean(true);
wrap.sayYesOrNo = function () {
    if (this) { return "yes"; } else { return "no"; }
};
console.log(wrap.sayYesOrNo()); // yes

Virtually all programming languages use a variety of data types to represent numbers; for instance bytes, ints, floats and doubles. Back when memory and processing power was expensive, we needed to be careful to limit our usages. It is quicker to operate on smaller number types, such as bytes and chars, than on floats and doubles. Likewise, the larger number types take up more memory. The limitiation of using different number types is that we need to be careful to use suitable number types to avoid overflow errors.

Javascript was always designed to be an easy language to use. For that reason, it has only one number type: Number. Number is a 64-bit floating point (or as we usually call it, a double), which allows developers to forget about overflow issues. Additionally, now memory is cheap and we have an abundance of processing power, we don’t have to worry so much about the effects of using larger data types. Perhaps in 1995 when javascript was first introduced this was not so true as it is today, but with hindsight it was clearly a good decision.

Number, like everything else in javascript, extends Object, which means that it can have functions. There are five functions that are included natively: toExponential(), toFixed(), toPrecision(), toString() and valueOf(); but since Number is an object, we are also able to extend it by adding new functions to its prototype. [Although on the whole this practise is not advised unless you are building a general use utility framework such as underscore.js]

There is one gotcha with the javascript, and that is NaN. NaN, or Number.NaN, is the result of an illegal math operation, such as division by zero or the square root of a negative number. Oddly enough however, NaN !== NaN. This means that the following statements are all true:

3/0 !== 3/0
Math.Sqrt(-4) !== Math.Sqrt(-4)
Math.abs("text") !== Math.abs("text")

This seems a little odd until you consider that each of the expressions returns the same result, so the inequality makes more sense when if we muddle up the examples:

3/0 !== Math.abs("text")
Math.Sqrt(-4) !== Math.abs("text")
Math.Sqrt(-4) !==  3/0

Since javascript doesn’t know what either side of the condition really is – as it evaluates all as NaN – it cannot accurately conclude whether or not they are really equal. People are critical of this, but to me it really seems to be the only thing that makes sense.

We are all faced with difficult decisions in our life, and one of the toughest I’ve faced so far is to decide between education and experience. I finished my degree in July 2011, with an offer to return to uni to do my masters in computer security. However, at the same time the company that I was working at part time was expanding, looking to take on more developers, and with that came an offer to come on full time working as a senior software developer, with greater responsibility; including leading a team of junior developers, project management, and more client interaction.

I loved uni, not because of the student lifestyle – that never really did it for me – but because I could dedicate my time to learning. My degree was strongly geared towards artificial intelligence – machine learning, optimisation and search techniques, etc. – and I ate up all of the new knowledge I could. I, like so many other programmers have, decided to teach myself a new programming language every month; not because these languages would ever really be useful to me, but because I wanted a broader knowledge of programming and computer science as a whole.

What I had never considered, however, was the breadth of knowledge learned on the job – all the really useful stuff that they never tell you about at uni. My first month at work was a whirlwind, learning about new program architectures and patterns, object relational mappers; even source control systems and working effectively in a team were was pretty new to me!

I decided to take the job. It would have been nuts really to pass up an opportunity like that; I figured that my experiences with more managerial responsibility were far more valuable than another certification. And hey, if I was wrong, I could always go back to university later on.

I’ve since come to decide that there were flaws in my learning ethos. I was so keen to learn that I failed to realise that I was really only learning for the sake of learning. Sure I’d familiarise myself with a new language, but that was never really that hard a task – I knew the foundation of a wide variety of languages already from uni – but since I never really had a reason to use them again what was the point? I already knew that I could pick up a language if I ever needed to. Although it seems that there is value in gaining a well-rounded knowledge of your chosen subject, I’ve begun to wonder if that’s really so true. While I don’t believe that you can truly be great at what you do by taking a completely narrow minded approach to learning, why not dig a little deeper into subjects that will be of value?

I’ve been at my new job for just over three months now, and cannot believe how profoundly it has helped to shape my views on learning. I still strive to learn at every available opportunity, but with an emphasis on spending my time learning what I believe will be of most use to me. Did I make the right decision to work rather than to continue down the educational track? It’s early days yet, and it may be a long time until I’m really able to answer that question, if ever. But right now it feels like one of the best decisions that I’ve ever made.

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!

Ok so I puzzled out what was wrong, and it was pretty damn annoying! It seems that the startup order was set for the web app to run before the scheduler. This meant that when the web app initialised, it looked to subscribe to the scheduler but, as the scheduler was not yet initialised, simply dropped the subscription. This meant that subsequent calls to Bus.Instance.Publish(…) did squat.

Two quick fixes:

1. Make sure the scheduler always starts up before the web app
2. Call the scheduler’s end point directly, using:

Bus.Instance
   .GetEndpoint(new Uri("msmq://localhost/scheduler_queue"))
   .Send(new UpdatedScheduledTask()
   {
       ScheduledTaskId = task.Id,
       Crontag = task.Crontag
   });

Note: probably not the best idea to hard code the uri, add it to your config instead!

So I’m currently writing a command line task scheduler so users can get various reports emailed to them at specific times. In order that the scheduler was not continuously polling the database to check for new scheduled tasks, I needed to be able to communicate from the web app to the scheduler whenever a new task was created/a task was edited, and decided to use Mass Transit for this. Mass Transit is a really easy way to set up service bus implementation, used to pass messages between parts of the system running as different processes/on different machines.

For whatever reason, I really love asynchronous stuff, it just seems so cool. So when I update a scheduled task and I see the change reflected in my command line app its pretty exciting.

When I come in to work the next day, and it doesn’t work anymore despite no code changes, it’s a real pain in the ass…

I have various forms on my application and I wanted to be able to see how much had been filled filled out, so I wrote this helper class that I could use to measure how much of the pages view model had been completed.

It uses reflection to check each of the fields in turn, simply checking whether the field is null or not. It’s a bit rough around the edges, and doesn’t really have a strategy for dealing with nullable data types (it simply ignores them) but it worked, and stopped me needing to write 10 different classes to measure 1 different view models so I was happy! It also ignores fields ending with Id, and the ignore rules can be easily extended. The other thing it does is keep track of any ignored fields, and any that it wasn’t able to count (ie. nullables). I never actually used these lists, but they come in pretty helpful during debugging I find.

public class ViewModelProgressHelper
{
    public static ViewModelProgressReport Process(TModel model)
    {
        var report = new ViewModelProgressReport();
        var fields = model.GetType().GetProperties();
        foreach (var field in fields)
        {
            if (Ignore(field.Name)) report.IgnoredFields.Add(field.Name);
            else if (field.PropertyType.IsGenericType && field.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                report.NumberOfFields++;
                if (field.GetValue(model, null) != null) report.FieldsCompleted++;
            }
            else if (field.PropertyType == typeof(string))
            {
                report.NumberOfFields++;
                if (!string.IsNullOrEmpty((string)field.GetValue(model, null)))
                    report.FieldsCompleted++;
            }
            else if (field.GetValue(model, null) == null)
                report.NumberOfFields++;
            else if (field.PropertyType.IsValueType)
            {
                var defaultValue = Activator.CreateInstance(field.PropertyType);
            }
            else report.UnrecognisedFields.Add(string.Format("{0} ({1})", field.Name, field.GetType().Name));
        }
        return report;
    }

    private static bool Ignore(string name)
    {
        return (name.EndsWith("Id")); // Ignore primary/foreign keys
    }
}

public class ViewModelProgressReport
{
    public ViewModelProgressReport()
    {
        IgnoredFields = new List();
        UnrecognisedFields = new List();
    }
    public int NumberOfFields { get; set; }
    public int FieldsCompleted { get; set; }
    public double Percent { get { return NumberOfFields > 0 ? ((double)FieldsCompleted / NumberOfFields) * 100 : 0; } }
    public List IgnoredFields { get; set; }
    public List UnrecognisedFields { get; set; }
}
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!

I guess this is the natural way to start a blog like this; hi to anyone reading! My name’s Jordan, senior software developer at Tech13 Ltd, C#/web development enthusiast. I’ve started this blog really to share some of my experiences working as a software developer, and also in the hope that I can cover issues that I’ve come across that were perhaps not quite solvable through stackoverflow or googling alone!

So maybe some quick facts about me?

  • Well, I just started as a senior software developer last month. It’s my first project management experience, currently only leading a small team but one that’s expected to grow over the next year. I’m hugely grateful to my bosses for the chance!
  • I’ve got a BSc in Artificial Intelligence and Computer Science from the University of Birmingham
  • I’ve got an HTC HD7 running Windows Phone 7, and it makes me pretty damn sad that fewer people are using WP7! I love my phone…
  • I’m from Devon, but currently living in Birmingham with my fiancé, who I owe the world to
Right then, enough of that, hopefully I can get back here soon and get some actual posts written!