Deploying a new NodeJS application to Azure, I came up against the following error runtime error:


Application has thrown an uncaught exception and is terminated:
Error: listen EADDRINUSE

The NodeJS app in question was set to listen on a port defined by the environment as such:


var port = process.env.PORT || 8080;
app.listen(port);

The particular issue I was facing was that process.env.PORT was returning NAN and this was being sent to app.listen.
Not wanting to remove the check for process.env.PORT the solution was to parse the value as an int to make sure that the fallback to port 8080 worked correctly.


var port = parseInt(process.env.PORT) || 8080;
app.listen(port);

Being new to Node my understanding of this is still quite basic and so there may have been some configuration that I missed in the first place.


Since we don’t have a garden to accompany our apartment, we decided on the next best thing, a balcony garden.

After spending only a little time preparing the box and planting the fruits and herbs, I feel like gardening and engineering have a lot in common.

We bought all of the bits from Homebase. The box was £40 and the Soil, Sand, Weed Control Fabric and Stones came to about £20.

I’ve been wanting to grow some chillies for a while so we now have Bellboy, Jalapeño, Apache and something called “Hot Chilli Pepper” (I lost the label for this one). We also have a couple of Tomato plants, some Basil, Thyme, Chives, and Parsley.

We’re looking forward to our first meal with our homegrown ingredients. Here’s some pictures of the planting process from empty-box to complete.


Ever needed to merge two collections  by interleaving them whilst still retaining the remaining items from the largest collections?

We wrote a small extension method to do just this:

?View Code CSHARP
public static IEnumerable<T> Interleave<T>(
                IEnumerable<T> first, 
                IEnumerable<T> second)
        {
            using (IEnumerator<T> firstEnumerator = first.GetEnumerator(), 
                                  secondEnumerator = second.GetEnumerator())
            {
                bool hasFirstItem = true;
                bool hasSecondItem = true;
 
                while (hasFirstItem || hasSecondItem)
                {
                    if (hasFirstItem)
                    {
                        hasFirstItem = firstEnumerator.MoveNext();
 
                        if (hasFirstItem)
                        {
                            yield return firstEnumerator.Current;
                        }
                    }
 
                    if (hasSecondItem)
                    {
                        hasSecondItem = secondEnumerator.MoveNext();
                        if (hasSecondItem)
                        {
                            yield return secondEnumerator.Current;
                        }
                    }   
                }
            }
        }

and some tests to prove the behaviour:

?View Code CSHARP
[TestMethod]
            public void Then_Should_Return_Interleaved_Collection_When_Inputs_Are_Same_Size()
            {
                var first = Enumerable.Repeat("First", 2);
                var second = Enumerable.Repeat("Second", 2);
 
                var interleaved = first.Interleave(second).ToList();
 
                Assert.AreEqual(4, interleaved.Count());
 
                Assert.AreEqual("First",  interleaved[0]);
                Assert.AreEqual("Second", interleaved[1]);
                Assert.AreEqual("First",  interleaved[2]);
                Assert.AreEqual("Second", interleaved[3]);
            }
 
            [TestMethod]
            public void Then_Should_Return_Interleaved_Plus_Extra_Items_When_First_Input_Bigger()
            {
                var first = Enumerable.Repeat("First", 4);
                var second = Enumerable.Repeat("Second", 2);
 
                var interleaved = first.Interleave(second).ToList();
 
                Assert.AreEqual(6, interleaved.Count);
 
                Assert.AreEqual("First",  interleaved[0]);
                Assert.AreEqual("Second", interleaved[1]);
                Assert.AreEqual("First",  interleaved[2]);
                Assert.AreEqual("Second", interleaved[3]);
                Assert.AreEqual("First",  interleaved[4]);
                Assert.AreEqual("First",  interleaved[5]);
            }
 
            [TestMethod]
            public void Then_Should_Return_Interleaved_Plus_Extra_Items_When_Second_Input_Bigger()
            {
                var first = Enumerable.Repeat("First", 2);
                var second = Enumerable.Repeat("Second", 4);
 
                var interleaved = first.Interleave(second).ToList();
 
                Assert.AreEqual(6, interleaved.Count);
 
                Assert.AreEqual("First",  interleaved[0]);
                Assert.AreEqual("Second", interleaved[1]);
                Assert.AreEqual("First",  interleaved[2]);
                Assert.AreEqual("Second", interleaved[3]);
                Assert.AreEqual("Second", interleaved[4]);
                Assert.AreEqual("Second", interleaved[5]);
            }

