Design, Build and Release

Ramblings of IainJMitchell on C#, javascript and Software Design

An quick introduction to nodejs

leave a comment

Introduction

nodejs is here, it’s going to save the world, long live Javascript!
Oh really?
As Chuck D says “Don’t believe the Hype”, however I’ve been using nodejs for a year or so and I quite like it.

Server side Javascript?

Well it is the simplest definition, but not 100% accurate. Yes, nodejs code is written in Javascript (the clue is in the js part of the name), but it’s actually defined as Event Driven, Asynchronous IO.

  1. Event Driven – eventing is built into the framework, which allows us to pass messages/commands in a nice OO friendly manor (tell don’t ask)
  2. Asynchronous IO – input and output does not block, which means no need for complex thread management

What do I need?

nodejs runs on Windows and Linux (I’d recommend the latter), it can be downloaded from here or directly from the git repository.

Fisherprice, my first node app

require('http')
	.createServer(function (request, response) {
		response.writeHead(200, {'Content-Type': 'text/plain'});
		response.end('Hello World');
	})
	.listen(1337);

console.log('Server running');

To execute the code we execute node from the command line, using the file name as an argument, e.g.
node helloWorld.js.

This code creates an app that is hosted at http://localhost:1337, when this address is hit the response will be a HTTP 200 (success) with the text ‘Hello World’. Pretty simple and no need for hosting in a separate web server*.

We can also rewrite this example to work with net.tcp:

require('net')
	.createServer(function (socket) {
		socket.write('helloWorld')
	})
	.listen(1330);

It’s all about the modules

You probably noticed the require keyword in the above examples, which is a request to load up a named module. This is possible because nodejs implements the CommonJS standard of defining and loading modules.

This allows us to define our own modules, like so:

var helloWorlder = function(){
	return 'hello world';
};

exports.helloWorlder = helloWorlder;

The exports object allows us to define the API of our module, in this case this is just a simple ‘hello World’ function. If this is saved in a file named aModule.js, then we can utilise this in another node application like so:

var module = require('./aModule.js');

console.log(module.helloWorlder());

Open source == Communism?

Of course, it would be dull world if we kept our node modules to ourselves. nodejs is all about open source and sharing our code, and this is where Node Package Manager (NPM) comes in.

NPM allows you to consume open source node modules and also submit your own. After installation NPM allows you to install modules at the command line, such as the following example for underscore:
NPM install underscore

After successfully running this command, you can then use underscore in your node app:

_ = require('underscore');
var collection = [1,2];
console.log(_.first(collection));

Good practice -> node modules differ from the large client side libraries (e.g. jQuery, Mootools etc), they tend to be smaller and focussed on one particular task.

Eventing

This often overlooked feature of node is implemented through the EventEmitter class, which allows code to publish messages/commands to other subscribing sections of code. Here is an example of a direct use of the event emitter:

var EventEmitter = require('events').EventEmitter;
var publisher = new EventEmitter();

publisher.on('stuff', function(){
	console.log('stuff event fired');
});

publisher.on('stuff', function(){
	console.log('other stuff event fired');
});

publisher.emit('stuff');

When this code is executed the emit call will output the following to the console:
stuff event fired
other stuff event fired

Classes can also inherit from the EventEmitter, allowing them to have their own dedicated subscribers that they can emit to (see my node shopping cart kata for an event driven node solution).

Lessons Learnt

  • Unit Testing – There is a node port of Jasmine, but I’d recommend Vows, which is an asynchronous unit testing framework designed for use with node
  • Coffeescript – This is a language that compiles down into Javascript, it gives you a more ruby like syntax and much easier construction of classes and inheritance. Although the outputted Javascript is a bit too verbose for client side code, it is great for node. More details here.
  • MVCExpress is a lightweight MVC framework for node (think more Sinatra/Nancy rather than ASP.NET MVC).
  • DevelopmentNodeMon can be used to watch files in a directory and restart your node application if they change.

Other useful links

Github repository containing the examples from this post.
Github repository of the shopping kata in nodejs.
Introduction to nodeJs by the creator Ryan Dahl.
@nodejs
@ryah

* Okay, it probably is a good idea to host behind a web server for web facing services, many leading web servers now have support for nodejs processes.

Written by IainJMitchell

May 18th, 2012 at 1:32 pm

Posted in Uncategorized

Tagged with , , ,

Rake copy directory task

leave a comment

A simple, recursive copy directory task for rake:

require 'fileutils'

@source = "./configs"
@target = "./exports"
@includePattern = "/**/*.config"

task :default => [:copyDirectory]

task :copyDirectory do
	FileUtils.rm_rf(@target)  #remove target directory (if exists)
	FileUtils.mkdir_p(@target) #create the target directory
	files = FileList.new().include("#{@source}#{@includePattern}");
	files.each do |file|
		#create target location file string (replace source with target in path)
		targetLocation = file.sub(@source, @target)
		#ensure directory exists
		FileUtils.mkdir_p(File.dirname(targetLocation));
		#copy the file
		FileUtils.cp_r(file, targetLocation)
	end
end

That is all.

Written by IainJMitchell

April 2nd, 2012 at 10:20 am

Posted in Uncategorized

Tagged with ,

Extending classes with IExtensibleObject

leave a comment

Introduction

One of the key features of Windows Communication Foundation (WCF) is the ability to extend various parts of the framework, by adding and/or replacing behaviours. Many of these extension points are implemented by using the IExtensibleObject interface. This post is going to examine how this works and the reasons for using it.

The IExtensibleObject Interface

Classes implement IExtensibleObject in order to be extendible. The interface is defined in .NET as:

namespace System.ServiceModel
{
    public interface IExtensibleObject<T> where T : IExtensibleObject<T>
    {
        IExtensionCollection<T> Extensions { get; }
    }
}

