I'm a C# developer located in Copenhagen, Denmark. I love simple solutions solving complex stuff.

Also I'm one of the founders of Servant.io.

jhovgaard on Twitter

How I stopped writing awesome code

PUBLISHED 12 June, 2012 ()

The problem

If writing awesome code is using all the best practices I can find, writing interfaces, unit tests and using top notch IoC containers to control my repositories and services all over my application’s different layers - Then I’m not writing awesome code at all!

I’ve been that guy, the one writing the awesome code, but I stopped. I’m not awesome any more. Instead, I’m productive, I’m so damn productive!

I don’t write unit tests

ZOMG you may think. You are right, I lose so much safety. I don’t know if I break other parts of my code if I change something.

I’ve spent so much time writing all of these tests, even before I ever wrote the code to test (that should be a “wtf”), and still my boss complained that functions suddenly didn’t worked any more.

To make my boss (or your customers) happy again I started investigating what I needed to make sure worked. The answer was the result in the browser. In my test scenario I found out that the important things for my boss was to be sure that these functions worked flawless:

My boss or your customers don’t care about the status of our unit tests. They look at the result in the browser and so should I.

To overcome this challenge, I downloaded the Selenium IDE for Firefox. Selenium is neat tool that enables you to run a list of commands directly in a browser. It gives you a list of all failed and succeeded tests (yeah, like your current unit tests). The big ass difference here is that these results is based on the end result (the HTML returned), not something techy stuff going on even before the browser.

I don’t wanna teach how to use Selenium (spam me in comments if you want me to), I just want to point out that my tests tells me what will make my boss sad, and your test tells you what code that breaks. If you don’t agree, please comment - that’s the purpose of this post :-)

I don’t do interfaces or use IOC

This started because of the lost connection between my concrete class and the place I ended when I hit F12 in Visual Studio (Go to declaration). This meant that not even Visual Studio understood what class my IUserService actually was. How could that be? What is the advantage? In my personal scenario (creating around 20-30 apps every year), I did it to be able to change the concrete class later on. The funny fact is that I never ever did this, except for one time.

I agree, it’s absolutely awesome that I can change the concrete type or lifecycle with ease, but for gods sake, I don’t even dare to count the hours I have spent creating these abstractions, making me able to do something I never freaking do.

Oh, I forgot something. I did spent a lot of time writing interfaces (yeah okay, Resharper did it, but was annoying when I created new methods). But also I spent hours trying to understand what Ninject or StructureMap did with my classes. When I finally understood, I handed over the application to the next developer who also was forced to spent time understanding some IOC.

How hard could it be to initialize every class like this:

var userService = new UserService();

I could even create my classes as static, making them singletons or whatever to each individual class. My co-programmers could understand what was going on immediately, without finding and understanding my AwesomeIoc.Init() method.

Sure, again I lose some functionality and safety but seriously, programming is like Diablo 3 - You don’t need armor and life, if you kill in one hit!

For non gamers: I mean you don’t need all that functionality, if your productivity gets much higher without it.

I don’t use regular ORMs

One day I was struggling with NHibernate, trying to make it send the correct query to my SQL server (not MySQL, just mine). Funny thing was - I knew what it should sent. So one thing was obvious - I didn’t used NHibernate to help me write complex SQL queries - I’m no brogrammer, so I know how to write those magic strings!

So why did I use it? The answer was: to map the data from my database to my “domain” classes (I hate that word, it’s POCOs). Also I used it to track all changes to the POCO’s properties.

I started searching Github for better alternatives and I found Simple.Data and Dapper. This is extremely simple ORMs. Dapper is the most simple, letting me write true SQL directly in C#, and gives me the results as POCOs. Simple.Data is a bit more complex. You don’t write SQL directly, but use chained lamba, to instruct how to query.

Whether I use Simple.Data or Dapper I no more struggle with things I already know. I’m not afraid of relations and I don’t have to open a Profiler to find out what queries my ORM sends to the SQL server.

Again, with thoughts back to Diablo 3, I gained more damage, but lost some armor. However, my accumulated damage (meaning productivity) is now so high, I just kill it all instantly!

I do everything to make things more simple

