Inspired by my old colleague Mookid, I want to also share what I’ve been working on this year. It has been a crazy and busy year. Even though my wife and I had a son last year, I’ve coded more than ever. Having a baby forces you to focus your time and energy.

Now for the retrospect, ordered by date, describing what I’ve been working on throughout the year.

thomasardal.com
My new year’s resolution last year, was to start blogging. I wrote my very first blog post on the 2nd of January this year under the title, performancedude.com. I blogged a lot during the first few months about performance optimizing web applications, but my passion for blogging expanded to include other subjects like unit testing. Around June, I decided to switch from my performancedude alias, to start blogging on thomasardal.com. In total, I’ve written 27 blog posts this year. I probably won’t blog as much next year, but I will definitely try to write a post once in a while.

MSBuild Shell Extension
January started the year of great. I was lucky to be contacted by a very talented developer, Rami, who wanted to help shine up my 5-year-old power tool for MSBuild, named MSBuild Shell Extension. MSBuild SE is, as the name proposed, a shell extension for running MSBuild scripts from Explorer, Total Commander or similar. I hadn’t really touched the tool for years, which is why I was happy that someone wanted to take over. Before Rami joined the project, the context menu showed from MSBuild SE was 100 % static, but configurable through a config app installed alongside the build runner. When Rami finished, the context menu was generated dynamically with the MSBuild targets from the right-clicked build-file. Rami did 90 % of the worked and I did all I could to help him finish. Great work, Rami! Our work paid off in the end and the tool was downloaded more than 2,000 times. We also got mentioned in Scott Hanselman’s 2011 Ultimate Developer and Power Users Tool List for Windows!

HippoFocus
While still employed by Trifork, I decided to look more into doing extensions for Google Chrome at one of the companies two annual Hackathons. My first real contribution to the community was HippoFocus, a tool to help you set correct focus points when visiting your favorite websites. This is not rocket science. Even though the extension didn’t really reach the masses, I still think that it is one of the most useful extensions I have implemented.

HippoTab
Why I chose the “Hippo”-prefix once more I can’t really tell you, but shortly after releasing HippoFocus, I did HippoTab. HippoTab automatically tabs when you reach the max length of any input field in a html form. Again not rocket science, but it was fun to implement and my JavaScript skills definitely improved.

eBay
Ok, maybe I didn’t invent this one. This story is about my switch from Trifork to eBay in March of 2011. I had worked at Trifork for 3½ years and wanted to try something new where I was able to focus on my .NET web developing skills. Luckily, I was contacted by eBay, who searched for a talented .NET developer (that’s me :) ). I worked at one of eBay’s Danish sites, named bilbasen.dk, for the first couple of months. It was a great learning experience for me, so naturally I was a bit sad when the company decided to split our team in half. My new team was moved to a new project named DealerHub. DealerHub is the nextgeneration application for Danish car-sellers. The project turned out to be an even better learning experience for me because I was given the freedom to design and implement a kick-ass system using multiple buzz-word enabled techs like KnokcoutJS, ASP.NET MVC 3 and RavenDB. Love it!

HippoLink
In the never-ending line of Hippo* Extension for Google Chrome, HippoLink was released. The idea was to convert unclickable URL’s on WebPages to anchor tags. The extension worked pretty well, but I had a hard time fixing bugs because of scenarios that I hadn’t planned for, like messing up certain websites such as Google Image Search. HippoLink was kind of a test for me. The core part of the extension was bought from a developer at fiverr.com. The test I faced was, whether or not I could have someone code boring pieces of code for me, for a very limited amount of money. I was pretty amazed by the quality of the code written by the programmer, but unfortunately, the test suite I wrote for the developer to pass, was deficient.

NuGetFeed.org
By Summer-Weekation, I started feeling integrated on the eBay team. I met a couple of colleagues who enjoyed coding in their spare time, like me. Brainstorming from these new found friendships ultimately gave birth to the website, NuGetFeed.org. This website is a service on top of NuGet.org, which lets users monitor updates on NuGet packages in their RSS reader. I was amazed by the popularity of the website. We were lucky enough to even get mentions from both Phil Haack and The Morning Brew. The website is still running and serving a lot of .NET developers to this day.

