The autistic coder - Andreas Öhlund's blog

world.Publish(new BlogPost());

I've just committed support for StructureMap to the NServiceBus trunk so if you are using NSB and prefer StructureMap as your IoC-Container you can get the latest NSB build from teamcity.codebetter.com (thanks Udi for trusting me as a committer)

To configure NSB to use StructureMap use the following syntax:

var bus = Configure.With()


   .StructureMapBuilder()


   .MsmqSubscriptionStorage()


   .XmlSerializer()


   .MsmqTransport()


       .IsTransactional(true)


       .PurgeOnStartup(false)


   .UnicastBus()


       .ImpersonateSender(false)


   .CreateBus()


   .Start();



If you are using an explicit instance of the container it can be passed to the builder like this:




var container = new Container();


 


var bus = Configure.With()


   .StructureMapBuilder(container)


   ...



The bus itself is added to the container by NSB so to get access to is in your code just add a dependency for it the usual way:




public class ClassThatNeedsAccessToTheBus


{


    private readonly IBus bus;


 


    public ClassThatNeedsAccessToTheBus(IBus bus)


    {


        this.bus = bus;


    }


    public void PerformSomeLogic()


    {


        bus.Publish(new WhatEverEvent());


    }


}



And to fill your message handlers with your own dependencies just configure them in SM and add them as constructor or setter dependencies :




public class MyMessageHandler:IMessageHandler<WhatEverEvent>


{


    private IRepository repository;


 


    public MyMessageHandler(IRepository repository)


    {


        this.repository = repository;


    }


 


    public void Handle(WhatEverEvent message)


    {


        repository.Save(message);


    }


}





Edit: You can also configure dependencies using NServiceBus own syntax , more on that here.



If you have any troubles, suggestions etc. let me know directly or post them to the NSB group.

In this post I will demonstrate a way to automatically manage a UnitOfWork (UoW) for Windows Communication Foundation (WCF) service requests. This is the equivalent of “Session per request” that is popular for Web applications. The reason for all this is to move transaction management out of user code resulting in cleaner and more maintainable applications.

The semantics of my UoW is the following, for each request to my WCF service:

    1. Create a new UoW and initialize it
    2. Cache the UoW in StructureMap for the duration of the request
    3. Commit and dispose the UoW when the request finishes
    4. Rollback the UoW if the service throws an exception

My interface for the UoW looks like this:

   1:  public interface IUnitOfWork : IDisposable


   2:  {


   3:      void Initialize();


   4:      void Commit();


   5:      void Rollback();


   6:  }



 


To do all this we need the following infrastructure.





    1. Basic StructureMap integration for WCF


    2. A way to cache objects for the duration of the service call


    3. Integration between the cache StructureMap


    4. Some hooks in WCF to allow us the Initialize and commit the UoW


    5. Another hook to detect exceptions and rollback the UoW




Let’s taka a closer look at how we can’t implement all this.



Basic StructureMap integration for WCF



This is a solved problem so I wont go into the details (Jimmy Bogard has an excellent post on the subject). Basically this means creating a “ServiceHostFactory” which in the end allows us to specify our own “instance provider”. Using this provider we can use StructureMap to instantiate the reuested instances.



Building a WCF per request cache



To enable caching I decided to cache objects in the WCF InstanceContext. The instance context is isolated for each service instance. This means that we must make sure that WCF creates a new Instance for each call (the default is one Instance per session). This is easily done by adding the following to our service implementations:





   1:  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]



Ok, but how do we cache stuff in the InstanceContext? Unfortunately WCF doesn't provide any collection like HttpRequest.Current.Items so we have to use the extensibility hooks in WCF to solve the problem. In this case we add our own Instance extension that can handle the caching for us. This is done by creating  a class that implements IExtension<InstanceContext>. The implementation looks like this:





   1:  public class WCFContextCacheExtension : IExtension<InstanceContext>


   2:  {


   3:      private MainObjectCache cache;


   4:   


   5:      public IObjectCache Cache


   6:      {


   7:          get { return cache; }


   8:      }


   9:   


  10:      public static WCFContextCacheExtension Current


  11:      {


  12:   


  13:          get


  14:          {


  15:              return OperationContext.Current.


  16:                  InstanceContext.Extensions.Find<WCFContextCacheExtension>();


  17:          }


  18:   


  19:      }


  20:      public void Attach(InstanceContext owner)


  21:      {


  22:          cache = new MainObjectCache();


  23:      }


  24:   


  25:      public void Detach(InstanceContext owner)


  26:      {


  27:   


  28:      }


  29:  }



