Adding Controls to a Server Control

Usually looks like this:

 
var row = new TableRow(); 
var cell = new TableCell()
    { 
         Height = Unit.Pixel(30) 
    }); 
cell.Controls.Add( new Button() 
    { 
        Text = "Go",
        CommandName = "Go",
        ID = "btnGo" 
    }); 
row.Controls.Add(cell); 

How about this instead:

 
var row = new TableRow(); 
var cell = row.AppendControl(x => 
                  { 
                      x.Height = Unit.Pixel(30); 
                   });
cell.AppendControl(x => 
    { 
        x.Text = "Go";
        x.CommandName = "Go";
        x.ID = "btnGo"; 
    });
 

Implemented with this:

 
public static ControlExtensions 
{ 
    public static TControl AppendControl(this TControl control, Action initialization) 
        where TControl : Control, new() 
    { 
        var controlToAppend = Activator.CreateInstance();
        intialization(controlToAppend);
        control.Controls.Add(controlToAppend); 
        return controlToAppend; 
    } 
} 

I think this reads better especially if you end up appending lots of child controls, thoughts or any other solutions?

Obstacles of unit testing & methods to side step them – Part 2: multi-threading

Introduction

Unit testing is good. Sure it’s no silver bullet but there is no such thing! Looking back I’m not sure how I managed to work without writing unit tests the number of time having tests has saved me from tracking down bugs isn’t worth thinking about :)

However everything isn’t all rosy once you start unit testing against your code, there are a number of items that can put a spanner in the works, and that’s why I have created this series of posts to try and help other people resolve some of these common issues you may find yourself up against.

  • Date & Time
  • Multi-threading
  • External Dependencies
  • Sharing Static items
Prerequisites
  • You have already been writing unit tests
  • You are familiar with state based testing and behaviour based testing & when best to use either
  • Are familiar with a mocking framework (these examples use Rhino Mocks).
Multi-threading

Let’s face it once we introduce multi-threading things usually get more complicated and trying to unit test multi-threaded code is no exception! Why? Well if we think about how our code is going to be executed it will be ran on the test runner thread by NUnit, MBUnit MSTest etc… And if we have code which is going to perform work on a separate thread this causes a problem because the test runner thread will not know that it should really be waiting for work on the other thread to finish before carrying on, let’s get into some code:

   1: [TestFixture]

   2: public class when_adding_two_ints_together

   3: {

   4:     [Test]

   5:     public void should_give_us_the_correct_result()

   6:     {
   8:         var processor = new Processor();

   7:         var sut = new AddTwoIntsWorkItem(1, 2);

   9:         processor.DoWork(sut);

  10:  

  11:         Assert.That(sut.Result, Iz.EqualTo(3));

  12:     }

  13: }

So for the example I created a simple Processor object and as simple command based interface and a concrete object:

   1: public class Processor

   2: {

   3:     public void DoWork(IWorkItem workItem)

   4:     {

   5:         ThreadPool.QueueUserWorkItem((state) =>

   6:             {

   7:                 workItem.Work();

   8:                 Thread.Sleep(2000);

   9:             });

  10:     }

  11: }

  12:  

  13: public interface IWorkItem

  14: {

  15:     void Work();

  16: }

  17:  

  18: public class AddTwoIntsWorkItem : IWorkItem

  19: {

  20:     protected int first;

  21:     protected int second;

  22:     protected int result;        

  23:  

  24:     public AddTwoIntsWorkItem(int first, int second)

  25:     {

  26:         this.first = first;

  27:         this.second = second;

  28:     }

  29:  

  30:     public void Work()

  31:     {

  32:         result = first + second;

  33:     }

  34:  

  35:     public int Result

  36:     {

  37:         get { return result; }

  38:     }

  39: }

You could imagine that this could represent something more real such as a scheduling object that hold a list of IWorkItem’s and can make calls to them in a async manner, so now we have everything setup we can run the unit test:

image

Hmm… were expecting 3 but getting 0 strange, well not really let’s try to breakdown what’s happening:

image

So our assertion Assert.That(sut.Result, Iz.EqualTo(3)); is being called before the work is done hence we get zero.