I found out that simple code makes me smile. It makes me able to create new functions extremely fast, without hitting “walls”. So whenever I write code, I always try to keep it simple. Not DRY, but simple! If some code gets more complicated when DRYing it, I don’t care about copy pasting (however, most of the time I just rewrite the DRY code, making it simpler).

I don’t use Microsoft’s big mother MVC framework, but instead stick with minimalistic and simple frameworks like NancyFX. Whatever I do, I just try to do it more simple.

The result is the conclusion

My personal result of doing all of this is productivity and better products. I can’t tell if I did it all wrong, and that’s why I’m writing better code now, but I truly believe that I’m not alone. In fact I think that most of us regular web developers, tend to do the same “mistakes” as I did.

Please, let me hear your thoughts. Do you think I’m just a noob who doesn’t understand shit? Is it all too “brogrammerish”, or do you actually agree with me? Whatever the reason, thanks for your comment!

If you read so far, why don’t you follow me on Twitter? :-)

Update 13th June 2012

Because of the big attention this post got, I wanna point out a few things:

I agree, the post was meant to provoke. However the post wasn’t written to flame unit tests. They are awesome and extremely important on large projects with a bigger lifespan. However, I believe they aren’t always necessary on smaller projects. The intention with this post is to make us all remember to be critical to our tools and remember that “best practices” can’t be best in all situations.

The post is targeted to the “average” developer (those we often forget), who’s responsible for developing the smaller applications, not necessary visible to the public, but extremely important for the right companies.

I do use TDD, I do use interfaces and IOCs, I do use complex ORMs and big frameworks, but only, and only when I really need it (I kinda try to reduce the noise in my apps). Like said in the comments: It’s a question about choosing the right tools for the job.

Oh btw, to avoid further flaming - Yes, you’re right, I’m a big noob who writes spaghetti code that isn’t maintainable at all.</sarcasm>

Update 12th July 2012

A few people have responded via blog post. Check em’ out here:

Thanks for joining the discussion guys :-)

Do you still manage your web server through remote desktop or IIS Manager? Try Servant.io today!

From ASP.NET MVC to Nancy - Part 3

PUBLISHED 23 February, 2012 ()

This is a series of posts. If you just dropped into this article, you really should start by reading part 1.

Wauw! Nancy is really the thing at the time! Part 1 and 2 have only been online for 5 days and you guys already made 1500 pageviews. I’m impressed! Unfortunately I haven’t recieved much feedback. Please make a comment, hit me on Twitter or email (j at jhovgaard dot dk). I need that feedback to make better posts. Thanks! :-)

Today’s Nancy topic is a bit more complex. We’re going to work a bit with Dependency Injection. Whether you’re an experienced injector, or you think this Dependency Injection is just another buzzword really doesn’t matter. This stuff will hopefully be so easy to understand that everybody gets it.

1. Installing TinyIoC on our Nancy project

Congratulations! You’re successfully installed TinyIoC! Yes, it was already included in Nancy, but let’s celebrate anyway.

2. Creating a service

Alright, I’m not going to try explain what dependency injection is. If you don’t know, try to figure out what’s going on here, it’s really that simple!

In this example we’re creating an WebApplicationService.cs. No doubt it’s a bad example, but we need to keep things simple. Our new service will have these abilities:

Go ahead and create WebApplicationService.cs in our /Models folder. Next, paste these methods into your new service:

public class WebApplicationService
{
    private readonly DateTime _created;
    private int _totalRequest;

    public WebApplicationService()
    {
        _created = DateTime.Now;
        _totalRequest = 0;
    }

    public DateTime GetCreationDate()
    {
        _totalRequest++;
        return _created;
    }

    public int TimesRequested()
    {
        return _totalRequest;
    }
}

3. Time for the mandatory administration section

Let’s create a ViewModel for our first action in the admin section, by creating a IndexModel.cs in /Views/Admin/Models/ (just create the folders). Drop in these properties in the IndexModel.cs file:

using System;

namespace nancytest.Views.Admin.Models
{
    public class IndexModel
    {
        public DateTime CreationDate { get; set; }
        public int TotalRequests { get; set; }
    }
}

Next up, add our new action to AdminModule.cs and use depedency injection to serve the WebApplicationService to our Module:

using Nancy;
using nancytest.Models;