Note that I’m using the MainObjectCache from StructureMap as the store for my cached objects, the reason for this will be explained when we take a look at how this can be integrated with StructureMap. I’ve also added a convenience method that finds the extension from the InstanceContext. But how do we make sure that our extension is added to every new Instance?



My approach is to implement a “InstanceContextInitializer” which is added to the dispatch runtime. This is accomplished with this modification to my StructureMap WCF integration:





   1:  ed.DispatchRuntime


   2:     .InstanceContextInitializers


   3:        .Add(new InstanceContextCacheInitializer()); 



The implementation of the InstaceContextInitializer is trivial:





   1:  public class InstanceContextCacheInitializer : IInstanceContextInitializer


   2:  {


   3:      public void Initialize(InstanceContext instanceContext, Message message)


   4:      {


   5:          instanceContext.Extensions.Add(new WCFContextCacheExtension());


   6:      } 


   7:  }



Ok, now that we have a way to cache objects in the InstanceContext lets see how we can integrate this with the StructureMap way of caching instances .



A WCFInstanceContextCache for StructureMap



Extending StructureMap with a custom caching solution is done by implementing your own “lifecycle”. (Here is an indepth discussion of scoping in StructureMap.)



In this case our custom lifecycle would look like this:





   1:  public class WCFInstanceContextLifecycle : ILifecycle


   2:  {


   3:      public void EjectAll()


   4:      {


   5:          FindCache().DisposeAndClear();


   6:      }


   7:   


   8:      public IObjectCache FindCache()


   9:      {


  10:          return  WCFContextCacheExtension.Current.Cache;


  11:      }


  12:  }



As you can see StructureMap requires our cache to implement the IObjectCache interface hence the use of MainObjectCache above. Noting magic here we just fetch the cache from our InstanceContext extension and let StructureMap do the rest.



The will enable us to configure StructureMap like this in order to cache objects for the duration of a service call:





   1:  x.ForRequestedType<IUnitOfWork>()


   2:       .LifecycleIs(new WCFInstanceContextLifecycle())


   3:       .AddConcreteType<TestUnitOfWork>();



Now that we have a way to cache our UoW for the duration of each service call we can move on to making sure that the UoW is initialized and committed automatically for each request.



How to manage the UoW on a Per request basis



To enable us to automatically initialize and commit our UoW we need a way to hook up to the WCF call pipeline. This is done by adding a custom IDispatchMessageInspector (a deeper explanation of MessageInspectors is found here).



To enable us to add message inspectors easily I've added the following feature to my StructureMap WCF integration:





   1:  foreach (var messageInspector in container.GetAllInstances<IDispatchMessageInspector>())


   2:  {


   3:      ed.DispatchRuntime.MessageInspectors.Add(messageInspector);


   4:  }



This gives me an easy way to add MessageInspectors just by configuring them in StructureMap.





   1:  x.ForRequestedType<IDispatchMessageInspector>()


   2:      .AddConcreteType<UnitOfWorkMessageInspector>();



 



With this in place it’s easy to implement my own “UnitOfWorkMessageInspector” that hooks up to WCF and performs the work. This looks like this:





   1:  public class UnitOfWorkMessageInspector: IDispatchMessageInspector


   2:  {


   3:      private readonly IContainer container;


   4:   


   5:      public UnitOfWorkMessageInspector(IContainer container)


   6:      {


   7:          this.container = container;


   8:      }


   9:   


  10:      public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)


  11:      {


  12:          var unitOfWork = container.GetInstance<IUnitOfWork>();


  13:   


  14:          Debug.WriteLine("Before invoke");


  15:          unitOfWork.Initialize();


  16:   


  17:          return null;


  18:      }


  19:   


  20:      public void BeforeSendReply(ref Message reply, object correlationState)


  21:      {


  22:          var unitOfWork = container.GetInstance<IUnitOfWork>();


  23:   


  24:          Debug.WriteLine("After invoke");


  25:          unitOfWork.Commit();


  26:          unitOfWork.Dispose();


  27:      }


  28:  }