So how can we tell the test runner thread to wait till the work is done? Well there’s thread.Join() however we A don’t want to expose the thread object outside of the Processor object as this breaks encapsulation and B In this case we use the threadpool so don’t actually have a new thread created.

With thread.Join() out of the question we need to look for an alternative, luckily the Threading namespace gives a good way of handling this scenario via the AutoResetEvent/ManualResetEvent (the difference being that AutoResetEvent will set it’s state to false after being signalled automatically) that’s great we now have a mechanism for telling the thread to wait however how do we know when to signal the event and allow the test runner thread to carry on? at the moment we have no way of knowing when the Processor has processed the IWorkItem.

I don’t think it’s unreasonable to provide someway of knowing when the DoWork is complete, we can provide a WorkItemComplete event that can be subscribed to:

   1: public class Processor

   2: {

   3:     public void DoWork(IWorkItem workItem)

   4:     {

   5:         ThreadPool.QueueUserWorkItem((state) =>

   6:             {

   7:                 workItem.Work();

   8:                 Thread.Sleep(2000);

   9:                 RaiseWorkComplete();

  10:             });

  11:     }

  12:  

  13:     protected void RaiseWorkComplete()

  14:     {

  15:         if (WorkComplete != null)

  16:             WorkComplete(this, EventArgs.Empty);

  17:     }

  18:  

  19:     public EventHandler WorkComplete;

  20: }

I have introduced the event the next step is to amend our unit test to take advantage of this event and to synchronize the test runner thread with the threadpool thread doing the work:

   1: [Test]

   2: public void should_give_us_the_correct_result()

   3: {

   4:     // this is used to synchronize between this current thread &

   5:     // the thread that performs the work in Processor

   6:     var evt = new ManualResetEvent(false); 

   7:     var sut = new AddTwoIntsWorkItem(1, 2);

   8:     var processor = new Processor();

   9:     

  10:     processor.WorkComplete += (sender, e) => evt.Set(); // signal that work is done

  11:     processor.DoWork(sut);

  12:     // tells current thread to wait till work has been done in Processor

  13:     evt.WaitOne(3000); 

  14:  

  15:     Assert.That(sut.Result, Iz.EqualTo(3));

  16: }

It shouldn’t be too hard to see what’s going on here, I create a new ManualResetEvent and set it’s state to unsignalled, I subscribe to the WorkComplete event via a lambda which simply sets the ManualResetEvent to signalled, after the call the DoWork is made we wait for the ManualResetEvent to be signalled. So let’s give the unit test another go:

image 

Great! that worked a treat one thing to bear in mind is when waiting for the event to be signalled is what timeout to use, in the case above I used 3000 milliseconds you typically want to use something around this figure and should be used as a failover in case the event/method that your expecting to be called isn’t and you don’t get to signal the event, this will prevent the test runner thread from getting stuck.

You should now be more comfortable when having to unit test code that performs work in a separate thread, if you don’t want to expose an event to know when a particular task is finished you could use subclass and override to only provide the event on the test subclass object.

Extending the ASP.NET MVC HtmlHelper

The HtmlHelperobject in MVC is great if we want to have a link to an action on a controller we simply do:


htmlhelper extension manual

And this will create us a link with the text ‘my link’ and will automatically route the href to the ViewItem action on the controller in context. However the HtmlHelper object doesn’t have everything and there are going to be times when you want to have your own HTML rendered on screen, so how can we go about doing that.

The answer lies with extension methods, we can use these to extend the HtmlHelper object and provide us with what were after, in my case it was that I wanted a link but an image enclosed instead of just text.

So here’s the code to achieve this:

public static class HtmlHelperExtensions
{
    public static string ImageActionLink(this HtmlHelper helper, string imagePath, string actionName, string controllerName, object routeValues, object imageAttributes, object linkAttributes)
    {
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
        var anchortagBuilder = new TagBuilder("a");

        anchortagBuilder.MergeAttributes(new RouteValueDictionary(linkAttributes));
        anchortagBuilder.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));

                var imageTagBuilder = new TagBuilder("img");
        imageTagBuilder.MergeAttributes(new RouteValueDictionary(imageAttributes));
        imageTagBuilder.MergeAttribute("src", imagePath);

        anchortagBuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing);
        return anchortagBuilder.ToString(TagRenderMode.Normal);
    }
}