gInfinity
It had been a few months since I had last done a Chrome extension when I came up with the idea for a new extension while at work one day. The question came to me; Why do you still accept clicking the “Next” button in Google search results? Shouldnt it be supported by infinite scrolls like Facebook, Twitter and numerous other sites? Even though Google is experimenting with infinite scroll themselves, I decided to do a quick fix for Chrome myself. The result was gInfinity which turned out to be my most popular Chrome extension so far with over 1,500 users.

smileyapi.dk

A couple of years ago where myrating.dk where still high on my priority list, I made a small service making it possible to generate a smiley image from a CVR number. CVR numbers are the social security number of a company in Denmark and smileys are awarded by the government to all companies handling food. Happy smileys are given for good hygiene and other things, and unhappy smileys are given to companies which needs to fix something. This way the consumers can decide if they want to shop at the company or not. I didn’t really do much work on smileyapi.dk myself this year, but my talented colleague Steffen, helped me by doing a new layout for the site.

startuphq.dk
The idea for my latest project, in 2011, was born from a blog post written by the Danish blogger, Therese Hansen, which listed all Danish IT startups. My former colleague, Rasmus Christensen, invited me to join him on implementing a new website for listing startups. We ended up going live with Version 1 after having spent nearly 4 nights on straight coding. The feature set was limited to the listing functionality, with some fancy Google Maps integration. In the spirit of startups, we used MongoDB for the persistence and hosted the whole thing on AppHarbor. This was a very pleasant experience and even though I aren’t impressed by MongoDB, the gopspatial search is pretty darn awesome. During the next couple of weeks, we implemented a bunch of features like the possibility to find startup related events in your area. We are still adding new features to the site and firmly believe that StartupHQ will have the potential to be a great platform for IT startups and entrepreneurs.

Those are pretty much all of the new projects of 2011. Aside from these, I have also been working on some of my pre-existing sites and projects. The ones worth mentioning are listed below.

myrating.dk
This is pretty much my first web-system implemented using ASP.NET MVC. myrating.dk is a Danish rating site, where users can rate anything from movies to restaurants. I haven’t worked on the site much this year, aside from a new front page and login using Facebook Connect. I could probably implement a lot of new features on myrating.dk, but I’ve been putting too many hours into other projects, aside from my family, to have much time for work lately. Overall, I’m satisfied with the page views on myrating.dk and even though I don’t make a lot of money on it, it’s more than enough to pay for the hosting.

hippovalidator.com
I started implementing hippovalidator.com last year. hippovalidator.com is a website validation system, which can validate a website for different items like markup, performance, spelling and much more. I created the basic features last year, but paused the project to work on a Danish buy/sell site. I had to totally hold off on this idea when starting working at eBay because my project would have been a competitor to another large site that eBay owns called dba.dk. I decided that my design skills weren’t good enough to go live with hippovalidator.com, so I decided to hire a designer to do the graphics. I got in contact with a very talented designer through my work on the buy/sell site and she agreed to design ppovalidator.com as well. The design is pretty almost compete and I’m hoping to get a Version 1 of hippovalidator.com started next year.

When scrolling through this list, I am astonished. I’m impressed with the amount of work I’ve done this year. So what’s up for next year? First, I would like to be able to focus on fewer projects. I’ve been coding multiple projects this year and would like to build a new kick-ass project. hippovalidator.com is one of my key focuses and I would like to be able to release an initial free version in the beginning of 2012. Second, doing both NuGetFeed.org and startuphq.dk in cooperation with others, has taught me that coding with someone else is so much more fun and makes my work more productive. Collaboration makes the final outcomes even better and allows me to focus more easily.

Thanks for sticking around to hear about all of my experiences. Have a great and productive year, folks!

Share this post:

Share to Google Plus

