Posted by & filed under Uncategorized.

After a couple of years in the dark, I’m attending a couple of conferences this year. First up is Microsofts Danish Developer Conference. I haven’t attended DDC before, but from the program the last two years, the conference looks like a lot of fun. I really like the GOTO conferences, but sometimes a conference just needs to be short, precise and not necessarily focus on what’s hot in three years, but what’s hot right now. I still haven’t decided 100 % on what sessions to attend, but my experience from multiple partipations at Goto tells me, that you gotta be prepared before showing up at a conference. My program looks like this at the moments:

09:00-10.15

Not much to choose from here. The keynote abstract doesn’t reveal much. Let’s wait and see.

10:30-11.45

Even though I would like to brush up on my Windows Phone developer skills, I think that I will attend Mads Kristensens session “Beyond Visual Studio 2012. What’s Coming for Web Developers”. I’m working with web development both professionally and personally and can’t what to see what new features will be included in the next versions of Visual Studio.

12:00-12:30

There’s a TFS session during lunch that I may attend. I’ve worked with TFS in the past and even though it was an awful experience, it could be fun to see if Microsoft improved anything since 2007.

12:45-14:00

The “Get the newest and sharpest Visual Studio 2012 and ReSharper Tricks” sounds like fun, but I really want to hear Gudmundur talk about single page apps. I’m working as a tech lead on a single page app on a daily basis and would love to hear what other have done to succeed in this area.

14:15-15.30

I’m torn. 4 exciting sessions in this slot. I’m doing Windows Phone apps privately and would like to hear about the possibilities of moving them to Windows 8. The “Async and Reactive Extensions” is probably the obvious choice related to my job at eBay, though.

15:45-17:00

No doubt about what to do in this slot. The “Bigger, Faster, Stronger: Optimizing ASP.NET 4 and 4.5 Applications” sounds like a perfect fit for both my position at eBay as well as my personal interest in performance optimization.

17:15-18:00

The program doesn’t reveal anything about the closing keynotes. If anyone have more information, please let me know.

Share this post:

Share to Google Plus

Posted by & filed under Uncategorized.

Time for another update on my progress on making HippoValidator the best website validator out there. I just pushed a major update including a lot of features and fixes. The most important ones are listed below.

JSHint

HippoValidator already validated some aspects of the JavaScript on your site. But a validator dedicated to writing good Javascript were always missing. Until now. JSHint will now validate all script tags on your site.

CSSLint

Like JavaScript, HippoValidator also looks at your stylesheets. Both the W3C style validator as well as the Accessibility validator look at your stylesheets, but focus more on the standard and less on writing quality code. Luckily CSSLint now runs as part of the scan, helping you avoid common mistakes when writing CSS.

Settings page

While HippoValidator runs a set of quality recognized rules, you may want to disable certain rules or maybe entire validators from your scheduled scans. This is now possible through the new Settings pages, which is accessed by clicking the small edit-icon next to your schedules. The settings page looks like this:

settings

Optimize images

The validators always focused a lot on telling you what’s wrong and no so much on how to fix it. My vision is to provide you with both links and tools to help you fix the problems found by HippoValidator. A good example of this is the new optimize image fix, which is available if the performance validator shows the “Optimize Images” error. When showed and the user clicks the error, an extended explanation is shown like this:

optimizeimages

HippoValidator automatically shows you the images which needs optimization and when clicking the “Optimize image” link, an optimized image is saved to you file system. You can replace the existing file on your website with the optimized one and gain a small performance boost.

Open source

What started as a small task, ended up taking a lot of time during this release: open sourcing some of the internals of HippoValidator. So far I’ve open sourced 4 of the .NET clients I’ve written for different validator services: JSHint, CSSLint, AChecker Accessibility Validator, W3C CSS Validator. You can find the projects at the HippoValidator organization at GitHub here: https://github.com/HippoValidator. I plan to open source even more and really appreciate YOUR help using and extending these validators.

What’s next?

I still have a lot of ideas for new features and improvements. This is what I’m planning to do next:

  • More to Azure.
  • More fixes
  • Email alerts
  • Migrate everything to Bootstrap

Please add your ideas and bug reports to the HippoValidator UserVoice: http://hippovalidator.uservoice.com/forums/105829-general.

Share this post:

Share to Google Plus

Posted by & filed under Coding.

Since starting web development about 4 years ago, I’ve been deploying every commit to a webserver from various build servers. Having an up-to-date webserver with the recent version of your code at all times makes it possible to do early testing on an environment other than your own machine. Since switching from SVN to Git, doing feature branches suddenly became possible (yes, I know about branches in SVN, but it was just too damn hard and slow to work with). Let’s face it; feature branches always caused problems on build servers, because you would have to manually add new project configurations every time a new feature branch was created. With TeamCity 7.1, feature branches are now a well-supported part of the build process, giving you some exciting new possibilities.

At eBay we use Git Flow and setup our build server to deploy every commit on develop to our test environment and every commit on master to our production environment. We have been using feature branches as well, but never really deployed them anywhere. I decided to do something about this, making it possible to do QA on a different environment than localhost. The problem with feature branches is that they, unlike develop and master, are dynamic branches, which are created and removed when needed. Luckily TeamCity now supports dynamic branches as well. The idea here was to create a new website every time a new feature branch is created. For instance, when creating a new feature branch named “feature1″, I would like to be able to access the latest code on this branch by visiting http://feature1.testenvironment/, where testenvironment is the local name of our QA webserver.

I spent some time figuring out how to do it and looked at both various TeamCity features as well as Git hooks. I ended up implementing the website creation using a simple PowerShell script, executed by TeamCity, each time a build is run. For deployment we already use Web Deploy, as this is the obvious choice. My build steps looks like this (simplified):

  1. Build code
  2. Create website
  3. Deploy website

Building the code is simple using MSBuild. To create the website I added a new step like this:

create_iis_application

For those of you who don’t like copy/pasting from an image, the script source is available in this Gist. The script creates a remote connection to a webserver. You obvious need to change the hostname and user credentials to match a server at your site with IIS installed. On the server, New-Item is called with parameters expected by that command. Look at the Gist for details. Finally the AppPool is set using the Set-ItemProperty command. Notice the use of the teamcity parameter named %teamcity.build.branch%, which is pretty much where the magic happens. This parameter is assigned the name of the Git feature branch. Very nice!

You may think: “Doesn’t this creates the website every time the project is build?”. Actually it doesn’t. On subsequent runs, the PowerShell script fails. As default TeamCity won’t fail if a PowerShell script fails so I decided to live with this.

The final stage is to deploy the website to our newly created website using Web Deploy. I won’t go into detail on how Web Deploy works (maybe another post, if anyone is interested?). In short the deployment step looks like this:

deploy_webapplication

This build step uses MSBuild and Web Deploy to publish the newly build code to the website created in the build step above. Again I use the %teamcity.build.branch% parameters to tell the IIS what website to publish to.

Share this post:

Share to Google Plus

Posted by & filed under Uncategorized.

Some positive Twitter feedback on my website validator HippoValidator and release of the great Web Developer Checklist, motivated me to do what turned out as one of the largest updates since introducing the website:

What’s new?

I did multiple things in the recent version.

Performance

Working with HippoValidator.com always felt kind of slow. Probably because it was implemented during diaper change and hosted on a free micro instance at Amazon. Upgrading to a paid plan really kicks some serious performance ass. Also I have been working a lot with RavenDB since implementing the site, which allowed me to do multiple Raven related optimizations. Finally RavenDB is upgraded from the one year old version to the new and shiny 2.0. Performance really improved in RavenDB in the most recent version.

SEO Validator

I always wanted to do a SEO validator, why this was the first I decided to implement. I got my inspiration from various other SEO validators, personal experience and the great Search Engine Optimization Starter Guide by Google. The new validator consists of 17 custom rules as we speak, but I have a lot more to implement.

Mobile Validator

Mobile just keeps getting more and more important. That’s why you have to ensure that your site looks good on mobile platforms these days. I really wanted to integrate the mobileOK validator from W3C, but I couldn’t find any webservice to use. I decided not to let that stop me and started to implement my own. In this version only three rules have been implemented, but again I have a lot of ideas to improve the validator with more rules.

Stability Issues

The previous version smelled a bit like beta. I’ve done a lot to stabilize the site, adding a lot of logging, bug fixes and a lot of other stuff.

Please help me and give the new version a try: Validate your website.