For the majority of cases the default model binder in MVC does all that we need it to do. Other times we just need to get stuck in and write our own and the process is largely painless.

Testing the Model Binders that we write, on the other hand, whilst not complicated in the traditional sense of complex algorithms and abstract thinking, is complex in that other way.
Ok, so complex probably isn’t the perfect word. I need another word that defines complexity in terms of the availability of information on a given topic and the obvious nature of the problem being solved.

Two things we do know about testing our model binder is that we’ll need an instance of it, and a way of providing it with some test data to bind against.

The second part of that raises some interesting questions. If we’re going to use test data then we need somewhere to store it that our model binder can access it. This forces us to look at the implementation of our model binder.

Handily we have access to a ValueProvider as part of the ModelBindingContext. Whilst there are other ways of obtaining the data to be bound, such as the ControllerContext.HttpContext.Request object, life becomes a little easier when we use the ValueProvider on the BindingContext.

(I know this because I was initially getting form values from controllerContext.HttpContext.Request["MyField"] and after writing the first test, discovered tis probably wasn’t the best idea)

In our test we can start by working backwards given the knowledge we currently have. That is, we can create an instance of our model binder, see what methods are available to us to get things going and work backwards from there.

If our model binder implements IModelBinder and doesn’t inherit or implement anything else, we’ve got a pretty limited number of methods we can work with. The most notable of these is the BindModel() method. This is the bit that’s going to kick things off and do the work we most likely want to test. If you’re inheriting your model binder from DefaultModelBinder and making use of the BindProperty method, you’ll note that, since it’s a protected method, it won’t be available to test directly. That’s OK since BindModel is going to call BindProperty for each property that it encounters so we’re good.

BindModel wants us to give it a couple of parameters, a ControllerContext and a BindingContext.

Since in my own example I’m now getting the form data from the BindingContext.ValueProvider, we can assume that the controller context doesn’t need anything doing with it. We can either create a mock or instantiate a new one for use:

?View Code CSHARP
var controllerContext = new ControllerContext();

Creating the binding context is the bit that takes a little more thinking about and probably some googling.

Both BindModel and BindProperty take a ModelBindingContext (System.Web.Mvc.ModelBindingContext) which we can go ahead and create which now means we have build-able code.

?View Code CSHARP
var controllerContext = new ControllerContext();
var bindingContext = new ModelBindingContext();
var modelBinder = new CustomModelBinder();
var result = modelBinder.BindModel(controllerContext, bindingContext);

At this point you’ll notice that there’s not a lot you can do with the result as it is and there’s no generic version of BindModel, so we’ll want to cast this to the type we’re binding to:

?View Code CSHARP
var result = (CustomModel)modelBinder.BindModel(controllerContext, bindingContext);

Now we need to figure out how to tell our binding context what we’d like to try and bind and to what model type.

ModelBindingContext has two main properties that we’re interested in: ValueProvider and ModelMetaData. There’s also a third parameter, ModelName, but I’ll come back to that in a moment.

In production our ValueProvider is going to be the forms collection that was posted to the server. In our test we need to create our own value provider and give it some data.

NameValueCollectionValueProvider in System.Web.Mvc is one value provider we can use quite easily and, as you can infer from its name, it’s a value provider for a NameValueCollection.

We can use the NameValueCollection to mimic our form post. My custom model binder is looking for the values “DateOfBirth.Day”, “DateOfBirth.Month” and “DateOfBirth.Year” inside the ValueProvider so we can also do the same in our NameValueCollection:

?View Code CSHARP
var formCollection = new NameValueCollection
                    {
                        { "DateOfBirth.Day", "08" },
                        { "DateOfBirth.Month", "10" },
                        { "DateOfBirth.Year", "1984" }
                    };
 
var valueProvider = new NameValueCollectionValueProvider(formCollection, null);

The ModelMetadata property on the ModelBindingContext is basically the meta data for the model we’re binding to. If you’ve never needed to obtain model meta data before (as I hadn’t) you can do so using the GetMetadataForType method on the ModelMetadataProviders class as follows:

?View Code CSHARP
var modelMetaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(CustomModel));

The ModelName property on ModelBindingContext needs to be either string.Empty or the name of the model being bound to.

So we now have all of the pieces we need to test our model binder. Putting this together into a more generic and reusable method looks like this:

?View Code CSHARP
TModel SetupAndBind(NameValueCollection nameValueCollection) where TBinder : IModelBinder, new() where TModel : class
{
var valueProvider = new NameValueCollectionValueProvider(nameValueCollection, null);
var modelMetaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));
var controllerContext = new ControllerContext();
var bindingContext = new ModelBindingContext
      {
       ModelName = string.Empty,
       ValueProvider = valueProvider,
       ModelMetadata = modelMetaData,
      };
 
var modelBinder = new TBinder();
 
return (TModel)modelBinder.BindModel(controllerContext, bindingContext);
}

Which can then be used like:

?View Code CSHARP
var formCollection = new NameValueCollection
                    {
                        { "DateOfBirth.Day", "08" },
                        { "DateOfBirth.Month", "10" },
                        { "DateOfBirth.Year", "1984" }
                    };
 
var boundModel = this.SetupAndBind(formCollection);
Assert.AreEqual(DateTime.Parse("08/10/1984"), boundModel .DateOfBirth);

Creating distinct collections of items is generally pretty easy in C#. We’ve got the Enumerable.Distinct() extension method that can take an IEqualityComparer if required and most of the time we don’t need anything more powerful than this.

At other times we want our deduplication process to be a bit more involved. In my case, I need to deduplicate one collection based on items in x number of other collections.

Enter “DeduplicationService” and as Phil Karlton once said, with the latter being more than applicable here:

“There are only two hard things in Computer Science: cache invalidation and naming things.”

To begin with I had an idea of how I wanted to call my service and it looked like this:

?View Code CSHARP
service.Deduplicate(operand, x => x.Id, operatorList1, operatorList2, ...);

After a bit of investigation and upon implementing my first version of this I ended up with a method signature more like:

?View Code CSHARP
service.Deduplicate(operand, (x, y) => x.Id == y.Id, operatorList1, operatorList2, ...);

It turns out that this is actually rather useful if you want to deduplicate based on different properties between your operand and operators. You may want to deduplicate your operand based on its Id being equal to the ParentId of your operators, for example.

Since we’re currently passing in a Func to our Deduplicate method, I also wanted a way to deduplicate complex types based on a more complex comparison than just a single property. This led to introducing a new signature that takes an IEqualityComparerwhich turns out to be a great base for the rest of the method signatures I’ll describe.

So here’s how that method looks in its entirety:

?View Code CSHARP
public IEnumerable Deduplicate(IEnumerable operand, IEqualityComparer comparer, params IEnumerable[] operators)
        {
         // Flatten the operator collections into one collection.
         var operatorItems = operators.SelectMany(x => x);
 
         // Remove items from our operand collection that conform to our comparer.
         return operand.Except(operatorItems, comparer);
        }

Now that we have a flexible base to work from we need some prettier methods to call that do most of the common operations for us. The first of these brings us back to a previously mentioned signature:

?View Code CSHARP
public IEnumerable Deduplicate(IEnumerable operand, Func func, params IEnumerable[] operators)
        {
            var comparer = new Comparer(func);
            return this.Deduplicate(operand, comparer, operators);
        }

In this method we take a Func which translates as something like:

?View Code CSHARP
 (x, y) => x.SomeProp == y.SomeProp