I’ve used mock as long as I remember (pretty much). I’m a big fan of the whole dependency injection movement and make heavily use of IoC containers. Especially constructor injection turns out to be the correct approach for almost every system I’ve worked on. One thing that always bugged me is when creating a new object to run some tests on, is the amount of mocking code I will have to write to create the instance:

var mock = new Mock<IService3>();
mock.Setup(x => x.DoStuff()).Returns(true);
var sut = new ServiceToTest(
    new Mock<IService1>().Object,
    new Mock<IService2>().Object,
    mock.Object);

The above code is a simplified example. Most of my test-hungry classes typically have lots of dependencies injected through their constructors. In the example I only need to set expectations on the mocked IService3, why I simply inject “empty” mocks for the rest of the parameters. Alternative I could inject nulls for the not important parameters, but in my experience, injecting something not null, makes the test more robust to changes in the tested code.

So why is this a problem? It all leads down to the fact that I am lazy. Creating multiple “empty” mocks is boring and every time I add a new parameter to the constructor of the ServiceToTest class, I need to fix one to multiple compile errors in my test project.

I recently discovered that AutoFixture, one of my favorite unit test frameworks, became a lot smarter from version 2.0 and beyond. AutoFixture now accepts plugins, which have opened up for a range of interesting additions to this great framework. A great plugin for all of your Moq users is AutoFixture with Auto Mocking using Moq. Even though the name sounds a bit uncool, the added value is really great! With Auto Mocking my code can be refactored to the following lines:

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var mock = fixture.Freeze<Mock<IService3>>();
mock.Setup(x => x.DoStuff()).Returns(true);
var sut = fixture.CreateAnonymous<ServiceToTest>();

I start by creating a new instance of the AutoFixture Fixture type (line 1). I typically have this line in my test base class anyway. In the same line I tell AutoFixture to use the Auto Moq plugin by creating a new AutoMoqCustomization instance and passing it to the new Customize method on my fixture instance. Fluent APIs are great!

Let’s jump to line 4, where I ask AutoFixture to create a new instance of the ServiceToTest class. AutoFixture does its magic and creates a new instance using reflection. Remember that the ServiceToTest class have a constructor taking three arguments. AutoFixture itself can’t figure out how to create instances of IService1, IService2 and IService3, but because we provided it with the AutoMoqCustomization plugin, which uses Moq for creating those instances. Brilliant!

In my case I actually want to setup some expectations on the IService3 mock, why I use the Freeze feature of AutoFixture (line 3), to tell the framework to use a freezed variable in the fixture. This will bypass the default behavior for creating new instances in AutoFixture.

So what did we accomplish here? Adding parameters to the constructor of ServiceToTest no longer causes compile errors in the tests and furthermore we don’t need to manually add additional “empty” mock parameters. Sweet right?

Share this post:

Share to Google Plus

Since I started writing my NUnit asserts using Assert.That* instead of Assert.Are*, I’ve been hooked on the new syntax. The constraint API makes asserts readable and helps you specifying the expected and actual values at their proper places. One thing that always displeased my eye for perfection, was the R# warning shown when doing multiple asserts on the same value:

R# tries to tell me, that result may be null. That’s just stupid, right? We just asserted, that result is in fact not null. While this definitely is a bug in R#, there is an easy fix for this. Recently I was looking some more at the That-method overloads and found a method, which is probably known but everyone than me. The overload takes a simple bool, making it easy to suppress the R# warning:

What is the difference here? Rather than using the constraints API in NUnit for asserting the value being not null, I simply write a statement translatable to a bool value (result != null). This should make R# happy and to be honest, the code still looks pretty readable to me.

Share this post:

Share to Google Plus

I’ve been praising the “new” Assert.That syntax, since introduced in NUnit 2.4. Expressing your tests using a constraint based API, rather than the old Are* and Is* API, makes reading your tests piece of pie. Take a look at the following test sample:

var result = "Hello World".Split(new[] {' '});
Assert.AreEqual(2, result.Length);
Assert.AreEqual("Hello", result[0]);
Assert.AreEqual("World", result[1]);