Share this post:

Share to Google Plus

Posted by & filed under Unit testing.

One thing using Moq always bugged me. When needing to verify some method call, Moq provides a Verify-metod on the Mock object:

So, what’s wrong with this piece of code? In fact nothing (if you ask me). The “problem” is the error message if the test fails:

verify_error

Something fails! Moq is in fact pretty decent when it comes to error messages (compared to other mocking frameworks at least). Still, I don’t think the error is obvious here. It takes some time to spot, that the first parameter of the AMethodCall-method have a spelling mistake. What we really wanted here is to do an assert on each parameter using NUnit.

Even though callbacks in Moq isn’t ment to fix this, it solves the problem quite well. One might argue, that we compromise a bit with AAA, though. Our test using callbacks look like this:

A bit more complex, but our error message now tells us exactly what’s wrong:

callback_error

Share this post:

Share to Google Plus

Posted by & filed under Unit testing.

A couple of weeks ago, I decided to switch from CoffeeScript to TypeScript on the project I’m working on at eBay. In my opinion, TypeScript makes a lot of a lot more sense when working with web applications in .NET. These are some of the advantages I’ve identified so far:

  • Great tool support. The Visual Studio add-in for TypeScript offers IntelliSense, which I never really found a good solution for with CoffeeScript.
  • Strongly typed: TypeScript lets you strongly typed parameters and field.
  • Modules and classes. Like CoffeeScript, TypeScript makes it a lot easier to define namespaces and classes. I really like the TypeScript syntax better than CoffeeScript.

In order for you to try out the examples in this blog post, you need to install TypeScript, Web Essentials and Chutzpah (install through Visual Studio Extensions and Updates).

Porting the existing CoffeeScript files is easy. Grab the existing JavaScript, generated by your CoffeeScript compiler. Paste the content into a new TypeScript file and worry about using the nice features of TypeScript later. I use Web Essentials to edit my TypeScript files and went through all the options for this to work out. Here is a screenshot of my settings:


wesettings

I changed the Keep comments to True, in order for my unit tests to work – more about this later. Also Compile TypeScript on save is enabled, because TypeScript as default only compiles the JavaScript on build.

Here’s a simple example of a TypeScript file called generator.ts:

module ThomasArdal {
    export class StringGenerator {
        generate(input: string) {
            return input + ": Hello World";
        }
    }
}

This is probably not the most advanced script you have ever seen (I hope), but it illustrates the main features in TypeScript: modules, classes, and strongly typed parameters. The generator method is called by running the following piece of TypeScript:

var gen = new ThomasArdal.StringGenerator();
console.log(gen.generate("Hi"));

Now for the purpose of this blog post: the unit test. We are using the excellent JavaScript unit test runner Chutzpah to execute our tests both from within Visual Studio and our TeamCity build server. The unit tests are written using QUnit, but if you prefer Jasmine, Chutzpah supports that as well. To install QUnit in your test project, run the following NuGet command:

Install-Package QUnit-MVC

The qunit.js script is added to your test project in a Scripts root folder. You can change the location of the QUnit script, but if you do, be prepared for some manual work each time you update QUnit to a new version.

Add a new TypeScript file named generator.tests.ts.

///<reference path="qunit-1.10.d.ts"/>
///<reference path="generator.ts"/>

QUnit.module("generator.ts tests");

test("Can generate string", function () {
    // Arrange
    var gen = new ThomasArdal.StringGenerator();

    // Act
    var result = gen.generate("Hi");

    // Assert
    equal(result, "Hi: Hello World", "Result should be concat of input and Hello World");
});

Besides a reference to the script we are about to test (generator.ts), I reference a file named qunit-1.10.d.ts. Normally you would reference qunit.js, but in order to get IntelliSense in TypeScript, you need to reference a definition file (d.ts). Luckily Boris Yankov did a great job extracting definition files from various JavaScript frameworks in this GitHub project. Another thing to notice here, is the module-function call. Under normal circumstances, you simply call this function directly, but because “module” is a keyword in TypeScript, you need to use the QUnit object instead. Writing the QUnit test is straight forward with an arrange, act and assert.

That’s it! Testing TypeScript with TypeScript is easy. Right click your test file and run your test using Chutzpah:

runtest

Share this post:

Share to Google Plus