We’ve also introduced a new type here, Comparer<T>. This is simple class that implements IEqualityComparerand gives us a way to wrap up our Func into something we can pass to IEnumerable.Except(). It looks like this:

?View Code CSHARP
public class Comparer : IEqualityComparer
    {
        private readonly Func comparer;
 
        public Comparer(Func comparer)
        {
            this.comparer = comparer;
        }
 
        public bool Equals(T x, T y)
        {
            return this.comparer(x, y);
        }
 
        public int GetHashCode(T obj)
        {
            return obj.ToString().ToLower().GetHashCode();
        }
    }

So now we can pass in a Lambda rather than creating a new equality comparer each time however this is still a bit convoluted for most situations. This brings me back to my most desired method signature:

?View Code CSHARP
service.Deduplicate(operand, x =&gt; x.Id, operatorList1, operatorList2, ...);

As it turns out this is pretty easy to achieve. We simply need a way of turning our Func<TIn, TOut> into a Func<TIn, TIn, bool> and since the result of this is the function of a comparison between x and y evaluated through the Func we end up with a slimline method that abstracts the detail from the consumer:

?View Code CSHARP
public IEnumerable Deduplicate(IEnumerable operand, Func func, params IEnumerable[] operators)
        {
            Func<TResult, TResult, bool> f = (x, y) => func(x) == func(y);
            return this.Deduplicate(operand, f, operators);
        }

We now have a clean method signature that accepts a simple Lambda and a few collections.

Job done? Almost.

Since internally (within our team) we know that most of our deduplication is going to be happening on items of a specific base class we can introduce a new signature that keeps things even more simple. It would be nice to have a method that knew what base type it was accepting and could present a default comparison, mitigating the need for any Lambda being passed in. For this we can just create a new signature that has a set property to filter on and we’re done!

?View Code CSHARP
public IEnumerable Deduplicate(IEnumerable operand, params IEnumerable[] operators)
 {
    return this.Deduplicate(operand, x => x.Id, operators);
 }
?View Code CSHARP
service.Deduplicate(operand, operatorList1, operatorList2, ...);

The full source code for this, with unit tests, can be found on GitHub here:

https://github.com/JamieDixon/DeduplicationService

If you have some ideas on how this can be improved then I’d love to hear them either in the comments or send me a pull request on GitHub!


As you do on a lazy Sunday afternoon, I started wondering how C# implements the foreach iterator.

I asked this question on StackOverflow and got a great reply from Jon Skeet and after reading section 8.8.4 of the C# 4 spec I thought it’d be a fun task to set about building a custom foreach. This is just an educational excersise for the sake of curiosity.

Here’s what I have so far:

?View Code CSHARP
public delegate void Statement(TElementType element);
?View Code CSHARP
public void ForEach(IEnumerable collection, Statement statement)
{
  var enumerator = (collection).GetEnumerator();
  try{
  	while(enumerator.MoveNext())
  	{
  		statement.DynamicInvoke(enumerator.Current);
  	}
  }
  finally{
  	IDisposable disposable = enumerator as IDisposable;
	if(disposable != null) disposable.Dispose();
  }
}

which you would use like:

?View Code CSHARP
	IEnumerable collection = new int[]{1,2,3,4};
	ForEach(collection, (int k) =&gt; {Console.WriteLine(k);});
 
	IEnumerable stringCollection = new []{"A","B","C","D"};
	ForEach(stringCollection, (string k) =&gt; {Console.WriteLine(k);});
 
	string[] x = new string[]{"E","F","G"};
	ForEach(x, (string k) =&gt; {Console.WriteLine(k);});

I’m currently unsure whether it’s possible to use the

?View Code CSHARP
Type x in collection

dialect but if I do I’ll put together a new version of this. What do you think? Any ideas on a more efficient/accurate way of doing this?

Update:

Jon just pointed out that I could be using Action T rather than the delegate I’ve choosen here. A somewhat “duh!” moment on my part.

