Improving JavaScript arrays by turning them into underscore.js “collections”

Whenever I write JavaScript code, I always end up using underscore.js in some way. It feels so natural to me now that I often will include the library in my project before ever actually needing it, since I know I can turn to it. If you’re unfamiliar with how underscore.js works, I highly recommend taking a look at the link above. They describe the library as:

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux, and Backbone.js’s suspenders.

Underscore provides 80-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map, reduce, filter, every, some and indexOf.

An example of a very simple filter operation:

var simplearray = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10];
var greaterThanFour = _.filter(simplearray, function(item) {
    return item > 4;
}); // greaterThanFour contains a brand new array containing [5, 6, 7, 8, 9, 10]

Sometimes the syntax just feels wrong to some. As indicated by this stack overflow question

To quote:

What I was hoping for:

Make underscore’s methods more object oriented:
_.invoke(myCollection, ‘method’); ==> myCollection.invoke(‘method’);

I’ll admit, minor difference, yet still it seems nice.

What problems will I run into if I use Backbone.Collection for non-Backbone.Models?

Are there any existing implementations, or a simple way to make a generic underscore collection class?

That got me thinking… I love JavaScript… this is now a challenge.

What is the simplest way to express an underscore “collection”?

What I came up with was to modify the Array prototype to include functions that tie into underscore. I didn’t want to maintain some large library, though, like how Backbone.JS did it. So, instead, I figured I can just pull the functions out of underscore and stick them on the Array prototype like so:

// This self-executing function pulls all the functions in the _ object and sticks them
// into the Array.prototype
(function () {
    var mapUnderscoreProperty = function (prp) {
        // This is a new function that uses underscore on the current array object
        Array.prototype[prp] = function () {
            // It builds an argument array to call with here
            var argumentsArray = [this];
            for (var i = 0; i < arguments.length; ++i) {
                argumentsArray.push(arguments[i]);
            }

            // Important to note: This strips the ability to rebind the context
            // of the underscore call
            return _[prp].apply(undefined, argumentsArray);
        };
    };

    // Loops over all properties in _, and adds the functions to the Array prototype
    for (var prop in _) {
        if (_.isFunction(_[prop])) {
            mapUnderscoreProperty(prop);
        }
    }
})();

Here is the same example as above, written with the new Array prototype:

var simplearray = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10];
var greaterThanFour = simplearray.filter(function(item) {
    return item > 4;
}); // greaterThanFour contains a brand new array containing [5, 6, 7, 8, 9, 10]

I like the syntax better. It feels like the filter function is part of the Array object. Actually, because of JavaScript's dynamic nature, it IS.

How does JavaScript Scope work?

In a previous post, I reviewed how JavaScript treats the “this” keyword.. In this post, I want to talk about how JavaScript defines scope. As a C# programmer coming to JavaScript a few years ago, I did not know this fact, and thus I assumed my C# knowledge of “this” and scope would follow to JS.

Only functions create scope in JavaScript

Take the following C# code for example:

public int x = 1; // this is a class member, and thus is scoped to the class instance
void Foo()
{
    if (true)
    {
        int i = 1;
    }
    // i is inaccessible here, because it is scoped to the if block
}

And the following javascript code:

var x = 1; // Variables not declared in a function are global
function foo() {
    if (true) {
        var i = 1;
    }

    alert(i); // This is perfectly legal, and I is accessible here.

    // Any variables declared here are scoped to the function foo.
    // To force scope:
    (function () {
        var y = 1;
        z = 2; // Declare a variable in the global scope by leaving out the var keyword!
    })();
    // y is not accessible here, because it was declared inside of a function
    // an anonymous self executing function still creates scope
}

alert(z); // z is undefined
foo();
alert(z); // z is 2 after running foo().
alert(window.z); // z is attached to the window object because it was declared without var!

Pay attention to the comments, please. Especially the bit about leaving out var, creating a globally scoped variable attached to window.