The good thing is that we get a few objects to help us build up the html and to handle the routing side of things rather than having deal with concatenating strings.

Notice that I use the RouteValueDictionary object so that I can use the anonymous type to dictionary trick, the UrlHelper deals with returning the routed URL I just need to provide the controller and what action to invoke, and the TagBuilder makes  light work of creating HTML.

So now from my view I can use it like this:


I could provide some overloads so that I don’t need to pass empty objects and to accept Dictionaries instead of just object, but you get the idea.

One other thing that’s worth doing is changing the web.config do that your namespace is added automatically to your views that saves having to put the Import on each view that wants to use your extensions, this can be found in the pages section in namespaces.

DataTable to CSV

This might come in handy for anyone who wishes to get there data from a DataTable into CSV format:

public static class DataTableExtensions
{
    public static string ToCsv(this DataTable dt)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append(dt.Columns[i].ColumnName);
            if (i < dt.Columns.Count - 1) 
                sb.Append(",");
        }
        sb.Append(Environment.NewLine);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sb.Append("\"");
                var row = dt.Rows[i][j].ToString().Replace("\"", "\"\"");
                sb.Append(row);
                sb.Append("\"");
                if (j < dt.Columns.Count - 1) 
                    sb.Append(",");
            }
            sb.Append(Environment.NewLine);
        }
        
        return sb.ToString();
    }
}

I have kept it simple by always wrapping the row values inside double quotes therefore should handle special characters ok, and I was in two minds whether to have this as a decorator around a DataTable or to just extend DataTable via extension method as you can see I went for the latter, not sure it matters much either way.

Obstacles of unit testing & methods to side step them – Part 1: date and time

Introduction

Unit testing is good. Sure it’s no silver bullet but there is no such thing! Looking back I’m not sure how I managed to work without writing unit tests the number of time having tests has saved me from tracking down bugs isn’t worth thinking about 🙂

However everything isn’t all rosy once you start unit testing against your code, there are a number of items that can put a spanner in the works, and that’s why I have created this series of posts to try and help other people resolve some of these common issues you may find yourself up against.

  • Date & Time
  • Multi-threading
  • External Dependencies
  • Sharing Static items

Prerequisites

  • You have already been writing unit tests
  • You are familar with state based testing and behaviour based testing & when best to use either
  • Are familar with a mocking framework (these examples use Rhino Mocks).

Date & Time

This first post covers testing against date and time, it is quite common to want to use the current date/time in your objects, say for example you have an audit object that keeps track of any changes made to a user of a system by an admin, it’s not unreasonable to expect a method along the way performing something like this:

public void PasswordChanged(string newPassword, IAdministrator changedBy)
{
    //.. set audit values
    passwordAudit.ChangedAt = DateTime.Now;
    auditService.Save(passwordAudit);
}

Now we have a problem how can we test that the audit service object got called with the correct values? Lets write a test for this:

[TestFixture]
public class when_changing_password_for_user : ContextSpecification
{
 //.. [snip]
    [Test]
    public void should_record_correct_values_against_audit_record()
    {
        mockAuditService.Expect(x => x.Save(null), o => o.IgnoreArguments())
                .Do(new Action(delegate(IAuditRecord audit))
                {
                    changedby.Username.ShouldEqual(audit.ChangedbyUsername);
                    audit.ChangedAt.ShouldEqual(DateTime.Now); // this aint gonna work!
                }
    }

    IPasswordAudit sut = createSUT();
    sut.PasswordChanged(newPwd, changedBy);
    }
 //..[snip]
}

I provided the textfixture to give some context to the testing taking place, this is the style I choose to write my tests it is based around BDD (Behaviour Driven Design).

As we can see audit.ChangedAt.ShouldEqual(DateTime.Now)); this bit of code is not going to do the trick, given that stopping time is out of the question, we have some other options a simpler way and one that works in this scenario is to push the date & time into the method call:

public void PasswordChanged(string newPassword, DateTime changedAt, IAdministrator changedBy)
{
    //.. set audit values
    passwordAudit.ChangedAt = changedAt;
    auditService.Save(passwordAudit);
}

We could now update the unit test to take this into account and check the DateTime values match (i’m not going to show this), there’s a lot to be said about KISS however sometimes this push approach can simple not be applied.