Posted by & filed under Uncategorized.

Another year of great experiences has come to pass. Just like last year, so much has happened during the last twelve months. Indeed, this year I had some events in my life which definitely dampened my personal projects. In January I was no-moted to Tech Lead at eBay. During the summer my father in law was diagnosed with intestinal disease, and at the end of the year, my wife and I had our second child, a beautiful daughter. Just like 2011, having less time forced me to focus on important and meaningful projects.


Chrome extensions
I spent a lot of time in 2011 playing with extensions for Google Chrome. In 2012 I came to the conclusion that even though coding JavaScript is fun, developing Chrome extensions isn’t monetizable. I spent a little time developing a DMI weather extension with a former colleague and also found time to combine all of my existing extensions into a single extension simply named gInfinity.


thomasardal.com
17 blog posts were published on thomasardal.com compared to 27 posts last year. I still love blogging, but I just don’t have a lot of time to spare. I’m still pretty happy with my effort in this area, though.


Hackernight
Together with my former colleague Troels, I founded the group named Hackernight. The idea behind Hackernight is simply about a bunch of guys getting together to code in their spare time, with projects one night a month. The group is still very active even though I haven’t participated in the last 4 meetings. It’s amazing what you can get done during 6 hours of free coding.


HippoValidator.com
My key focus from last year was HippoValidator.com, and I worked a whole lot on this site during my participation in Hackernight. The site is live with a killer design and some nice new features. The next step is to build a monetizable part of the project.


Mobile development
Mobile development always interested me, but I never really had a job which required me to write mobile applications, and the few attempts I had tried something on my own didn’t turn out as I’d hoped. 2012 has seen sort of a breakthrough for me in this area. My co-worker Casper and I decided to start implementing apps for Windows Phone under the name Limited Apps. During H2 we implemented 9 Windows Phone rating apps all based on the same backend, a fruit and vegetables app, a video poker app and an app helping car buyers to spot scammers (together with the website kmtjek.dk). In addition Casper did a Windows 8 version of one of our rating apps and I did one for Android. Implementing all these apps have probably been the biggest learning experience for me this year.


MSBuildShellExtension
My open source MSBuild shell extension from back in the days got a major update, primarily driven by Rami, the talented developer on the project.


NuGet Package Visualizer
One of my last projects of 2012 has been the NuGet Package Visualizer. NuGet comes with its own visual representation of a packages.config file, but I need one able to show me when new packages are available. The project resulted in a small console application able to generate a DGML file showing your NuGet references across a project or solution.

Share this post:

Share to Google Plus

Posted by & filed under Coding.

I had a fun task a couple of weeks ago, simplifying some code that another dude wrote. It’s always more fun to optimize the hell out of other people’s code, right? :) The problem code was pretty much a proof of concept and no considerations about good or bad design had gone into writing it. The problem solved by the code written was basically a LINQ-like expression, using the excellent ElasticSearch .NET client NEST. The syntax is a bit weird at first, but after having used the API for a while, I’ve decided to like it. Back to the code, this is a snippet of the code handed to me:

var results = _elasticClient.Search<CarSearchable>(
    s =>
        {
            var mustQueries = new List<Action<FilterDescriptor<CarSearchable>>>();
            if (registrationYearFrom.HasValue || registrationYearTo.HasValue)
            {
                mustQueries.Add(
                    mq => mq.Range(
                        r =>
                            {
                                r.OnField(x => x.RegistrationDate);
                                if (registrationYearFrom.HasValue)
                                {
                                    r.From(registrationYearFrom.Value.ToString());
                                }

                                if (registrationYearTo.HasValue)
                                {
                                    r.To(registrationYearTo.Value.ToString());
                                }
                            }));
            }

            if (carTypeId.HasValue)
            {
                mustQueries.Add(mq => mq.Term(x => x.CarTypeId, carTypeId.ToString()));
            }

            if (!string.IsNullOrWhiteSpace(freetextQuery))
            {
                mustQueries.Add(
                    mq =>
                    mq.Query(
                        query =>
                        query.Text(
                            txt =>
                            txt.OnField(f => f.FreeText).QueryString(freetextQuery).Operator(Operator.and))));
            }

            s.Filter(f => f.Bool(b => b.Must(mustQueries.ToArray())));
            return s;
        });