This can be a big sticking point for developers coming from C# or Java where scope is very different. Many bloggers will take this type of post to the extreme and explain other concepts like closures and prototype, as well as combining the topic of context binding the “this” keyword, but I am keeping this succinct for a reason. I’ve already covered “this” in a previous post, and I can probably do a post on closures and using the prototype more in depth another time.

In my opinion, this topic stands on its own as one of the most confusing points for a developer that is new to JavaScript, so it deserves a separate post.

JavaScript and the “this” keyword

One of the things that tripped me up when I first learned JavaScript was the “this” keyword. I came from a pure OO world, where classes were clearly defined objects, and “this” always referred to the object in context. JavaScript is a prototype based scripting language, though, and as such, doesn’t have the concept of a class. The “this” keyword means something very different in JavaScript.

According to the ECMAScript language specification:

The this keyword evaluates to the value of the ThisBinding of the current execution context. 

And the “ThisBinding” keyword is:

The value associated with the this keyword within ECMAScript code associated with this execution context.

So, both definitions refer to the other, which I was always taught in elementary school was not to be done! In my opinion, this definition is rather useless to the new JavaScript developer. Practical examples are much more useful!

In JavaScript in a browser, all global functions are bound to the Window object. You can see the behavior by running this bit of code in any browser’s developer console:

(function () {
    console.log(this); // [object Window]
})();

It’s a self executing function that exists in the global scope, and the console.log(this); line should write out [object Window] or something similar. That’s because “this” is a reference to Window. In a function like this, anything that exists on the Window object is also available through the “this” keyword:

(function () {
    this.alert(0);
})();

Because the alert function exists in the global scope, it is attached to the Window object. A related phenomenon occurs when you declare global variables:

hello = function() {
    alert('hello');
}

(function () {
    this.hello(); // same as calling window.alert('hello');
})();

This is the default behavior, but that’s only when functions are declared, or rather, bound to the global scope when executed. One can easily rebind a function with .call() or .apply():

var newobj = {
    alertit: function (message) {
        alert(message);
    }
};

var func = function (message1, message2) {
    this.alertit(message1 + " " + message2);
};

func.call(newobj, 'hello', 'world'); // alerts hello world
func.apply(newobj, ['hello', 'world']); // alerts hello world

the .call() and .apply() functions are both used to change the “this” keyword binding, or the “ThisBinding” as described in the ECMAScript spec. They do the exact same thing, but they pass parameters into the called function differently. The .call() function takes a dynamic parameter set, and the .apply() function takes an array of parameters. Either way, you can see that ‘func’ is called the same way, with its “this” keyword bound to the newobj object.

In the case where a function is already scoped to an object, the “this” keyword will reference the parent object:

var NewObj = function () {};

NewObj.prototype.alert = function (message) {
    alert('NewObj alert: ' + message);
};

NewObj.prototype.test = function (message) {
    this.alert(message);
};

var newobj = new NewObj();
newobj.test('test'); // alerts NewObj alert: test
newobj.test.call(window, 'test'); // alerts test

In this case, the first newobj.test() is called while using the default binding, which is the instance of NewObj that was created, so when it calls this.alert(), it is calling the object’s prototype.alert() function.

The second time it is called, I forced a rebind to the window object, by using .call(). This causes the normal global alert() function to be the one called, since in this call, “this” is bound to window.

I hope this clears up a common problem for someone. I certainly had a hard time understanding “this” when I first learned JavaScript, but hopefully it makes more sense after seeing a few examples.

Test driven development (TDD) should drive your class design (Part 2 of 2): The right way

Update (9/16/2013): Example source code is now attached, including source for parts 1 and 2.

In the previous post, I proposed a simple example:

You work for Company A, and they want you to write a simple web portal for them. You learn that there is a process in place already that spits out about 30 images as email attachments, and they would much rather see these displayed on a web site. The images will have to be categorized into main, sub, and chart type