Take for example a scheduler object that is tracking the current date & time the push approach is unworkable, we need to some way to provide the scheduler object with a DateTime value but for it to be under our control.

There are 2 different styles that I know of to get date and time under our control, the first is by using an abstraction type that provides us with the current date and time:

public interface ICurrentDateTimeProvider
{
    DateTime Current {get;}
}

We can then use in our class that needs to access the current date and time, this would be a good argument for using property injection as it’s only a seam for testing purposes:

public class Scheduler
{
    protected ICurrentDateTimeProvider currentDateTimeProvider = new RealDateTimeProvider();

    public ICurrentDateTimeProvider DateTimeProvider
    {
        set {currentDateTimeProvider = value;}
    }
}

RealDateTimeProvider simply returns DateTime.Now.

We can now use this abstraction to control date and time:

[TextFixture]
public void when_scheduler_is_started : ContextSpecification
{
    [Test]
    public void given_schedule_item_next_run_is_in_the_past_should_execute_it()
    {
        currentDateTimeProvider.Stub(x => x.Current).Return(scheduleItemNextRun.AddMinutes(-1));
        var sut = createSUT();
        sut.CurrentDateTimeProvider = currentDateTimeProvider;
        sut.Start();
        //...[SNIP]
    }
}

I have kept the code to a minimum to show the important part where we stub out the ICurrentDateTimeProvider and inject it via the property on Scheduler.

The problem with this approach is that it’s a little long-winded, we have to introduce a new interface, create the real implementation and also find a way to inject the dependency into the class were testing against.

There is a really nice way I came across recently that gets round these issues it was while reading ayende’s blog, the code needed is incredibly small but gives us a lot:

public static class SystemTime
{
    public static Func Now = () => DateTime.Now;
}

This gives us one place to go to for date and time so no injection needed, it also provides us with the real date and time and allows us to control what should be returned. Code wanting to get the current date and time would use this:

var currentDateTime = SystemTime.Now();

Code wanting to change what is returned i.e. out test code would do so like this:

SystemTime.Now = () => new DateTime(2009,1,1);

Very neat and requires less work than the former way. In the next post we will look out dealing with testing multi-threading code.

Spaghetti code? No I dont think so

I just wrote this while working on the IssueTracker.NET project:


<tr>
<th>
        - </th>
</tr>
<tr>
<td>
       </td>
</tr>

Now some will look at this and be thinking eurgh!… why is he writing classic ASP style spaghetti code and that’s the point, since when did writing code in the page == spaghetti code? I believe that spaghetti code originated because of the shortcomings of ASP 3.0 not allowing us to separate UI concerns from other concerns, but we don’t have this problem in ASP.NET we can quite nicely have our seperate objects in other layers deal with persistence, domain etc… and the code on our pages can deal just with what they are supposed to the UI.

This is why when I look at the code above I don’t think eurgh! because it’s not dealing with anything other than concerns of the UI and in the case above displaying any comments assigned  to the current issue and in my opinion it reads quite well.

NHibernate & Null Object Pattern: The Options

Don’t bother using Null Object Pattern

The first option is to just not bother using Null Object Pattern, this is the easiest solution however has the side-effect that you end up with null checks everywhere which is the reason for moving to the Null Object Pattern in the first place.

Place a Null Object in the database

Next option is to have an object in the database that represents the null object so it will probably have an Id of zero and a value of << Unassigned >> or along those lines. This then has its own problems because if it’s a user editable object you don’t really want them to be able to change/delete this data so it becomes a special case that will need to be locked for editing/deleting.

Use Field Access and have the Property Handle the Mismatch

This is my preferred method whereby NHibernate is configured to use field access to the object, and the property handles the mismatch internally for example:

// inside class definition
protected User assignedTo;

public virtual User AssignedTo
{
    get
    {
        return assignedTo ?? User.NotAssigned;
    }
    set
    {
        if (value == User.NotAssigned)
            assignedTo = null;
        else
            assignedTo = value;
    }
}

This gives NHibernate a different view of the assigned to value than outside objects, for NHibernate which uses the internal field assignedTo it can be set to a null however for outside objects that have to use the AssignedTo property it will never be a null and instead will be set to the Null Object in this case User.NotAssigned.

Any other options please add a comment below 🙂