It doesn’t take 10 years of programming to understand the code here, but I’ve always had a problem with the order of the parameters to the AreEqual-method. The problem is, that the expected value goes before the actual value. First it is not readable. Second when people by accidently swap the order of the parameters, problems starts happening. As long as the test is running successfully, there’s no problem. The static AreEqual-method on the Assert class, simply calls equals on the two objects and equals doesn’t care about the order of the parameters. The problem arises when the objects aren’t equal. NUnit throws an exception, with an error message indicating what went wrong. If you’ve swapped the parameters, NUnit says something like: “Expected ‘A’, Should have been ‘B’”. When in fact expected it’s the other way around. I have once spend two hours of debugging, just to find out about the switched parameters. DOUGH! For these two reasons, switching to the Assert.That-syntax, makes it all worth it. The previous code sample can be written like this:

var result = "Hello World".Split(new[] {' ');
Assert.That(result.Length, Is.EqualTo(2));
Assert.That(result[0], Is.EqualTo("Hello"));
Assert.That(result[1], Is.EqualTo("World"));

Notice how the actual value now goes first, and the constraint (Is.EqualTo) goes last. No confusion about the order of the parameters here. Also the code is now pretty much self explained (Assert that result length is equal to 2).

But we can do better than this. I stumbled upon a framework called Shouldly last year, but didn’t really saw the potential until a few months ago. Shouldly uses .NET extension methods to simplify the assert syntax even more, making it clean and readable. Our sample written with Shouldly looks like this:

var result = "Hello World".Split(new[] {' '});
result.Length.ShouldBe(2);
result[0].ShouldBe("Hello");
result[1].ShouldBe("World");

Why is this better than the Assert.That syntax one might wonder – well, it is probably a matter of taste. I really like the idea with using extension methods to achieve the shortest possible syntax for asserting a value. Why do you need to keep repeating yourself by writing Assert. before every single assert? With Shouldly you don’t! That’s fluent baby!

Share this post:

Share to Google Plus

A former college of mine told me, that he had founded “The association opposed the abandonment of PerformanceDude.com”. In order to make him happy, I thought that I would leave the wonderful world of unit testing for a moment, in the benefit of writing a performance related post :)  We’ve reached YSlow rule number 12 – Avoid redirects. I think the Yahoo documentation about the subject is a bit vague, so here’s my opinion on the subject.

Redirects are used to tell the browser, that a requested URL have been moved either permanent (http status code 301) or temporarily (http status code 302). When doing a request which returns a 301/302, the browser automatically makes a new http request, towards the URL returned by the 301/302. Being able to redirect URLs is really important if you want to change your URLs and your site is already indexed by search engines. If changing your URL scheme without returning a redirect, you basically lose your ranking in search engines like Google and all those hours spend getting link juice is wasted. In ASP.NET MVC 3 doing redirect is easy:

public ActionResult OldUrl()
{
    return RedirectPermanent("/the-new-url");
}

Notice that the above example returns a 301 (permanent redirect). If you for some reason need to return a 302, use the Redirect-method instead.

So what is my opinion on this YSlow rule? Well unless you use some sort of obscure web-framework which does a lot of magic behind the scene, there’s only one pitfall which should make you want to do something about this rule. When doing permanent redirects, ALWAYS make sure that all your internal links points to the new URL, rather than towards the old URL, letting the browser do the redirect. Implementing this anti-pattern will absolutely slow down your site!

Share this post:

Share to Google Plus

I’m usually writing about unit testing but hey, you want to test your lower layers as well. If you design your application with low coupling and test in mind, all of your layers but the data layer, can be tested with unit testing. You need to write some integration tests of your ORM layer though, in order to test your object to database mappings.

At my workplace we use FluentNHibernate and are pretty happy with it. I won’t go into detail on how the tool works, but in short it is an alternative to hbm.xml and ActiveRecord mapping entities in NHibernate. All the mapping stuff goes into a separate class, which makes the entity itself clean and simple. When doing mapping code, you always want to test it against a real database (possible in-memory), doing all of the CRUD operations. If you have a lot of entities, writing all these tests can be a time consuming and tedious task. Luckily FluentNHibernate provides us with the Persistence specification testing framework, which makes testing the mapping code easy (source code from the FluentNHibernate site):