In that post, I outlined how one might develop a library for such a site without TDD. Erase that code from your memory. DELETE.

In this post, I will be showing how test driven development can vastly improve the flexibility of the code you write, using the same example. I will be using a 3rd party tool called JustMock from Telerik. I highly recommend at least finding some mocking tool, as this will greatly enhance the TDD process. You can read a previous post for more on the subject of dependency injection, IoC, and mocking. It is through these principles and patterns that TDD becomes a really powerful method for class design. Let’s get started!

Sometimes staring at a blank test class can be rather daunting.

dont-panic-circle

Calm down!

DON’T PANIC!

LET GO!

*SLAP*

Feel better? Me too… I got to slap you!

In all seriousness, think of the test area as your white board. Your API isn’t written yet, but you get to use it already!

What is the most basic thing you need to do? Load charts from somewhere right? What holds things? A container? Perhaps… but, let’s call it a Repository. We know it needs to return an enumerable collection of Chart objects. We also know that something is going to depend on this “Repository” object to load its charts from. Let’s say we haven’t settled on the architecture yet (MVC, WebForms, HTML5 with a WebAPI service). We need to test that SOMETHING can load the charts using a repository just to get started, so let’s call it ChartLoader. I think we have enough to write our first unit test. I typically start by renaming the class and first test method, and inserting my standard AAA comments:

	[TestClass]
    public class when_loading_charts
    {
        [TestMethod]
        public void chart_loader_returns_charts_from_repository()
        {
            // Arrange
            // Act
            // Assert
        }
    }

TDD has a cadence to it. You will:

  1. Write a test.
  2. The you run all tests.
    1. New test fails because the requirement isn’t met yet
  3. Do the simplest thing to make all tests pass again
  4. Refactor
    1. Only after everything passes do you refactor. It may be tempting, but don’t do it earlier! Get a good baseline first.
  5. Repeat for the next requirement

The first test

	[TestMethod]
	public void chart_loader_returns_charts_from_repository()
	{
		// Arrange
		var container = new MockingContainer<ChartLoader>();
		container.Arrange<IChartRepository>(r => r.Charts).Returns(new List<Chart>
		{
			new Chart
			{
				FileName = "file1.png",
				Category = new ChartCategory
				{
					Main = "main",
					Sub = "sub",
					Type = "type"
				}
			}
		});

		// Act
		ChartLoader loader = container.Instance;
		IEnumerable<Chart> result = loader.GetCharts();

		// Assert
		Assert.AreEqual(1, result.Count());
		Assert.AreEqual("file1.png", result.First().FileName);
		Assert.AreEqual("main", result.First().Category.Main);
		Assert.AreEqual("sub", result.First().Category.Sub);
		Assert.AreEqual("type", result.First().Category.Type);
	}

So, we have a test for this fictitious ChartLoader object, and we know it needs to load from a repository, so ChartLoader needs some abstract definition of a repository (IChartRepository), and we know it needs to get charts… IChartRepository.Charts is going to be an IEnumerable, but it’s undefined so far. The Arrange call is essentially setting up a return value from the chart repository, so that when ChartLoader hits it, it will get the list as defined in the .Returns() call. We’ll see that in the next code section. So, the next thing to do is call the method in the ChartLoader to get the charts, and then assert that everything the ChartLoader returned, matched exactly what the repository returned (and you know exactly what it’s going to return, because you mocked it!)

So now there is a test with a bunch of red lines, because nothing is real yet. This is why I love tools like ReSharper, which let me auto generate the classes very quickly. What gets generated:

    public interface IChartRepository
    {
        IEnumerable<Chart> Charts { get; }
    }

    public class ChartLoader
    {
        public IEnumerable<Chart> GetCharts()
        {
            throw new NotImplementedException();
        }
    }

    public class ChartCategory
    {
        public string Type { get; set; }
        public string Main { get; set; }
        public string Sub { get; set; }
    }

    public class Chart
    {
        public ChartCategory Category { get; set; }
        public string FileName { get; set; }
    }

