Little nifties #1

Almost always, the first extensions methods I add to a system are these:

which allows me to format any sequence of stuff sensibly, easily, and inline, e.g. like so:

and so:

and so:

Nifty!

Tell, Don’t Ask

or “How big is an interface?”… Uuuh, what?

Well, consider these two interfaces:

– which is bigger?

If you think that ISomeService1 is the bigger interface, then there’s a good chance you’re wrong! Why is that?

It’s because an interface is not just the signatures of the methods and properties it exposes, it also consists of the types that go in and out of its methods and properties, and the assumptions that go along with them!

This is a fact that I see people often forget, and this is one of the reasons why everything gets easier if you adhere to the Tell, Don’t Ask principle. And by “everything”, I almost literally mean “everything”, but one thing stands out in particular: Unit testing!

Consider this imaginary API:

Now, in our system, on various occasions we need to change the values for a particular name. We start out by doing it like this:

Obviously, if GetValues returns a reference to a mutable object, and this object is the one kept inside the value store, this will work, and the system will chug along nicely.

The problem is that this has exposed much more than needed from our interface, including the assumption that the obtained Values reference is to the cached object, and an assumption that the Value1 and Value2 properties can set set, etc.

Now, imagine how tedious it will be to test that the Run method works, because we need to stub an instance of Values as a return value from GetValues. And when multiple test cases need to exercise the Run method to test different aspects of it, we need to make sure that GetValues returns a dummy object every time – otherwise we will get a NullReferenceException.

Now, let’s improve the API and change it into this:

adhering to the “Tell, Don’t Ask” principle, allowing a potential usage scenario like this:

As you can see, I have changed the API from a combined query/command thing to a pure command thing which appears to be much cleaner to the eye – it actually reveals exactly what is going on.

And testing has suddenly become a breeze, because our mocked ISomeKindOfValueStore will just record that the call happened, allowing us to assert it in the test cases where that is relevant, ignoring it in all the other test cases.

Another benefit is that this coding style lends itself better to stand the test of time, as it is more tolerant to changes – the implementation of ISomeKindOfValueStore may change an in-memory object, update something in a db, send a message to an external system, etc. A command API is just easier to change.

Therefore: Tell, Don’t Ask.

Getting my Mongo on

This is the sixth post in a small series on Node.js. In this post, I will take a look at how to use my MongoDB from a Node app.

First, let’s install a driver for MongoDB: node-mongodb-native:

NPM really make it easy to get going!

Now, in order to connect to MongoDB, do this:

This should be done only once when the application starts up.

Then, to access a collection, do this:

Inside the function above, coll gives you access to do all the usual stuff to a MongoDB collection. To name a few, there’s insert, find, findOne, ensureIndex, count, etc.

As the node-mongodb-native documentation is pretty sparse, I’ve found it useful to open up a Node.js shell and connect with the driver, allowing me to inspect the various objects’ properties and methods, e.g. by inspecting db.__proto__ like so:

and coll.__proto__ like so:

Of course this way of barfing functions all over the place is not pretty, but it makes it possible to get a glimpse of what kinds of operations that can be performed on the various objects.

Getting Express to show flash messages

Now, this one might be obvious if you’re experienced with Node.js and Express, but it took me a while to figure out… therefore, so I know where to look the next time I forget it, and as a service to people Googleing in frustration; without further ado:

How to make Express render flash messages

First: Realize that flash messages are messages that are stored on the server for the duration between two requests from the same client, and thus are only available in the next request :D. Don’t try to req.flash(...) stuff and expect it to be available when render ing the view immediately after… (yeah, I did that for some time – pretty stupid, I know)… the locals object is how you do that.

Next: You need to make sure that the cookie decoder and session middleware are active:

Then: To store messages to be shown in the next request:

Note how nifty the PRG pattern can be implemented with Express. Note also that flash supports formatters, where the default supports %s and _, e.g.

resulting in something like this (with jQuery UI for formatting):