?View Code CSHARP
public void ForEach(IEnumerable collection, Action<T> statement)
{
  var enumerator = (collection).GetEnumerator();
  try{
  	while(enumerator.MoveNext())
  	{
		statement(enumerator.Current);
  	}
  }
  finally{
  	IDisposable disposable = enumerator as IDisposable;
	if(disposable != null) disposable.Dispose();
  }
}

He also pointed out that I don’t need to be so explicit (in many cases) with the lambda expressions:

?View Code CSHARP
IEnumerable<int> collection = new int[]{1,2,3,4};
ForEach(collection, (k) => {Console.WriteLine(k);});
 
IEnumerable<string> stringCollection = new []{"A","B","C","D"};
ForEach(stringCollection, (k) => {Console.WriteLine(k);});
 
string[] x = new string[]{"E","F","G"};
ForEach(x, (k) => {Console.WriteLine(k);});

I’ve just started using AutoMapper this past two days and am really enjoying the experience. One thing I tend to do quite often is map one collection to another. AutoMapper handles this really well since the mappings need only be defined for the individual types.

Example:

?View Code CSHARP
Mapper.CreateMap<UserProfile, UserProfileDisplayViewModel>()

Because we only need to map the types and not the collections we can quite easily do something like:

?View Code CSHARP
Mapper.Map<IEnumerable<UserProfile>, IEnumerable<UserProfileDisplayViewModel>>(users);

This seems a bit unwieldy to me and since I’m using a wrapper over the Mapper object anyway I thought it’d be handy to add a method that would allow me to negate the IEnumerable decleration from my controllers mapping:

?View Code CSHARP
public IEnumerable<TOutput> MapEnumerable<TInput, TOutput>(IEnumerable<TInput> source)
        {
            return Map<IEnumerable<TInput>, IEnumerable<TOutput>>(source);
        }

Now we can keep our controllers looking a bit more readable:

?View Code CSHARP
AutoMapperWrapper.MapEnumerable<UserProfile, UserProfileDisplayViewModel>(users);

Being a contractor is wonderful.

When I first began contracting I felt a freshness and lightness to my working that I’d been seeking out for years. I felt more appreciated, less confined and more able to express myself in my work.

For a long time I thought all of those feelings and experiences had something to do with the outside world. That somehow the world was different because I was contracting.

Through the years I’ve learned a lot about myself and the world that I live in and I’ve come that little bit closer to understanding that my experience of the world is the one I create for myself.

The feelings of freedom, expressiveness and appreciation that I so easily attributed to some outside influence were really an indicator of the kinds of thoughts I was creating my experience from.

During the last few weeks of job searching I’ve been asked the same question by many recruitment agents: “What about going perm? How do you feel about that?” and my answer has been the same, although somewhat rote, to each one of them: “I’m not looking to go perm but show me what you’ve got. For the right company there’s always the chance”.

I was pretty convinced that I was going to continue contracting. I had a whole story in my head about what it would mean to go perm and what it means about me as a person.

Then I was introduced to blinkbox.com, the TV and Movie streaming service that boasts a subscription-free service and over 2 million monthly users.

I quite like movies. For those of you who know me and Karina, we average 2 visits per week to the cinema and both have Unlimited Cards (We can see as many movies as we like for £15 a month!).
We also tend to watch 2-3 movies per week at home as well as other great TV (Game of Thrones, House, Spartacus [ok,ok, i did say great TV]).

Intrigued by the idea of blinkbox and the work they’re doing I was put forward for interview for a new permanent position they were offering. I was still quite sure I wasn’t going to go perm but since I’d been saying “For the right company…” I figured it’d be useful to find out more.

Suffice to say that after meeting the guys at blinkbox and learning more about how they work, their passion for what they do and their appreciation of the developer species, I was impressed. Very impressed.

Yesterday I was offered a position with blinkbox as their newest Principal Development Engineer and was please to say “Yea!”.