As you can see we Initialize, Commit and Dispose the UoW for each “Message” going in and out of our service.



Notes:




  • BeforeSend reply will still be invoked even if the operation is “OneWay”.


  • As you can see we always commits, this works because the implementations of IUnitOfWork is required to always start a new transaction after commit and rollback. This is to allow user code to perform manual commits and rollback. This feature is also required to enable other errorhandlers to update application state if needed. (more on this below)



Ok, so far so good. Lets look at the final piece of the puzzle. The rollback…



Rollback the UoW if the service call throws an exception



By now you’ll probably guess how this will be done:) WCF is extensible beyond belief. First we add some more code that allows us to autoregister WCF Errorhandlers through StructureMap.





   1:  foreach (var errorHandler in container.GetAllInstances<IErrorHandler>())


   2:  {


   3:      cd.ErrorHandlers.Add(errorHandler);


   4:  }



With this in place we can configure a custom “UnitOfWorkErrorHandler” that can perform the rollback in case of an exception. The fact that we are resolving the errorhandlers using StructureMap means that we can have the container itself injected into them if necessary.





   1:  public class UnitOfWorkErrorHandler : IErrorHandler


   2:  {


   3:      private readonly IContainer container;


   4:   


   5:   


   6:      public UnitOfWorkErrorHandler(IContainer container)


   7:      {


   8:          this.container = container;


   9:      }


  10:   


  11:      public void ProvideFault(Exception error, MessageVersion version, ref Message fault)


  12:      {


  13:          var uow = container.GetInstance<IUnitOfWork>();


  14:   


  15:          Debug.WriteLine("Rolling back UoW");


  16:   


  17:          uow.Rollback();


  18:      }


  19:   


  20:      public bool HandleError(Exception error)


  21:      {


  22:          return false;


  23:      }


  24:  }



But why are you not injecting the IUnitOfWork directly?



The reason for this is that there is no ongoing call when the error handler is instantiated so the cache wouldn't work (We are storing the cache in the active service instance remember). The workaround would be to add some kind of “lazy dependency” feature to StructureMap that would instantiate our UoW the first time it’s accessed. But until then will just use the container directly.



The fact that a new transaction is started after rollback enables the other errorhandlers to perform custom business logic that requires an active transaction eg. logging to a database, publishing events to an service bus etc. ( remember that the  “new UoW transaction” is going to be committed by the message inspector above)



Summary



Phew, we are finally done. WCF and StructureMap is really easy to extend. There is a lot of extensions required for this to work but I like the fact that each extensions does its thing and thereby adhering to Single Responsibility Principle. Having the infrastructure managing your UoW is a great way to keep your code clean and minimizes the risk of “forgetting” transaction management.



Resources



The code for the StructureMap WCF Integration can be found here.



A test that shows the configuration and usage of the UoW is here



And the code for the WCF UoW is here



Jimmy Bogard has written a post about this (but it turned out to have some threading problems but It got me stared down the right path)



Donald Belcham at igloocoder.com has posted some info on the subject



AltOxite has a great UoW implementation for Fluent NHibernate that I have shamelessly copied :)



As always comment, suggestions etc is most welcome!

Writing integration tests with tools like WatiN usually involves a lot of "magic strings" which makes the tests very fragile and refactoring unfriendly. This leads to tests that are hard to maintain and as the project moves on they end up being commented out or not being run at all. There are two ways to produce integration test for web applications with tools like WatiN , Selenium etc.

1. Record the tests with a recorder

2. Write the tests using code.

I prefer #2 because this lets me to produce my tests before the functionality is done. (Integration tests TDD-style) The technique described in this post apply to method #2.