Just a quick explanation of what’s going on here. I’m doing a search on ElasticSearch with a range filter, a term and a full text search. Those of you who have ever wrote queries against Solr or Lucene probably understand exactly what is going on here, but for you other guys, you’ll just see this as your standard LINQ query against some database.

Time for some refactoring. The first step was to get rid of that nasty code block adding the range filter. The refactoring tools in R# quickly transformed the code into something much cleaner:

var results = _elasticClient.Search<CarSearchable>(
    s =>
        {
            var mustQueries = new List<Action<FilterDescriptor<CarSearchable>>>();
            var range = Range(registrationYearFrom, registrationYearTo, x => x.RegistrationDate);
            if (range != null)
            {
                mustQueries.Add(range);
            }

            if (carTypeId.HasValue)
            {
                mustQueries.Add(mq => mq.Term(x => x.CarTypeId, carTypeId.ToString()));
            }

            if (!string.IsNullOrWhiteSpace(freetextQuery))
            {
                mustQueries.Add(
                    mq =>
                    mq.Query(
                        query =>
                        query.Text(
                            txt =>
                            txt.OnField(f => f.FreeText).QueryString(freetextQuery).Operator(Operator.and))));
            }

            s.Filter(f => f.Bool(b => b.Must(mustQueries.ToArray())));
            return s;
        });

I’ve cheated a bit, because most of the code has been extracted to a new method. Let’s look at that later. First of all it bugs me that the code is still 30 lines long and all I want to do is add three filters. The problem here is all the null checking, which makes what should be a simple code very hard to look at. Monads to the rescue! Using monads, the ugly if statements can be written in a much nicer way:

var results = _elasticClient.Search<CarSearchable>(
    s =>
        {
            var mustQueries = new List<Action<FilterDescriptor<CarSearchable>>>();
            Range(registrationYearFrom, registrationYearTo, x => x.RegistrationDate).Do(mustQueries.Add);
            carTypeId.Do(x => mustQueries.Add(mq => mq.Term(cs => cs.CarTypeId, carTypeId.ToString())));
            freetextQuery.If(x => !string.IsNullOrWhiteSpace(x))
                         .Do(
                             x =>
                             mustQueries.Add(
                                 mq =>
                                 mq.Query(
                                     query =>
                                     query.Text(
                                         txt =>
                                         txt.OnField(f => f.FreeText).QueryString(freetextQuery).Operator(Operator.and)))));

            s.Filter(f => f.Bool(b => b.Must(mustQueries.ToArray())));
            return s;
        });

Rather than checking the input values for null, I use the cool Do extension-method in Monads, which executes the given delegate, if the input value is not null. freetextQuery is a string and I want to check for both null and empty string before adding the query. The Do-method only checks for null, but luckily Monads provides us with an If-method, making it possible to provide an expression evaluating to true or false just as an ordinary if-construct. I use a lot of lines on the free text query and maybe I could have squeezed it down to fewer lines, but I’m actually pretty satisfied with the code now. Remember the extracted method? Well, that bastard is still pretty nasty:

private Action<FilterDescriptor<CarSearchable>> Range(int? from, int? to, Expression<Func<CarSearchable, object>> field)
{
    if (from.HasValue || to.HasValue)
    {
        return mq => mq.Range(
            r =>
                {
                    r.OnField(field);
                    if (from.HasValue)
                    {
                        r.From(from.Value.ToString());
                    }

                    if (to.HasValue)
                    {
                        r.To(to.Value.ToString());
                    }
                });
    }

    return null;
}

Doing a bit of Monads magic simplifies the two if statements:

private Action<FilterDescriptor<CarSearchable>> Range(int? from, int? to, Expression<Func<CarSearchable, object>> field)
{
    if (from.HasValue || to.HasValue)
    {
        return mq => mq.Range(
            r =>
                {
                    r.OnField(field);
                    from.Do(x => r.From(x.Value.ToString()));
                    to.Do(x => r.To(x.Value.ToString()));
                });
    }

    return null;
}

It’s probably a matter of taste whether you like the Monads extension methods or not. I’ve got to admit: I love it! Any ideas for improvement?

Share this post:

Share to Google Plus

Posted by & filed under Uncategorized.