namespace nancytest.Modules
{
    public class AdminModule : NancyModule
    {
        public AdminModule(WebApplicationService webApplicationService) : base("/admin")
        {
            Get["/"] = parameters => {
                var model = new Views.Admin.Models.IndexModel {
                    CreationDate = webApplicationService.GetCreationDate(),
                    TotalRequests = webApplicationService.TimesRequested()
                };

                return View["Index", model];
            };
        }
    }
}

Let’s take a deeper look at this code. First thing to notice is the expansion of the constructor : base(“/admin”). This tells Nancy that every action’s URL inside this Module starts with /admin. The next big thing is the injection of our WebApplicationService. This is extremely simple, isn’t it? We just throw in the objects we want initialized in the parameter list of the constructor and Nancy together with TinyIoC takes care of everything. By default all injections on concrete/base classes will be made as multi-instance, meaning that every call (http request) creates a new instance of the object. If we had used an interface (could be IWebApplicationService) TinyIoC detects this and make the object behave like a singleton (meaning only a single instance of the object, shared over all http requests).

Before we can see all this in action we need (of course) to create the Index view. Create a new HTML page called Index.cshtml inside the /Views/Admin folder. Make it look like this:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<nancytest.Views.Admin.Models.IndexModel>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1>Welcome to the admin page</h1>
    <table>
        <tr>
            <td>Creation date for WebApplicationService:</td>
            <td>@Model.CreationDate</td>
        </tr>
        <tr>
            <td>Total request on the service:</td>
            <td>@Model.TotalRequests</td>
        </tr>
    </table>
</body>
</html>

Save everything and power it up (CTRL+F5). Point your browser to /admin. If everything is as expected you should see something like this:

4. Defining the lifecycle of WebApplicationService

Okay, try to do some refreshes on our /admin page. You see? The creation date changes. That’s a bug combined with the intention of our service. To fix this, we need to tell Nancy that we don’t wanna use the default life cycle (which is multi-instance for concrete classes like ours), but rather wants to treat it as a singleton (meaning the object will only be created one time).

To do this we create a custom bootstrapper. This could seem a bit complex, but it really isn’t when you get the understanding (you didn’t figure that out, huh? Hehe). Create a MyBootstrapper.cs class in our /Models folder. Make it look like this:

using Nancy.Bootstrapper;
using TinyIoC;

namespace nancytest.Models
{
    public class MyBootstrapper : Nancy.DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            container.Register<WebApplicationService>().AsSingleton();
        }
    }
}

I know. Freaking overrides and stuff. But actually most of this stuff is standard code. The only thing to notice here is this line:

container.Register<WebApplicationService>().AsSingleton();

This tells Nancy that our WebApplicationService… Wait, you already get it, right? That’s how an awesome framework roll!

Again, save everything and hit CTRL+F5. Point your browser to /admin again and try refresh a couple of times. Do you see the difference? Our service is now only created once, making us able to count the requests and persist the CreationDate.

One last thing? Didn’t you expect we needed to tell Nancy about our custom bootstrapper? I did. But because Nancy is trying to be the best micro MVC framework, it just detects our bootstrapper and uses that instead. No need for Global.asax, just plug and play.

5. Conclusion

In this post we learned how to use the integrated dependency injection of Nancy provided by TinyIoC. Also, we learned how to modify objects’ lifecycle and last we learned how to create a base url for a NancyModule.

I’m not finished with Nancy yet and I believe there will be 2 or 3 additional parts. If you have some specific topic you want me to cover, let me know :-)

Click here to download the source for this post.

Please, if you enjoyed reading this post - share and comment it!

Do you still manage your web server through remote desktop or IIS Manager? Try Servant.io today!

From ASP.NET MVC to Nancy - Part 2

PUBLISHED 19 February, 2012 ()

This is a series of posts. If you just dropped into this article, you really should start by reading part 1.

Alright. Note to my self: Never say “tomorrow I will…” in a blog post unless the stuff to do already is done :P Sorry for the delay but here we go again.

Nancy Modelbinding - moving data from our module to the view

Today we’re going to move an object from our module/controller to the view. Next we’re going the other way, posting a new object from the view and back to the module.

Creating a BlogPost object

First, let’s create an actual object to return to our View. We make a classic BlogPost object in a folder called Objects:

using System.Collections.Generic;
namespace nancytest.Objects
{
    public class BlogPost
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public List<string> Tags { get; set; }