[Test]
public void CanCorrectlyMapEmployee()
{
    new PersistenceSpecification<Employee>(session)
        .CheckProperty(c => c.Id, 1)
        .CheckProperty(c => c.FirstName, "John")
        .CheckProperty(c => c.LastName, "Doe")
        .VerifyTheMappings();
}

Pretty sleek, right? The code creates a new PersistenceSpecification with a generic type of the entity I want to test. For each property, call the CheckProperty method on the fluent API, assigning a test value and finally call VerifyTheMappings, which executes the basic CRUD operations. I used this approach during some time and found it usable but required some maintenance, each time the entities grew with more properties. @chripede and yours truly set out to find a better solution.

We ended up using AutoFixture by @ploeh to create maintainable tests. We already used AutoFixture to generate test values for all of our unit tests, but found the tool to work extremely well in conjunction with the Persistence specification testing methods. The above test were refactored to look something like this:

[Test]
public void CanCorrectlyMapEmployee()
{
    var fixture = new Fixture();
    new PersistenceSpecification<Employee>(session)
        .VerifyTheMappings(fixture.CreateAnonymous<Employee>());
}

AutoFixture generates a new Employee object, filling out all the properties with test values. In the test we don’t care if FirstName is set to “John” or some random string. The important part is, that the property can be written to and fetched from the database. So why is the second test method cooler than the first? When adding new properties to the Employee entity, our CanCorrectlyMapEmployee test automatically tests the new property, because AutoFixture uses reflection to fill the entity with data.

Share this post:

Share to Google Plus

This is my first blog post about unit testing. And so, without further ado here’s a small utility I wrote the other day.

Problem

Attributes in .NET as well as annotations in Java are great. I simply love the strengths of action filters in ASP.NET MVC, which are simply just a way to do aspect oriented programming through attributes. You typically want to write a unit test of the method annotated with an attribute, as well as a unit test of the attribute implementation. But sometimes it would be a disaster if someone by mistake removed or out commented the attribute definition from a method. So why not write a unit test of the presence of the attribute? In my case I had a number of ASP.NET MVC actions, annotated with the Authorize attribute. This simply tells the framework to verify that only logged on users can call the method.

Solution

My solution was to write some reflection code, which verifies the presence of a specified attribute on the method under test. I’m a big fan of DRY and therefore wanted to make a reusable method for this scenario. Inspired by Shoudly (a framework for writing cleaner unit tests, which I will probably write more about in the future), I wrote the following extension method:

public static void ShouldHave<T, TT>(this T obj, Expression<Func<T, TT>> exp, params Type[] attributes)
{
    var memberExpression = exp.Body as MethodCallExpression;
    foreach (var attribute in attributes)
    {
        Assert.That(
            memberExpression.Method.GetCustomAttributes(attribute, false).Any(),
            Is.True,
            attribute.Name + " not found on " + memberExpression.Method.Name);
    }
}

This small method makes unit testing the presence of an attribute piece of pie:

var controller = new HomeController();
controller.ShouldHave(x => x.Index(), typeof(AuthorizeAttribute));

Nice! We now have a strongly typed test, which verifies the AuthorizeAttribute on the Index method.

Share this post:

Share to Google Plus

Way down the list of YSlow rules, we’ve reached rule number 11, which is important and a no-brainer to implement. The rule is titled “Minify JavaScript and CSS.” So what is minification, and why do we need it?

Both JavaScript and CSS files are packed with unnessecary characters like spaces, comments, tabs, etc. Minification is the process of identifying which characters can be cut out. One part of minification can also be done by obfuscating the code, as we know it from obfuscators for Java and C#. In short, obfuscation is the process of shortening everything that can be shortened: method names, variable names, etc. These different methods combined lead to a more compressed output file, which leads us to question number 2: why do we need it? Fetching not only JavaScript but also CSS is a time-consuming task in the browser. The render thread blocks every time the browser loads a script, which can cause the user experience to regenerate. Speeding up the load time for JavaScripts and style sheets causes the browser to render the page quicker.