Last: When handling the next request, the flash messages are available in an object that can be retrieved only once by calling flash with no arguments on the request:

Now, having passed the flash object to my view, I can do this in my HAML view:

where the preliminary :if typeof flash != 'undefined' ensures that we don’t get errors if we haven’t transferred the flash object to the locals object.

The only annoying thing is that we need to remember to transfer the flash object in each request handler. I set out to write a piece of Node.js middleware that handled this, and I thought it was going pretty well until I realized that the middleware was executed in the wrong place. I haven’t found out if there’s an appropriate hook that can do this, so if anyone knows, please tell me :).

How Windsor’s decorators can save your life (almost)

Have you ever needed some kind of “master switch” in your application – i.e. some central place to flick a bool, resulting is changed behavior in numerous places?

Recently, we got the requirement that our application could function in two modes: active and passive. In active mode, the application must work like usual, whereas in passive mode, the app must not do anything to the outside world.

In our app, doing stuff to the outside world can be two things:

  • Writing stuff to a bunch of external SCADA systems.
  • Publishing status messages via NServiceBus.

which means that in order to implement passive mode, we need to avoid doing these two things.

Now, since everything in our app is wired by Windsor, and Windsor supports the nifty decorator pattern, implementing this “master switch” was a breeze!

The master switch

First, we implemented something like this to capture the switch itself:

which is registered like this:

Note th at the switch is a singleton, thus allowing all other services to have the same instance injected. Note also that concurrency is not an issue in our system – if MasterSwitch was to be used e.g. in an ASP.NET MVC application, it would have had a couple of locks in there or something similar.

Intercepting writes to external systems

All external hardware communication goes through an implementation of this interface:

so in order to abort all writes when we’re in passive mode, we added a new implementation of IExternalStuff that looks something like this:

Note how ExternalStuffWithMasterSwitch depends on IExternalStuff – this is where Windsor gets really cool, because if I remember to register my components in the following order:

then Windsor is smart enough to resolve the ExternalStuffWithMasterSwitch supplying the next available implementation of IExternalStuff, instead of entering a cycle.

Thus, we have cancelled all writes through IExternalStuff in our entire application with a few lines of extra code.

Avoiding publishing status messages

First, we needed som way to tell if a message was a status message, which was pretty easy – now all our status messages “implement” this marker interface which in turn implements IMessage from NServiceBus:

So, in order to “swallow” all published status messages when we’re in passive mode, we implemented this decorator to IBus:

which must be registered before NServiceBus’ own IBus gets registered:

I think this is a really cool example on how wiring everything with an IoC container provides some cool hooks in an application, allowing you to modify behavior in an extremely agile and non-intrusive manner.

2010 retrospective and 2011 resolutions

Now that ++year == 2011, and the last remaining effects of New Year’s Mojitos has finally left my brain, I think it is in order to take a look back at 2010 and evaluate a bit, and then maybe come up with some goals for 2011.

2010 retrospective

2010 has been pretty busy for me – check out this list of professional as well as personal activities:

  • My 2nd child was born in February :).
  • Wrote 34 blog posts spread pretty evenly over the year (except February).
  • Gave two talks on MongoDB in June, two talks on Castle Windsor in November and December, and two talks on NServiceBus in December.
  • Gave two 2-day introductory courses on getting up to speed with C#, .NET, dependecy injection, unit testing, and continous integration.
  • Gave one 1-day course as an introduction to C#, . NET, and WCF.
  • Gave 2 courses on NServiceBus.
  • Spent September and October on paternity leave.
  • Spent most of my other professional time as a development and architecture consultant on the core team of Dong Energy’s smart grid project, PowerHub. We’re controlling a hydro power plant right now at this very moment :).
  • Participated in two episodes of ANUGCast about MongoDB: Part 1 and part 2.
  • Learned a lot about new and emerging .NET technologies, NoSQL databases, and about architecture in general.