        public BlogPost()
        {
            Tags = new List<string>();
        }
    }
}

Return the new BlogPost object to our view

Start by extending our “/” action to create a new BlogPost object and return it to our Index view:

using Nancy;
using nancytest.Objects;

namespace nancytest.Modules
{
    public class HomeModule : NancyModule
    {
        public HomeModule()
        {
        Get["/"] = parameters => {
            var blogPost = new BlogPost {
                Id = 1,
                Title = "From ASP.NET MVC to Nancy - Part 2",
                Content = "Lorem ipsum...",
                Tags = {"c#", "aspnetmvc", "nancy"}
            };

            return View["Index", blogPost];
        };
        }
    }
}

Notice that I simply pass in my object as the second parameter when I return my view.

Preparing the view for BlogPost and enabling IntelliSense

Open up Views/Home/Index.cshtml. We need to tell Razor what model it should use. In ASP.NET MVC we would do it like this:

@model nancytest.Objects.BlogPost

Unfortunately Microsoft made some bad decisions designing Razor. Because of that we’re not able to do this using Nancy. Instead insert this line of code in the very top of the page:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<nancytest.Objects.BlogPost>

This tells Razor about the model - Nancy Style!

Take it for a spin by adding some @Model usage on Views/Home/Index.cshtml:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<nancytest.Objects.BlogPost>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
    <body>
        <table>
            <tr>
                <td>Id:</td>
                <td>@Model.Id</td>
            </tr>
            <tr>
                <td>Title:</td>
                <td>@Model.Title</td>
            </tr>
            <tr>
                <td>Content:</td>
                <td>@Model.Content</td>
            </tr>
            <tr>
                <td>Tags:</td>
                <td>@string.Join(", ", Model.Tags)</td>
            </tr>
        </table>
    </body>
</html>

Did you just freaking notice how natural that felt for IntelliSense? Or do you instead wondering why I’m so psyched about an old feature in Visual Studio? Well, the reason for that is in the early versions of Nancy, IntelliSense wasn’t available and Visual Studio didn’t recognize the .cshtml as Razor view pages, so even simple HTML made VS throw errors. These days are over and Nancy works, as you can see, like a magical unicorn in VS.

Do some CTRL+SHIFT+B and CTRL+F5 magic and you should see something like this:

Time for the post action. Let’s pretend we create a BlogPost

Jump right back into HomeModule and add a new action mapped to /new/ (GET) like this:

Get["/new/"] = parameters => {
    return View["New"];
};

Next create a New.cshtml in the folder Views/Home. Again we declare it to use our BlogPost object as model:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<nancytest.Objects.BlogPost>

Create a simple form, posting to /new/:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<nancytest.Objects.BlogPost>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
    <body>
        <form action="/new/" method="post">
            <table>
                <tr>
                    <td>Id:</td>
                    <td><input type="text" name="Id" value="@Model.Id" /></td>
                </tr>
                <tr>
                    <td>Title:</td>
                    <td><input type="text" name="Title" value="@Model.Title" /></td>
                </tr>
                <tr>
                    <td>Content:</td>
                    <td><input type="text" name="Content" value="@Model.Content"/></td>
                </tr>
                <tr>
                    <td>Tags:</td>
                    <td><input type="text" name="Tags" value="@string.Join(",", Model.Tags)"/></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Add new"/></td>
                </tr>
            </table>
        </form>
    </body>
</html>

Next up is creating the action handling the POST coming from this form. Jump back into our HomeModule and add a new action:

Post["/new/"] = paramters => {
    var blogPost = this.Bind<BlogPost>();
    // Redirects the user to our Index action with a "status" value as a querystring.
    return Response.AsRedirect("/?status=added&title=" + blogPost.Title);
};

Also, don’t forget to import the Nancy.ModelBinding namespace in the top of our class like this:

using Nancy.ModelBinding;

Awesome! Here we throw the user back to our Index page (root) including some stuff in the querystring for our convenience.

Nancy is just getting more and more fantastic. Did you notice the extremely fast build times and the native feeling when you just do raw web development?

That’s all folks! In post 3 I’ll start by looking into the IoC container TinyIoC which is by default integrated in Nancy.

Still psyched about Nancy? Click here to go directly to part 3!