Someone jokingly asked me if I was going to be developing principles at the company and the more I think about it, the more that makes sense. Being part of a wonderful team is a lot about developing ideas, ways of doing things, and a culture within the company. More than that, every interaction is an opportunity to be of service and to be part of making a difference in someones world. I’m certainly looking forward to developing those principles.

As for my thoughts on switching from contract to perm, they’re just thoughts. My experience of freedom, enjoyment and creativity are mine to explore and when I notice that I’m already free, that there’s nothing outside of me in this world that can take away the value of any person, I remember to wake up that little bit more and enjoy being present to a fantastic opportunity.

I’m excited to get started at blinkbox and I’ll let you know how it goes.

You can find out some more about blinkbox here http://www.blinkbox.com


Quite often it’s necessary to control the output of a method called from within a method we’re testing.

When this method is outside of the class we’re testing we simply create a mock of the interface for that class and setup the return value for the method in question.

But what about when we’re testing a method that calls another method in the same class? We don’t want to test that the called method works in our unit because we have a seperate test for that. So how can we control the output of this internal method call?

CallBase to the rescue!

Moq’s CallBase property allows us to inform a mocked object that we want it to invoke the base class implimentation if no expectation overrides the member.

That is to say, if we don’t Setup a given member on a mocked object it will invoke the base classes implimentation of that member. What this gives us is a way to set up an expectation for one member of a class whilst still running the base class implimentation of another.

Consider the following:

?View Code CSHARP
[TestFixture]
    public class CacheTests
    {
        private readonly Mock _mockCache = new Mock<Cache>();
 
        [SetUp]
        public void SetUp()
        {
            _mockCache.CallBase = true; // CallBase to the rescue!
        }
 
        [TestFixture]
        public class GetOrStoreMethodTests : CacheTests
        {
            [Test]
            public void ExecutesFuncWhenCacheReturnsNull()
            {
                _mockCache.Setup(m => m.Get(It.IsAny())).Returns(null);
                var output = _mockCache.Object.GetOrStore("foo", () => "Foo", 100);
 
                Assert.AreEqual("Foo", output);
            }
 
            [Test]
            public void ReturnsValueFromCacheWithoutExecutingFuncWhenCachReturnsItem()
            {
                _mockCache.Setup(m =>; m.Get(It.IsAny())).Returns("Foo");
 
                var output = _mockCache.Object.GetOrStore("foo", () => "Bar", 100);
                Assert.AreEqual("Foo", output); // Assert that cached version is returned
            }
        }
    }

For this set of tests I wanted to control the output of the Get method whilst still being able to correctly test the GetOrStore method. Using the CallBase property on the mocked object we can do this.

Posted in tdd

Someone over at StackOverflow was asking how to create a Html extension method that closed itself around a code block in the same way that BeginForm does inside a using statement.

I answered the question and thought I’d post the code here for anyone else looking to do something similar.

The way that this is done with BeginForm is that the return type, MvcForm, impliments IDisposable so that when used within a using statement, the Dispose method of MvcForm writes out the closing </form> tag.

You can write an extension method that does exactly the same thing.

Here’s one I’ve written to demonstrate.

First off, the extension method:

?View Code CSHARP
public static class ExtensionTest
    {
        public static MvcAnchor BeginLink(this HtmlHelper htmlHelper)
        {
            var tagBuilder = new TagBuilder("a");
            htmlHelper.ViewContext.Writer
                            .Write(tagBuilder.ToString(
                                                 TagRenderMode.StartTag));
            return new MvcAnchor(htmlHelper.ViewContext);
        }
    }

 


And here’s our new type, MvcAnchor:

?View Code CSHARP
public class MvcAnchor : IDisposable
    {
        private readonly TextWriter _writer;
        public MvcAnchor(ViewContext viewContext)
        {
            _writer = viewContext.Writer;
        }
 
        public void Dispose()
        {
            this._writer.Write("</a>");
        }
    }

 


In your views you can now do:

?View Code CSHARP
@{
    using (Html.BeginLink())
    { 
        @Html.Raw("Hello World")
    }
}

 


Which yields the result:

<a>Hello World</a>;

 

Posted in MVC