Now, the test will fail, but at least everything compiles. This is where you go to step 4 in the process. Do the simplest thing to make all the tests pass. In this case it’s 1 test, but get in the habit of running all tests… find the keyboard shortcut for doing this and learn it! Optionally, if you’re really into it, you can get a tool that automatically runs your tests like NCrunch

Here, there is a certain pattern that IoC containers work with: Your class constructor should take parameters for all of its dependencies. Here is the implementation of ChartLoader I came up with to get the tests to pass:

    public class ChartLoader
    {
        private readonly IChartRepository _chartRepository;

        public ChartLoader(IChartRepository chartRepository)
        {
            _chartRepository = chartRepository;
        }

        public IEnumerable<Chart> GetCharts()
        {
            return _chartRepository.Charts;
        }
    }

Now typically, you will do whatever refactoring that is necessary, which includes moving classes into appropriate folders and projects, etc, because all of the generated code I’ve shown is at the bottom of the test file. That would be out of the scope of this post, though, and sometimes it’s ok to leave them inline while you’re still writing tests.

This might actually be a good time to create a fake IChartRepository implementation on the front end site and actually give the business something to look at!

Hah! Did you think TDD was slow? How much quicker did we just deliver something to business and get feedback? This is VERY early on, and it is invaluable, because business requirements change when the people using a system get to play with it. You can and should show them something as soon as possible.

Back to TDD. The second test:

We have an object that can get charts, but we still don’t have anything loading from disk. Let’s write another test (because in TDD we always write a test before a feature):
I typically start a new test class when I’m dealing with a new system under test, but for this example, I won’t bother.

        [TestMethod]
        public void chart_repository_returns_charts_from_directory()
        {
            // Arrange
            var container = new MockingContainer<DirectoryChartRepository>();
            container.Arrange<IDirectory>(d => d.GetFiles()).Returns(new List<string>
            {
                "file1.png",
                "file2.png"
            });

            // Act
            DirectoryChartRepository repository = container.Instance;
            IEnumerable<Chart> result = repository.Charts;

            // Assert
            Assert.AreEqual(2, result.Count());
            Assert.AreEqual("file1.png", result.ElementAt(0).FileName);
            Assert.AreEqual("file2.png", result.ElementAt(1).FileName);
        }

Here I just want to prove that charts can load from a directory. Now, what really makes this a special scenario (and why I chose this example) is that there is an inherent dependency on the file system in the requirement: Charts will be loaded off the hard drive. This is about class design and controlling inputs in order to test things properly, though. I don’t want a hard drive to have to spin up in order to run a unit test. Tests should execute in milliseconds and be self contained units. The arrange section of a unit test HAS TO contain all of the dependency mocking, or it is going to be a brittle test that requires too much setup. Furthermore, System.IO.Directory.GetFiles(path) is static and can’t be overridden, so it’s impossible to mock (without a major effort or something that can fiddle with system libraries at runtime).

So, now let’s do some more class generation.

    public interface IDirectory
    {
        IEnumerable<string> GetFiles();
    }

    public class DirectoryChartRepository : IChartRepository
    {
        public IEnumerable<Chart> Charts { get; }
    }

So now everything compiles, but the new test still fails, because the DirectoryChartRepository object doesn’t actually use IDirectory and isn’t building any chart objects from the directory. So we have to do more to get it to pass:

    public class DirectoryChartRepository : IChartRepository
    {
        private readonly IDirectory _directory;

        public DirectoryChartRepository(IDirectory directory)
        {
            _directory = directory;
        }

        public IEnumerable<Chart> Charts
        {
            get
            {
                // TODO: I'm going to need a way to inject the path
                return _directory.GetFiles().Select(f => new Chart
                {
                    FileName = f
                });
            }
        }
    }