Looking back at all this, I think 2010 has been a little bit too busy – especially since most of the presentations and teaching happened in November and December :).

2011 resolutions

This is what I’d like to do in 2011:

  • I would like to continue doing all these great things in 2011, because that’s what makes my job alternating and fun, but ideally I would like to spread the activities some more.
  • I would like to start a pet project – i.e. build “something real”.
  • I would like to continue widening my horizon by cheching out non-.NET-stuff, like e.g. MongoDB and Node.js, which I am actually starting to like quite a bit.
  • I would like to continue contributing to OSS – either in a direct manner with code, or indirectly by blogging, tweeting, helping, creating courses, etc.
  • I would like to continue communicating with great people and be inspired.

Actually I should have hightlighted that last bullet – I guess it pretty much sums up my main goal for 2011 :).

How to loop good

…or “Short rant on why C-style for-loops are almost always unnecessary “…

If you’ve been with C# for the last couple of years, your coding style has probably evolved in a more functional direction since the introduction of C# 3/.NET 3.5 with all its LINQ and lambda goodness.

In my own code, I have almost completely dismissed the old C-style for-loop in favor of .Select, .Where etc., making the code way more readable and maintainable.

The readability and maintainability is improved because long sequences for for/ foreach and collection-juggling can now be replaced by oneliners of selection, mapping, and projection.

One place, however, where I often see the for-loop used, is when people need to build sequences of repeated objects, or where some variable is incremented for each iteration.

Now, here is a message to those developers: Please realize that what you actually want to do is to repeat an object or map a sequence of numbers to a sequence of objects.

Having realized that, please just implement it like that:

Same thing goes for sequences of elements where something is incremented:

There’s just too many for-loops in the world!

Not the same thing, but still somehow related to that, is when people need to collect stuff from multiple properties and ultimately subject each value to the same treatment – please just implement it like that:

</rant>

How to avoid (unnecessarily) touching the container

…or “How to resolve stuff all over the place” – two appropriate titles for a blog post that shows the solution to a problem you will eventually run into when using an IoC container… if not in your first application, then maybe in the next…

What’s the problem?

Not all applications lend themselves equally well to leveraging an IoC container for resolving stuff. Generally, applications that follow some kind of request-response pattern are easy to adapt to use the container to build objects that handle requests: Just resolve some kind of handler that handles each request.

E.g.: It is trivial to make Castle Windsor resolve/release controllers in an ASP.NET MVC application by implementing a CastleWindsorControllerFactory.

There are applications however, that do not follow this kind of pattern – or at least not as clearly. Take for instance a typical Windows Forms desktop application that looks like this:

An attempt to use the container could look like this:

But then one problem remains: How can we make the Windows Forms application use our beloved Windsor Container without resolving the entire world at this point?

E.g. if MainForm at some point needs to show a SubForm, then how do we do that without doing a new SubForm() inside of MainForm, thus tying MainForm directly to the concrete SubForm? (and worse: ruining our ability to unit test MainForm…?)

Let’s try using a service locator

In order to avoid new’ing up SubForm, we could use a service locator to provide the form to us. Consider this button handler:

That solves the problem, right? Wrong! I mean, now SubForm can have dependencies injected and stuff, but MainForm is tied to a class called ServiceLocator with a static generic method that creates stuff.

That’s pretty hard to unit test, and in the long run this will just prove to be a serious PITA.

How to fix the problem

If we wanted to fix the problem with MainForm and SubForm, we could do it by passing a ISubFormFactory to MainForm like so:

thus allowing MainForm to instantiate SubForms at will without depending directly on the container. Now on to implement ISubFormFactory:

Now, why is that implementation uncool? There are several reasons, and two of them are: 1) I’m tying myself to a Windsor container somewhere in a static variable in my app, and 2) The implementation is stupid and boilerplate – I need to write one of these every time I need to show a new form… Uncool!

Enter TypedFactoryFacility

Windsor comes with a bunch of facilities in the box, and one of them fits this gap nicely: <a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx">TypedFactoryFacility</a>.