Minifying your JavaScripts and style sheets is easy. You can use one of the various minification tools online like thisthis, or this. If you want to use this approach, Google for “JavaScript minify” and use the tool you think is the best.

There’s a downside to minification as well. When you want to debug your JavaScript, the minified source code looks pretty messy and is hard to read. Luckily there’s a better way than hardcoding your minified source: minifying on the fly. I’ve previously talked about Mads Kristensen’s WebOptimizer, which contains nice HTTP modules for both JavaScripts and style sheets. I usually go with SquishIt, which I wrote about in my blog post “Combining your scripts and style sheets with SquishIt.” SquishIt combines your scripts and style sheets into a single file, which reduces the amount of HTTP requests done by the browser. In addition, SquishIt also minifies the generated file. What’s really genius about the minification in SquishIt is its ability to avoid merging and minification when working on a localhost. Here you will have the ability to work with individual files as well as not-minified scripts, which helps you debug.

(Proofread by inWrite)

Share this post:

Share to Google Plus

Google just introduced a new performance related feature in Google Chrome: Prerendering. The feature is pretty basic, but makes a big difference when using Google as your search engine. When searching, Chrome will start background-loading the first URL in the search result. If you choose to click the URL, the content will load instantly. You’ll need the dev channel of Chrome for this to work. Read more at the Chromium Blog.

Share this post:

Share to Google Plus

Most of us (me included) don’t think much about the way DNS works. Browsers, on the other hand, use DNS pretty much every day. For the uninformed, I will start by explaining how DNS works. If you already know this, feel free to skip the following paragraph.

As you know, all computers with a network card installed are awarded an IP address, which is four (or more) numbers separated by dots. When you do a request on a webserver, you are actually making an HTTP request to an IP address. Inputting IP addresses in the browser would make browsing the web just plain horrible. The DNS was invented to avoid having to remember IP addresses. When requesting a domain name, like www.hippovalidator.com, your browser asks the DNS to resolve the inputted domain name to an IP address. The request is then sent to the IP address returned by the DNS server, making it easy and painless for you to request a webpage.

Now then, why do we as performance-optimizing wizards need to worry about DNS? Well, in my opinion, we don’t. According to the YSlow documentation, a single DNS request typically takes 20-120 milliseconds. This may not seem much, but imagine the following HTML header example code:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js"></script>
 <script type="text/javascript" src="http://static.myrating.dk/rating.js"></script>
 <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>

<script src="http://cdn.uservoice.com/javascripts/widgets/tab.js"></script>

The browser needs to make 5 requests to the DNS server in order to fetch the referenced scripts. Worst case scenario, this will (according to YSlow) take as much as 600 milliseconds. This is a substantial amount of time! How do you avoid this?

Option 1: Reference less stuff from other domains.

Option 2: Copy the referenced stuff from the other domains to your own domain (in the example above, the scripts could all reside on the local domain).

So let’s head back to my point about DNS not being important. In fact, I don’t think you should implement any of the solutions mentioned above. Why?

1. Because of DNS caching. When your browser asks a DNS server for an IP address, the result is cached in the browser’s local DNS cache. Chances are, your ISP already has the result cached as well.

2. Because of prefetching in all modern browsers. Every single browser that I can think of does some sort of prefetching. In Chrome, a background thread parses all domain names in a requested HTML document and resolves the domain names while you look at the page. IE does something similar.

3. Because reducing DNS lookups also reduces the number of simultaneous downloads in the browser. As I mentioned in a previous post, the browser is not able to make unlimited simultaneous requests to the same domain. That’s why my recommendation is to use jQuery (and similar from Google’s or Microsoft’s CDN) and place all of your static files like images, scripts, and style sheets on a subdomain. This would result in more DNS lookups, but it would optimize the browser’s possibilities to fetch the needed resources.

The conclusion is this… Don’t be alarmed when YSlow warns you about reducing DNS lookups!

Share this post:

Share to Google Plus