Now both tests should pass, and we can move on. How do charts get categories? NEW TEST! Seeing the pattern now? (Good, because I’m going to go faster):

Going faster. The third test:

	[TestMethod]
	public void chart_repository_categorizes_charts_from_categorizer()
	{
		// Arrange
		var container = new MockingContainer<DirectoryChartRepository>();
		container.Arrange<IDirectory>(d => d.GetFiles()).Returns(new List<string>
		{
			"file1.png"
		});

		container.Arrange<IChartCategorizer>(c => c.GetChartCategory(Arg.IsAny<Chart>()))
			.Returns(new ChartCategory
		{
			Main = "main",
			Sub = "sub",
			Type = "type"
		});

		// Act
		DirectoryChartRepository repository = container.Instance;
		IEnumerable<Chart> result = repository.Charts;

		// Assert
		Assert.AreEqual("main", result.ElementAt(0).Category.Main);
		Assert.AreEqual("sub", result.ElementAt(0).Category.Sub);
		Assert.AreEqual("type", result.ElementAt(0).Category.Type);
	}

    public interface IChartCategorizer
    {
        ChartCategory GetChartCategory(Chart chart);
    }

Tests compile but fail again. Add a dependency on IChartCategorizer to the DirectoryChartRepository, and use it. New DirectoryChartRepository class:

    public class DirectoryChartRepository : IChartRepository
    {
        private readonly IDirectory _directory;
        private readonly IChartCategorizer _chartCategorizer;

        public DirectoryChartRepository(IDirectory directory,
            IChartCategorizer chartCategorizer)
        {
            _directory = directory;
            _chartCategorizer = chartCategorizer;
        }

        public IEnumerable<Chart> Charts
        {
            get
            {
                return _directory.GetFiles().Select(f =>
                {
                    var chart = new Chart
                    {
                        FileName = f
                    };
                    chart.Category = _chartCategorizer.GetChartCategory(chart);
                    return chart;
                });
            }
        }
    }

Tests pass. Things are really starting to come together at this point. We still want to load categories from that XML file perhaps, but who’s going to maintain the XML file? What if they want to be able to manage categories themselves? Things are really starting to get going now, and with this class design, to implement any categorization requirements, it’s simply an implementation of IChartCategorizer. XMLChartCategorizer or SQLChartCategorizer? Well for now let’s do DictionaryChartCategorizer since we’re going to be the only ones maintaining the categories for now.

Fourth test:

	[TestMethod]
	public void dictionary_categorizer_loads_categories_from_dictionary()
	{
		// Arrange
		var container = new MockingContainer<DictionaryChartCategorizer>();
		container.Arrange<IChartCategoryDictionaryProvider>(d => d.GetCategories()).Returns(new Dictionary<string, ChartCategory>
		{
			{
				"file1.png",
				new ChartCategory
				{
					Main = "main",
					Sub = "sub",
					Type = "type"
				}
			}
		});

		// Act
		var result = container.Instance.GetChartCategory(new Chart
		{
			FileName = "file1.png"
		});

		// Assert
		Assert.AreEqual("main", result.Main);
		Assert.AreEqual("sub", result.Sub);
		Assert.AreEqual("type", result.Type);
	}

    public interface IChartCategoryDictionaryProvider
    {
        Dictionary<string, ChartCategory> GetCategories();
    }

    public class DictionaryChartCategorizer : IChartCategorizer
    {
        public ChartCategory GetChartCategory(Chart chart)
        {
            throw new NotImplementedException();
        }
    }