Nine months ago, I wrote a couple of blog posts that were a bit different from what I usually write. In the meantime I have received good feedback on the posts and therefore decided to write this follow-up. So here it goes: 5 more tips to optimize your time.

Organize your cooking

One thing I won’t compromise on is making tasty and healthy food myself. I know that a lot of time could be saved by buying prefabricated food for me and my family, but I simply don’t do it. Pretty much all of our food is made from scratch, which can quickly become a time robber. To be able to produce great homemade food without using up multiple hours every day, I practice three things:

  1. Cook for multiple days: When doing a dish, make sure to prepare enough food for two or even three days. Most food tastes just as good the second day.
  2. Cook for your freezer: My freezer is always filled with partial made ingredients like tomato sauce and meat balls. I make 3 liters of tomato sauce once in a while using this recipe (in Danish). I also make both boiled and fried meat balls using my favorite kitchen gadget, the Meat Baller.
  3. Freeze uneaten food: Always freeze leftovers (not the food you’ve already put on your plate but couldn’t eat, but the uneaten food from your pans and pots). Once in a while we eat stuff from the freezer for the entire week. Someone always wrinkle their nose when told this, but remember this is well-prepared and delicious food and not a machined pizza.

Work from home or work on your way to work

When I talk to some of my friends living in bigger cities or other countries I feel gifted. I “only” use about an hour to go to work every day. You may use more than that, but no matter if you’re using 30 minutes or 3 hours a day, you could probably use that time for something else other than transport. When working from home I save 1 hour of transport and because I usually eat my lunch at home while working in front of the computer, working from home gives me around 1½ hours extra each day. Sometimes this time ends up in my employer’s wallet, and sometimes I stop early and do personal stuff if I gain any hours.

Another approach is to use public transportation instead of driving to work yourself. Even though it’s not comfy to work with a laptop on the bus, it’s amazing what you can achieve during a 45 minutes bus ride.

Listen and even watch shows and movies on double speed

A lot of people laughed at me during the last couple of years when I told them about listening to podcasts and watching shows on double speed. I first got introduced to listening to podcasts on double speed in a great podcast for entrepreneurs called Startups For The Rest Of Us. Please don’t laugh. Try it and I can almost promise you that you will never listen to slow motion (1x) again. After falling in love with listening to podcasts in double speed, I started wondering if the idea could be transferred to other platforms like television. If you really want more time, simply don’t watch TV at all, but if you like to catch a numbers of weekly shows like me, night after night quickly disappears in front of the TV. Watching movies and shows on double speed really didn’t word for me, but I found out that speeding up a show to 1.5x or maybe even 1.6x speed makes it possible to understand what’s going on and still be entertaining. You’d probably don’t want to do this with your favorite shows like Dexter and Breaking Bad, but slow-paced shows only get better when watching them on 1.5x speed. Watching your shows like this means that you can catch a 50 minute show in about 30 minutes.

Automate repeating tasks

Before having children I never really thought too much about how I used my spare time and night after night quickly disappeared without any visible results. I didn’t see anything wrong in using time on manual tasks which could have been automated. Today I try automating as much as possible. I could probably automate even more, but this is what I’ve done so far:

  1. Automatic backup: Once in a while I did a manual backup by copying files to an external hard drive. A lot of people use their NAS for backup, but having a dedicated and always-on server in the house always made a NAS redundant for me and my family. Backing up files is boring and you can easily forget to do it on a regular basis. I signed up for automated backup in the cloud at Mozy a couple of years ago and this year I changed to Backblaze which offers unlimited space. All I had to do was to install their client and the software automatically backs up my entire PC. Simple, easy, and time saving.
  2. Automatic picture synchronization: Another task that I would do on a regular basis was to copy files from my digital camera to my PC. We take a lot of pictures of the kids and therefore need to empty the memory card quite often. I bought an Eye-Fi SD Card two years ago and it has become one of the three loves of my life. The Eye-Fi card slips into any SD port (in this case my camera) and automatically syncs the pictures on the phone with my PC through Wi-Fi. That’s right! That small card contains not only 4GB of space but also a Wi-Fi chip. When I get near my wireless network, the pictures are automatically copied to my PC, which again is backed up with Backblaze. It doesn’t get any easier than that.

Buy a robot (or two)