If TypedFactoryFacility had a tagline it would be either “The missing link!” or “Gimme another chance!” or something like that.

Put shortly, TypedFactoryFacility gives the container the ability to dynamically implement the ISubFormFactory interface from above, thus allowing my code to pull stuff from the container without even knowing it! \o/

In order to do that, I need to start out by registering the facility;

and then I need to register my factory service like so:

Now the container will delegate the call to CreateSubForm() to container.Resolve<SubForm>(), based on the return type of the factory method – nifty!

When working with Windsor, it is very important that everything that has a transient lifestyle gets properly released! – the facility has this capability as well, just implement a method with the following signature on the factory: void Release(SubForm subForm).

Now our MainForm’s event handler can look like this:

allowing Windsor to properly take care of decommission concerns, thus properly disposing IDisposables and more.

I hope this post gave an understandable introduction to TypedFactoryFacility. To help some more, I have created a simple Windows Forms application on GitHub that shows how a simple Windows Forms application can implement a simple MVC pattern using Castle Windsor and TypedFactoryFacility.

Comments, questions and suggestions are appreciated 🙂

What is that module thing again?

This is the fourth post in a small series on Node.js. In this post, I will take a look at how the Node.js module mechanism works.

In my previous posts on Node.js, I nonchalantly went ahead and require(...)d something called http – but what was that? And what happened when I did that?

Well, require is one of the few globals when running a Node program, and it is used to import a module. The parameter is a string, which Node uses to look for a file to load.

The simplest usage refers directly to a file relative to the path of the currently running program. E.g., if I have a module residing in a file called importantBizLogic.js in the lib folder beneath my program’s directory, I can include its exports (which I’ll get back to in a moment :)) like so:

If I omit the ./, Node will go look for importantBizLogic in each directory in the require.paths array, which is a list of default paths to search for modules.

Let’s see what it contains… Go to a terminal and enter the Node shell:

Great – so that’ s where my global modules reside. Now, what was that export thing again?

Well, that’s related to how importantBizLogic.js is structured… in order to control how the import works, a module must explicitly export stuff – and that can be done like so:

– allowing this module to be imported and used like so:

Nifty!

Apparently – and I am almost embarrassed that I did not know that – there is a thing called CommonJS, which is an initiative that strives to create a JavaScript standards library – and the require stuff I’ve described here is actually just Node implementating the CommonJS Modules specification. Pretty sweet, actually!

Up and running with Express

This is the third post in a small series on Node.js. In this post, I will take a look at how to get up and running with Express.

Let’s get Express installed – first, let’s install NPM – a package manager for Node:

That was easy. Now, Express can installed like this:

Too easy!

Now, let’s create a simple app like we did the last time:

Punch in the following few lines:

and run the app from the terminal like so:

and navigate to http://localhost:3000 – on my machine it looked like this:
Hello Express

That was easy. See how the API pretty much resembles Node’s builtin HTTP server, except it adds routes into the mix!

Now, in order to build a web site we need some kind of view engine to help generate some HTML for us. I have used Haml a couple of years ago, and I really liked it… and luckily, some nice people have made Haml available to Node apps, so let’s try installing that:

Now we configure Express by punching in the following stuff in the app:

As you can see, I tell Express to use Haml as the default view engine. Moreover, I configure Express to serve static content from the /public folder in my app dir, and then I install the bodyDecoder middleware which will parse incoming posts and make posted values available in req.body.

Now, let’s alter our action to render a view:

and now create two files, layout.haml and index.haml in the /views folder. Mine look like this – /views/layout.haml:

and /views/index.haml:

Now, let’s go to the terminal and node app.js and navigate to http://localhost:3000 – on my computer it looks like this:
Hello Express + Haml

As you can see, view models can be handed to the view via the locals object.

This was some basic web app stuff – only thing missing is some way to persist data, so next time I will take a look at how to get my Mongo on…