Partway through writing the Arrange section, I realize that I need a way to control the dictionary of categories, and this is a good time to make a new IChartCategoryDictionaryProvider object, because I can implement that interface for XML, SQL, a Code Only version, or this mock version! We have a compiling test that fails due to exceptions. Let’s fix that:

    public class DictionaryChartCategorizer : IChartCategorizer
    {
        private readonly IChartCategoryDictionaryProvider _chartCategoryDictionaryProvider;

        public DictionaryChartCategorizer(IChartCategoryDictionaryProvider chartCategoryDictionaryProvider)
        {
            _chartCategoryDictionaryProvider = chartCategoryDictionaryProvider;
        }

        public ChartCategory GetChartCategory(Chart chart)
        {
            var categories = _chartCategoryDictionaryProvider.GetCategories();
            ChartCategory category;
            if (categories.TryGetValue(chart.FileName, out category))
            {
                return category;
            }
            return null;
        }
    }

With that new implementation of DictionaryChartCategorizer, everything passes again. So, we have the basic structure of our API down that satisfies all of the requirements, but STILL no call to System.IO.Directory.GetFiles() and no loading charts from XML? What gives? We’ve reached the point where we need real implementations in order to call this done, but we could easily skip that and write the whole front end website. As noted, we could have done that a long time ago as soon as we had the ChartLoader object.

Now let’s finish this thing out