Click here to download the source for this post.

Please, if you enjoyed reading this post - share and comment it!

Do you still manage your web server through remote desktop or IIS Manager? Try Servant.io today!

From ASP.NET MVC to Nancy - Part 1

PUBLISHED 17 February, 2012 ()

If you have ever been in the world of Ruby you would know about this little framework called Sinatra. In it’s core concept it’s a MVC framework, just extremely simple and fast.

Nancy is a Micro .NET framework inspired by Sinatra. If you ever felt that ASP.NET MVC is too heavy, too clumsy and stands in your way, Nancy is definitely made for you.

I’m an average .NET developer. I work for a middle-sized company where we build a lot of applications in ASP.NET MVC 3 and because of that, this series of posts will be designed for exactly that purpose: moving from ASP.NET MVC 3 to Nancy.

Creating the application

Grap a new instance of Visual Studio 2010 and create a new Empty ASP.NET Application. Yes that is what we want. Personally this was my first time using this template.

Next we’re going to install Nancy using Nuget. Right click References in the solution explorer and click Manage Nuget Packages…. Search for Nuget and install Nancy.Hosting.Aspnet and Nancy.Viewengines.Razor:

This will install Nancy including Razor support. Also it will add Razor as a BuildProvider in your web.config, enabling Visual Studio to support IntelliSense in our views.

Time to get nasty - the good way…

Yay! We’re ready! You remember controllers in MVC3 right? In Nancy we got something like that, it’s just called Modules, but seen from our eyes it’s the same thing.

Again, in MVC3, inside our controller, we had a massive amounts of “Actions” defined as methods. This is not nearly as complex in Nancy. Let me create an Index-action for you:

public class HomeModule : NancyModule
{
    public HomeModule()
    {
        Get["/"] = parameters => {
            return View["Index"];
        };
    }
}

zOMG! See what’s going on here? First I create a “parameterless constructor”. Fancy word, but this is actually just the public HomeModule() part. So inside our constructor (if you’re in for seh winz you call this a “ctor”) I both define the route (the ones we know from Global.asax) and the action it self. At last I return a view called Index.

Creating the “Index” view

Next up is our Razor Index view. Create a new folder called Views. In here create another folder called Home. Now right click the folder and create a HTML page called Index.cshtml. Put in some motivating text and hit CTRL+F5.

Now two things can happen. You’ll see a scary YSOD page telling you that the page “/Views/Home/Index.cshtml couldn’t be served, or you will see your motivating text, served directly from Nancy. If you got the scary one, point your browser to the root of the application. If the last I would like to congratulate you with your first Nancy application :-)

This was part 1. Wanna know something about Nancy’s ModelBinding, ViewModels and so on? Go for part 2 :-)

Click here to download the source for this post.

Please, if you enjoyed reading this post - share it!

Do you still manage your web server through remote desktop or IIS Manager? Try Servant.io today!

C# Generating new priority/index order

PUBLISHED 8 February, 2012 ()

Sup!

I just came by one of those scenarios where you need to generate new priority indexes because the user wants to reorganize some list.

Normally I iterate through my list of objects and then calculate the new priority/order number on each loop (by doing difference stuff whether the new index is positive nor negative).

But this time I freestyled a little with NHibernate and the List generic. The user gets a list of “pages” that can be reordered.

I came out with this awesome method:

public void SetNewPagePriority(int pageId, int newPriority)
{
    newPriority--; //Abstract the user from zero-index
    var page = _pageService.GetById(pageId);
    if(page == null) return;

    var pagesInNewOrder = page.Test.Pages.OrderBy(x =&gt; x.Priority).ToList();
    pagesInNewOrder.RemoveAt(pagesInNewOrder.IndexOf(page));
    pagesInNewOrder.Insert(newPriority, page);

    //Sets the new priority in the database using the current index of the loop.
    for(var i = 0; i &lt; pagesIsNewOrder.Count; i++)
        pagesInNewOrder[i].Priority = i;
}

The code simply removes the object that needs to be reorganized from the list (NHibernate is clever enough to not delete the object from the database at this time), and then pushes it into the new location.

After that I simply iterate the newly reorganized list and sets the current index. NHibernate will then commit the changes for me.

Do you still manage your web server through remote desktop or IIS Manager? Try Servant.io today!