So how can we produce more robust tests using Asp.Net MVC and WatiN?

Lets explore how we can combine strongly typed views and forms in Asp.Net MVC with some “Lambda-fu” to help us write refactoring friendly WatiN tests.

The benefits we get is when we refactor controller actions, view data and user input our integration test will automatically be updated to reflect the changes. Another benefit is that you can write you integration tests in true TDD-style and let Resharper generate the code for you. ( Remember, Alt +  Enter is your best friend!)

Enough talk, time for some code!

Binding to controller actions

The idea here is to use lambda expressions to bind our tests to controller actions and then infer the Url from the class and method names of the controller. The following test demonstrates this

[Test]


public void Can_execute_action_with_arguments()


{


    var productsController = new ControllerProxy<ProductsController>(browser);


 


    productsController.ExecuteAction(x => x.Edit(123));


 


    browser.AssertWasCalled(b => b.GoTo(http://localhost/Products/Edit/123));


}







As you can see we create a “ControllerProxy” for the Asp.Net MVC controller called ProductsController and then executes the “Edit” action passing the parameter value “123”. The browser object that is passed to the proxy is the WatiN -  IBrowser interface that abstracts the different supported browsers (IE and Firefox). This makes is easy to run the integration tests for both browsers.



The code in controller proxy looks like this:




public ControllerProxy<CONTROLLERTYPE> ExecuteAction(Expression<Func<CONTROLLERTYPE, Object>> expression)


{


    var methodCall = (MethodCallExpression)expression.Body;


    var url = BuildUrlFromControllerAction(methodCall.Method.Name);


 


    foreach (var argument in methodCall.Arguments)


        url += "/" + argument;


 


    browser.GoTo(url);


 


    return this;


}



As you can see we generate the correct url from the controller name and the specified action. Then we append the action parameters and finally tell WatiN to browse the url.



I wont bore you with the rest of the code but if you are interested it can be found here.



Validating view data



Ok, now that that we can execute controller actions in a strongly typed manner wouldn't it be nice if we could validate the resulting view (if of course the action results in a rendered view). This can be easily achieved if you use Asp:net MVC support for strongly typed views (if you don't, you really should! Ayende shares my position in this matter :)



This test demonstrates how we can assert that the rendered view contains expected values.




[Test, ExpectedException(typeof(AssertionException))]


public void Enable_validation_of_view_data()


{


    var productsController = new ControllerProxy<ProductsController>(browser);


 


    var mockTextBox = MockRepository.GenerateMock<IElement>();


 


    browser.Stub(b => b.Element("Name")).Return(mockTextBox);


 


    mockTextBox.Stub(textbox => textbox.Text).Return("Not the name we expected");


 


    productsController.AssertViewData<CreateViewModel>(x=>x.Name == "Expected name");


}



Here the call to “AssertViewData” binds to the ViewModel called “CreateViewModel” and then makes sure that the property value of “Name” is “Expected Name” (which in this test it’s not and a AssertionException is raised). This solution has a potential flaw in that is expects you to generate the html input control with the id “Name”. The way to solve this is to use a view engine or view helpers that allows you to bind your html controls directly the view model property. My personal favourite is FluentHtml which allows you to use he following syntax:




<%= this.TextBox( x=>x.Name) %>


 


instead of:


 


<%= Html.TextBox("Name") %>



 



User input and submitting forms



By utilizing Asp.Net MVC support for strongly typed user input we can add support for a “magic string free” way of inputting and submitting data using WatiN. Firsts lets look at a controller action that accepts strongly typed data




[AcceptVerbs(HttpVerbs.Post)]


public ActionResult Create(CreateProductForm userInput)


{



In this example “CreateProductForm” contains a “Name” and a “Price” property that the user inputs. When the form is submitted Asp.Net MVC’s model binders automatically binds the submitted data to the above properties. Let see how we can handle this scenario using our controller proxy (I talked about this in my previous post)




[Test]


public void Can_submit_formdata()


{


    var productsController = new ControllerProxy<ProductsController>(browser);


 


    var mockedTextBox = MockRepository.GenerateMock<ITextField>();


 


    browser.Stub(e => e.Element("Name")).Return(mockedTextBox);


    browser.Stub(e => e.Element("Price")).Return(mockedTextBox);


 


    IForm mockedForm = MockDefaultForm();


 


 


    productsController.SubmitForm<CreateProductForm>(form =>


                                                         {


                                                             form.Name = "Product name";


                                                             form.Price = 100.0;


                                                         });


 


    mockedTextBox.AssertWasCalled(x => x.Value = "Product name");


    mockedTextBox.AssertWasCalled(x => x.Value = "100");


    mockedForm.AssertWasCalled(x => x.Submit());


}



Behind the scenes we extract data from our “form” object and use WatiN to simulate the user input to the browser. And finally we submits the form.



Conclusion



Combining the above we can write strongly typed integration test for the creation of an article in an online cash register like this:




controller.ExecuteAction(x => x.CreateArticle())


    .SubmitForm<CreateArticleCommand>(formData =>


                                          {


                                              formData.Price = 100.0;


                                              formData.Name = articleName;


                                              formData.ArticleNumber = "123123";


                                          })


    .AssertViewData<ViewArticleViewModel>(viewData => viewData.Name == articleName);



 



I hope this post will give you some ideas on how to use lambdas and the strongly typed way of programming Asp.Net MVC to help you write more robust and refactoring friendly integration test using WatiN. This technique will also work with other MVC frameworks such as Fubu Mvc etc.



Source can be found here if you are interested.



As always comments and suggestions are welcome!

I'm currently playing around with Asp.Net MVC for a private little "pet-project" and I'm amazed how easy it is to make Ajax calls using jQuery!

I'm currently implementing the following story:

As a user I want to search for available rooms in order to make a reservation

So my web page would look something like this: (obviously I'm not a web designer:)

image

And when the user clicks the search button an Ajax call will be made to the server which returns a list of available rooms. After the call the page will look like this:

image

jQuery Code

The call is easily made with the jQuery $.getJSON - method. Lets look at the JavaScript that is executed when the user clicks the "search" - button

$("#btnSearch").click(function() {
//users room requirements
var roomRequriements = {
"requirements.From": $('#fromDate').attr("value"),
"requirements.To": $('#toDate').attr("value")
}

//clear table
$("#availableRooms tbody").html("");
$.getJSON(
"/Booking/FindRooms", roomRequriements, function(rooms) {
$.each(rooms,
function(i, room) {
var row = $("<tr/>").attr("id", room.Id);

$(
"<td/>").html(room.Type).appendTo(row);
$(
"<td/>").html(room.Description).appendTo(row);
$(
"<td/>").html(room.Price).appendTo(row);
$(
"<td/>").html($("<input type='radio'/>").attr("id","radio" + i)).appendTo(row);

$(
"#availableRooms tbody").append(row);
});
});

$(
"#availableRooms").trigger("update");
return false;
});







The first argument to getJSON is the URL that is going to get our call. If you are familiar with Asp.Net MVC you'll know that "/Booking/FindRooms" will be routed to the FindRooms - method on a class called BookingController.



The second is a map of key/value - pairs that will be sent as parameters to the server. The name of the keys is important because the entire map will be automatically mapped to an C# object by Asp.Net -MVC (more on this later).



The third is the callback that will execute when the call returns. As you see I'm iterating over some kind of magical object called "rooms" and for each "room" I'm adding a new row to my list of rooms that the user can choose from.



Where did that magical "rooms" object come from?



The "rooms" object is representing the returned data that our server sent in response to our call. In our case the server sent an IList<Room> serialized as JSON back to us. To explain this further we must look at the FindRooms method.



The Asp.Net MVC Code



So the user clicked the "Search"-button and a script in or browser took the entered dates and passed them as parameters to the URL /Booking/FindRooms. Asp.Net MVC received the call and routed it to a method on BookingController called FindRooms. Lets se how that method looks.




public ActionResult FindRooms(RoomRequirements requirements)
{
return Json(new List<Room>
{
new Room
{
Id
= 1,
Type
="Single",
Description
="201",
Price
= 1100.0
},
new Room
{
Id
= 2,
Type
="Single",
Description
="301",
Price
= 1000.0
}
});
}



Is that all??



Yes, and that's why I love Asp.Net MVC! ( you can write soooo clean code and the support for TDD is amazing!)



Remember those strange keys in the map that was sent as parameters? (requirements.From,requirements.To)



By using those keys Asp.Net MVC figured out how to deserialize that into the required "requirements"-parameter that our FindRooms -method expects. ("RoomRequirements" has two properties "To" and "From"). This means that we can keep our C#-code clean from "magic"-strings and let Asp.Net MVC get the parameters out of the request in a strongly typed manner. This is achieved be something behind the scenes called ModelBinders more on that here.



Data is returned back to the caller serialized in JSON by the Json method of the Controller (the MVC base-class for all controllers).



Ok, a list of Room-objects was sent back to the client in JSON-format. Can that explain those magical "rooms" and "room"-objects?



It sure can!! As you would guess the method getJSON is expecting JSON formatted data back from the call to the server. When this happens jQuery automatically deserialize's the data to corresponding Javascript objects. So "rooms" was serialized to a list of "room"-objects. We iterated the list using jQuery's $each -function and created our row using room.Type, room.Name etc.



Conclusion



jQuery and Asp.Net MVC helps us to write powerful and clean code with just a few lines. And as a bonus it helps us to keep our "magical - strings" usage low.



Hey, what about all that TDD - stuff you force us to do at work. Don't you do it on your hobby projects?



Of course I used TDD for this. (Yes, I should use QUnit to TDD the JavaScript, I'll do that next time , promise! :)



Lets see how we can test our controller action with just a few lines of test code:



[Test]
public void Find_avaliable_rooms()
{
var controller
= new BookingController();
DateTime to
= DateTime.Today;
DateTime from
= DateTime.Today.AddDays(1);

var model
= controller.FindRooms(new RoomRequirements {From = from, To = to})
.AssertResultIs
<JsonResult>()
.AssertPayloadIs
<IList<Room>>();

Assert.That(model.Count, Is.EqualTo(
2));
Assert.That(model[
0].Id, Is.EqualTo(1));
Assert.That(model[
0].Type, Is.EqualTo("Single"));
Assert.That(model[
0].Description, Is.EqualTo("201"));
Assert.That(model[
0].Price, Is.EqualTo(1100.0));

}


Asp.Net MVC is really easy to unit test. In the code above I just create my controller. Invoke the "FindRooms" - method and make sure it return a JsonResult in which the payload is a list of rooms.



Note: AssertResultIs is a method from MVCContribs TestHelpers and AssertPayloadIs is one of my own helpers.



Phew, long post, must sleep now....

I decided to try this new "Twitter thing"... You can follow me on twitter here.

James Shore has an excellent article on how you will fail with Scrum and other agile methodologies if you don't to realize the importance of engineering practices such as XP, TDD, Automated Acceptance tests etc. If you don't you'll probably end up with an ever increasing amount of technical debt that is going to fail your project. (hmm, increasing debt seems to be the theme this year:) )

One part that got me laughing was Ken Schwabers analogy about Scrum and your mother-in-law

"Scrum is like your mother-in-law," Ken Schwaber said at the recent Agile Vancouver conference. "It's constantly pointing out your shortcomings."

Having practiced Scrum for a while I must agree that this statement is spot on!

Just for the record: This is of course not true for my mother-in-law :) *** Gun against my head ***

Tonight Alt.Net-Sundsvall had it's first meeting. We held a coding dojo where we practiced the famous Bowling Game kata. It was a really good time and a perfect way to share and learn knowledge about, TDD, OO-design, Resharper etc.

Lessons learned

  • Make sure everyone knows the problem domain (in our case the rules of bowling)
  • Only code enough to satisfy the unit tests. We ended up with far to complex implementation in the beginning and had to refactor allot
  • Order food as soon as possible. "A hungry developer is a crappy developer" :)

Images from the epic event can be found here.

And finally a big thanks to Steria for letting us use their office.