Let’s admit it. Physical work isn’t fun for nerds like me. Mowing the lawn or vacuuming is some of the most boring stuff I can come up with. Being the man of the house, I’m responsible for lawn mowing, which I why I bought that robot first. Unfortunately I ended up buying a robot with a defective battery, which took a long time to discover. Luckily the robot now works like a charm and runs every day. When my wife got pregnant in the spring, she was ordered not to vacuum and we got ourselves a nice vacuum robot from E.ziclean. People typically go for the Roomba 581, but I got the E.ziclean for half the usual price and the machine actually runs pretty good. I can’t stress this is enough: robots are a great way for you to shift more focus away from those weekly boring tasks. I’m looking for more robots, but can’t really decide on what to automate next. Any ideas would be appreciated.

Share this post:

Share to Google Plus

Posted by & filed under Unit testing.

I recently attended a course organized by Mark Seemann at my workplace. Among other topics, the course involved advanced usage of AutoFixture, a framework that I’ve loved using for a couple of years now. AutoFixture always did a good job of helping to create dummy data for my unit tests, but one thing always bugged me. In pretty much all my tests, I’d really want to write this:

var fixture = new Fixture();
var model = fixture.CreateAnonymous<MyModel>();

but always ended up writing something like this:

var fixture = new Fixture();
var model =
    fixture
        .Build<MyModel>()
        .Without(x => x.Id)
        .CreateAnonymous();

So what’s the difference between the two code samples? In the first sample, I simply tell AutoFixture to create a new instance of MyModel with generated values for all public properties. In the second sample, a new instance is created with all public properties with generated values besides the Id-property. The above sample is inspired by an integration test I’ve written of the backend for a couple of Windows Phone apps created together with Casper Skydt. The idea here is to generate a model containing random values, besides the Id-property, which is generated by an Embedded RavenDB on insert. Letting AutoFixture generate a random value for the Id-property makes RavenDB fail because I instructed RavenDB to assign primary keys.

I typically solved the above problem with private help-methods generating MyModel instances with AutoFixture, but the whole idea with the simplicity and easy of creating new objects with AutoFixture, sort of disappears when starting to create test helpers to create test-data.

Mark showed a nice feature of AutoFixture, which is actually able to fix problems like this (and a lot more): Customizations. In fact customizations for AutoFixture is implementing types of the ISpecimenBuilder interface. A specimen builder is sort of the backbone of AutoFixtures algorithms for generating random values for different types of properties. Lucklily the AutoFixture folks added the ability to add custom specimen builders. In my case, I want AutoFixture to generate a new instance of the MyModel type without an assigned value to the Id-property. In fact, I want AutoFixture to never assign values to properties named Id and of type string. This behavior can be implemented as a customization like this:

namespace ThomasArdal.SpecimenBuilders
{
    public class NoIdSpecimenBuilder : ISpecimenBuilder
    {
        public object Create(object request, ISpecimenContext context)
        {
            var propertyInfo = request as PropertyInfo;
            if (propertyInfo != null &&
                propertyInfo.Name.Equals("Id") && 
                propertyInfo.PropertyType == typeof(string))
            {
                return new OmitSpecimen();
            }

            return new NoSpecimen(request);
        }
    }
}

My customization for AutoFixture implements the ISpecimenBuilder interface and thereby overrides the Create-method. The parameters send to the Create-method are a bit of a secret. For each property which needs a random value, AutoFixture invokes the Create method with a PropertyInfo instance. On the PropertyInfo we can use standard reflection to check if the current property needing a value is of type string and has a name equals “Id”. In this case I return a new OmitSpecimen, which tells AutoFixture not to set the Id property. Otherwise I return a new NoSpecimen, which tells AutoFixture that this specimen builder didn’t assign a value to the property.

Specimen builders need to be registered manually. When done, our code sample looks like this:

var fixture = new Fixture();
fixture.Customizations.Add(new NoIdSpecimenBuilder());
var model = fixture.CreateAnonymous<MyModel>();

Nice and clean! As indicated earlier, I don’t really like the object parameter send to the Create-method on specimen builders. I think that a generic interface making it possible to specify a subclass of ISpecimenBuilder<PropertyInfo> would be a lot cleaner and make it possible to strongly type the request parameter of the Create-method.

Share this post:

Share to Google Plus