The test for this is basic, because there’s not much to arrange or assert:

	[TestMethod]
	public void filesystem_directory_does_not_throw_exception()
	{
		// Arrange
		var directory = new FileSystemDirectory("C:\");

		// Act
		var result = directory.GetFiles();

		// Assert
		// Pass if no exceptions
	}

    public class FileSystemDirectory : IDirectory
    {
        private readonly string _path;

        public FileSystemDirectory(string path)
        {
            _path = path;
        }

        public IEnumerable<string> GetFiles()
        {
            return System.IO.Directory.GetFiles(_path);
        }
    }

You’ll notice I didn’t mock anything, because this class doesn’t have a mockable dependency. It goes directly to a static method to get files off the disk, and that’s exactly what we didn’t want polluting our classes making testing them hard. It has to be done at some point, though, and at least we have a single class to handle it and it’s tucked away neatly in an abstraction. As a side note, this opens up the possibility of having a non filesystem directory (store image byte arrays in SQL?), which is a pretty neat concept, and no code would have to change.

Almost done!

	[TestMethod]
	public void xml_categorizer_loads_categories_from_xdoc()
	{
		// Arrange
		var document =
			new XDocument(new XElement("charts",
				new XElement("chart", new XAttribute("maincategory", "main"), new XAttribute("subcategory", "sub"),
					new XAttribute("type", "type"), new XAttribute("filename", "file1.png"))));

		var categorizer = new XmlChartCategorizer(document);

		// Act
		var category = categorizer.GetChartCategory(new Chart
		{
			FileName = "file1.png"
		});

		// Assert
		Assert.AreEqual("main", category.Main);
		Assert.AreEqual("sub", category.Sub);
		Assert.AreEqual("type", category.Type);
	}

    public class XmlChartCategorizer : IChartCategorizer
    {
        private readonly XDocument _document;

        public XmlChartCategorizer(XDocument document)
        {
            _document = document;
        }

        public ChartCategory GetChartCategory(Chart chart)
        {
            var chartElement = _document.Descendants("chart").FirstOrDefault(x => x.Attribute("filename").Value == chart.FileName);
            if (chartElement != null)
            {
                return new ChartCategory
                {
                    Main = chartElement.Attribute("maincategory").Value,
                    Sub = chartElement.Attribute("subcategory").Value,
                    Type = chartElement.Attribute("type").Value
                };
            }
            return null;
        }
    }

That’s it. We have everything we need, and the library has tests for all business functionality. The design is a LOT different, no? You might not see the value in such a design pattern at first, but consider how flexible it is to change. I’ve already outlined some changes that would be very simple, but more than just simple changes, even complex changes are not going to damage the integrity of the rest of the library. Changing the Categorizer implementation to a SQLChartCategorizer does not have anything to do with where the files come from on disk. Files could come from cloud blob storage, and categories could come from an infinite monkey array… the rest of the code won’t care.

If you implement the infinite monkey array, though, I want to see the code.


(Contains 1 attachments.)

Unit testing with mocks

Recently I have really gotten into Test Driven Development (TDD). My first real try at TDD was for a library that I have yet to complete for integrating spriter animations into FlatRedBall. Now I am working on something work related, so I can’t give any specific details as it is proprietary information. I can, however, come up with some contrived examples that may be beneficial to the community regarding Mocking.

There are several different mocking frameworks out there, and I started using Moq first, but I have changed to using Telerik JustMock because it has a less verbose syntax. I may post a “differences between Moq and JustMock” some day, but others have already covered that on the web, so it really isn’t necessary.

I also find great value in dependency injection, so IoC containers are invaluable in my production code; however, something I have also recently learned is that they can be just as invaluable in a unit test. Implementing the dependency injection pattern enables techniques such as inversion of control (IoC), which allow specifying concrete dependencies at runtime for abstract dependencies. That is to say, if class A relies on interface I, and B implements I, class C associates A with B at runtime without either class knowing of the other. Example:

public class Foo
{
    private IWorker _iworker;
    public Foo(IWorker iworker)
    {
        _iworker = iworker;
    }

    public string DoWork()
    {
        return _iworker.DoWork();
    }
}

public interface IWorker
{
    string DoWork();
}

public class Bar : IWorker
{
    public string DoWork()
    {
        return "Bar";
    }
}

We have two classes. Foo which has a dependency on an abstraction (interface IWorker). You can see that Foo doesn’t have any reference to class Bar in this example, and the reverse is true. Bar doesn’t know anything about Foo.

One might use this class in the following manner:

// Manually injecting the dependency through a constructor
var foo = new Foo(new Bar());

// or by Automatically injecting the dependency by setting up an IoC container
var container = new UnityContainer();
container.RegisterType<IWorker, Bar>();

// Typically the below step is done by a dependency resolver which depends on a
// container of some sort, but for a concise example:
Foo foo = container.Resolve<Foo>();

I’ll let the comments explain the code. Suffice it to say that the second pattern is much nicer, because a third class is responsible for coupling all of your dependencies. In MVC, this is typically a BootStrapper static class, but it can be anything that sets the MVC configuration’s global DependencyResolver object.

Why should you use this pattern in your class design? Unit tests! Unit tests! Unit tests!

Example:

[TestMethod]
public void a_dowork_returns_dowork_from_IWorker()
{
    // Arrange
    var container = new MockingContainer(); 
    container.Arrange(i => i.DoWork()).Returns("test");

    // Act 
    Foo foo = container.Instance;
    var result = foo.DoWork();

    // Assert
    Assert.AreEqual("test", result);
}

Mind blown? There’s a lot going on here, but essentially:

Arrange:
The unit test takes advantage of the dependency injection pattern and injects a proxy implementation of the IWorker interface into the Foo object it maintains inside the MockingContainer. The call to Arrange is saying that this proxy object should return “test” for any calls to its DoWork function. So we have an object that implements IWorker (it has nothing to do with class Bar), and we inject that into the instance of Foo automatically with the container.

Act:
We then call DoWork on the instance of Foo that the container provides us (which has the dependency injected already)

Assert:
We assert that the result returned from foo.DoWork() matches what the proxy DoWork was returning.

This is a simple contrived example, but it illustrates how IoC containers work in tandem with mocking very well. I hope someone finds this useful!

Using VirtualBox to run the Microsoft Virtual PC test images

At some point with every new project, we have to do multiple browser testing to check for compatibility. The major browser types are usually covered by the team, and we all usually have at least Firefox, Chrome, and one flavor of IE (IE7 or IE8 w/ some having IE9 access at home or via an external VM). What we don’t always have are reliable IE6 installs to test with. Microsoft makes Virtual PC (.vhd) images available for free that expire every quarter (You can find them here). They also make Virtual PC 2007 available as a free download, which works great for XP users. They have their XP mode for those of us that run Windows 7 pro or ultimate, but for those of us who have a lower version of Windows (Windows 7 Home Premium and below), at first glance it would appear that we are out of luck.

VirtualBox is a free virtualization tool built by the folks at Oracle. You can setup a virtual machine in it just like you can in Virtual PC 2007, and they both support the VHD file type, which you will need to convert to a VDI file if you want to load more than one of the free images from MS because of some ID in the file that VirtualBox checks. That article is written for a Linux system, but if you get the windows binary for qemu, it should work fine. For the purposes of this article, I am going to assume you either didn’t need to run more than 1 image (like me), or you already can figure that part out for yourself.

The kicker to this whole thing is that you can just use the VHD image and all seems to work until you boot up. You get the annoying message from MS saying you need to validate your copy of Windows within 3 days or the men in black suits will come beating down your door. The best part of this is that if you reboot, you can’t get past this step so you have to do this all at once without rebooting! Windows sees that it was unable to activate and thus prevents you from installing network drivers. Awesome… I need to install my network drivers so I can activate windows, but I need to activate windows before installing the network drivers. Most people (as was I) are thinking “You just have to install the guest operating system tools to get the network drivers,” but that did not work for me. I also did the handy little trick to extract the drivers from the guest tools by running their something-x86.exe /extract /D=C:Drivers (I tried so many times that I memorized everything but the exe itself since you can tab correct that). The drivers simply are not included no matter what article one might read about  them being moved into an exe archive so as to save space in the ISO image, which makes no sense anyway since the exe is in the ISO anyway.

Long story short (still long), the only way to get the network card working is to install the drivers, but the only way to get the drivers on the virtual box is to put them on an ISO image so you can mount that via VirtualBox. Here are the XP Drivers for the AMD NIC that were missing from the guest OS tools ISO image included with VirtualBox.

  1. Boot the VHD image for the first time
  2. Cancel all prompts to activate and install new hardware
  3. Mount this ISO image via VirtualBox’s device dropdown
  4. Update the drivers from within the Device Manager for the Ethernet Adapter
  5. Activate your free XP IE6/7/8 testing image
  6. Repeat this next quarter (half the reason I wrote this article)

I hope this helps someone and saves them the hassle of trying 1000 times to find the NIC drivers before doing it themselves. I know this will become my new reference every quarter when my VPC image expires!

Bust that cache!

<shamelessplug>I don’t know if I have shared this, but I work for Caesars Entertainment doing web development. Go make a hotel reservation and you’ll be using everything that my work has been for the last 2 years.</shamelessplug>

Anyway, as web development goes, the site is very javascript heavy, and we have some core functionality existing in a javascript file linked via a

<script type="text/javascript" language="javascript" src="blahblah.js"></script>

tag. Regardless of the specifics, certain browsers end up being a pain when it comes to caching. For instance, we make a change to blahblah.js, but the browser has an old version of it cached for speedy loading and it ends up not picking up the change. It takes some time for the browser to get around to updating, and every browser is different, so I did some searching.

I found a site (http://davidwalsh.name/prevent-cache) which basically says to do this:

<script type="text/javascript" language="javascript" src="blahblah.js?(insert some dynamic number based on current time here)"></script>

This effectively makes the browser see a new reference for the javascript file every time it loads the page… not completely ideal for all situations. Namely, browser cache can be a very helpful thing to improve site performance… we like browser cache, but we need to make it work for us and not against us.

The simple solution is:

<script type="text/javascript" language="javascript" src="blahblah.js?(insert static version # here)"></script>

The version # is actually loaded via a web.config file, but that’s neither here nor there… what is important is that every time we want the browser to reload the cached js file, we simply increment that version # and the browser doesn’t have that src reference cached, so it has to download it.

Cache busted!