This interface ensures that implementers have a publicly accessible IExtensionCollection, which is the access point for injecting custom behaviour. The example below demonstrates a custom extension being added, via this property, to the InstanceContext in WCF:

  instanceContext.Extensions.Add(customExtension);

The simplest implementation of this interface would look like this:

public class ExtendableClass: IExtensibleObject<ExtendableClass>
    {
        public IExtensionCollection<ExtendableClass> Extensions
          { get; private set; }

        public ExtendableClass()
        {
            this.Extensions =
              new ExtensionCollection<ExtendableClass>(this);
        }
    }

The class adds a setter to the Extensions property, and ensures that the property is initialised during class construction.

Implementing an extension (via IExtension)

In order to be added to the IExtensibleObject.Extensions collection, the class has to implement the generic interface IExtension. This is defined in .NET as:

namespace System.ServiceModel
{
    public interface IExtension<T> where T : IExtensibleObject<T>
    {
        void Attach(T owner);
        void Detach(T owner);
    }
}

Classes that implement this interface will have to define Attach() and Detach() functions. These are called when automatically on an instance, when it is added to a IExtensibleObject.Extensions collection. The owner argument will be the IExtensibleObject class that they are being added to.

Below is a very simple implementation of an extension class for our ExtendableClass. The Attach() and Detach() functions have been implemented simply as console writes.

public class ExtensionClass: IExtension<ExtendableClass>
{
   public void Attach(ExtendableClass owner)
   {
      console.WriteLine("attached!");
   }

   public void Detach(ExtendableClass owner)
   {
      console.WriteLine("detached!");
   }
}

Putting it together

Here is an example of the ExtendableClass and ExtensionClass in action:

var extendable = new ExtendableClass();
var extension = new ExtensionClass();
extendable.Extensions.Add(extension); //writes 'attached!' in console
extendable.Extensions.Clear(); //write 'detached!' in console

So, why would I use this?

The real power of the extensions is the way that they can access the extendible object on the Attach() and Detach() functions. They can then interact with any publicly exposed members on this, without the orchestrating code being aware of it.

Below is a different example of IExtensionObject and IExtension that demonstrate this. The NameExtenable is the extension object, which also holds an internal list of names and methods to add and remove names. There is also a method GetNames() that returns a string of all the names it holds.

public class NameExtendable : IExtensibleObject<NameExtendable>
{
    private readonly List<string> _names = new List<string>();
    public IExtensionCollection<NameExtendable> Extensions
        { get; private set; }

    public NameExtendable()
    {
        this.Extensions = new ExtensionCollection<NameExtendable>(this);
    }

    public void AddName(string name)
    {
        this._names.Add(name);
    }

    public void RemoveName(string name)
    {
        this._names.Remove(name);
    }

    public string GetNames()
    {
        return _names.Aggregate(new StringBuilder(),
            (sb, name) => sb.Append(name),
            sb => sb.ToString());
    }
}

public class IainNameExtension: IExtension<NameExtendable>
{
    public void Attach(NameExtendable owner)
    {
        owner.AddName("Iain");
    }

    public void Detach(NameExtendable owner)
    {
        owner.RemoveName("Iain");
    }
}

public class TerryNameExtension : IExtension<NameExtendable>
{
    public void Attach(NameExtendable owner)
    {
        owner.AddName("Terry");
    }

    public void Detach(NameExtendable owner)
    {
        owner.RemoveName("Terry");
    }
}

The two extension classes (IainNameExtension and TerryNameExtension) use their Attach() and Detach() methods to add and remove a particular names to their owner.

So when we utilise the code, like this…

var nameExtendable = new NameExtendable();
Console.WriteLine("Names: " + nameExtendable.GetNames()); //Names: 

var iainNameExtension = new IainNameExtension();
nameExtendable.Extensions.Add(iainNameExtension);
Console.WriteLine("Names: " + nameExtendable.GetNames()); //Names: Iain

var terryNameExtension = new TerryNameExtension();
nameExtendable.Extensions.Add(terryNameExtension);
Console.WriteLine("Names: " + nameExtendable.GetNames()); //Names: IainTerry

nameExtendable.Extensions.Remove(iainNameExtension);
Console.WriteLine("Names: " + nameExtendable.GetNames()); //Names: Terry

..the resulting console output will resemble:

The code samples from this post are all in this Example solution

Written by IainJMitchell

March 16th, 2012 at 1:16 pm

Posted in Uncategorized

Tagged with ,

Kata exercise: Three is the magic number…

leave a comment

Background

The idea behind “Ping Pong” pairing is that the person driving constantly switches between the pair, so the three stages of Test Driven Development (test, implement and refactor) are carried out in the following pattern:

  1. Person A – Writes a test
  2. Person B – Implements it (to bare minimum)
  3. Person A – Refactors
  4. Person B – Writes a test

…and so on

However, what often happens is that the refactor stage is missed out, which leads to Person A writing all the tests and Person B doing all the implementation! The cause of this is often attributed to an overzealous implementation that is far from the bare minimum, though it can also be just be plain old forgetfulness.

The Kata exercise

Pick any simple Kata (we used the Roman Numerals Kata) and everyone splits into groups of threes, rather than pairs. The three should then tackle the problem with each person taking a TDD role in the cycle – so we end up with the following pattern:

  1. Person A – Writes a test
  2. Person B – Implements it
  3. Person C – Refactors
  4. Person B – Writes a test
  5. Person C – Implements it
  6. Person A – Refactors
  7. Person C – Writes a test

…and so on

The only additional rule is that if the person refactoring has nothing to refactor, then they have to role back to the last written test and start again.

Written by IainJMitchell

February 27th, 2012 at 7:51 pm

Posted in Uncategorized

Tagged with ,