Archive for November, 2009

The TFS Merge Dance

Wednesday, November 11th, 2009

We do a lot of branching and merging at work using TFS. Merging can be difficult at times but here is a simple check list that we have come up with over time that we follow to reduce the headache a little – I still hate merging though!

Verify The Trunk Is Good

  1. Get latest on the trunk.
  2. Open up the trunk solution.
  3. Build the trunk solution.
  4. Run all the tests on the trunk. If you get any failed tests find out who to hit.
  5. Verify The Branch Is Good

  6. Get Latest on your branch.
  7. Open up solution.
  8. Build solution.
  9. Run all the tests and make sure everything is green.
  10. Forward Integrate

  11. Merge from trunk -> branch.
  12. Resolve issues in your branch – Build solution.
  13. Run tests again – repeat items 6 & 7 till you get green lights.
  14. Check in your merged changes.
  15. Check the Pending Changes window at this point to make sure that TFS has actually checked in everything ok.
  16. Merge Back To Trunk

  17. Merge from branch -> trunk.  If you get any merge conflicts at this stage you can safely copy from source to target for *.cs files. Project and configuration files should be merged manually.
  18. Get latest on trunk.
  19. Build the trunk solution.
  20. Run tests on trunk. Fix up any problems and repeat step 18 till you get green lights.
  21. Check in the merged changes.
  22. Check the Pending Changes window at this point to make sure everything is checked in ok.

Everything should all be good now

Inversion of Control and StructureMap: Part 1

Tuesday, November 10th, 2009

I’ve been asked at work to provide some documentation to the other guys on the team around Inversion of Control and how we should be using StructureMap on our projects. Nothing in these upcoming blogs is revolutionary or new and there is nothing that you couldn’t from countless other sources but I thought I would share it anyway. I hope its of use.

What is StructureMap?

StructureMap is an Inversion Of Control container. There are a few out there but essentially they all do the same thing:

  • StructureMap
  • Windsor Castle
  • Spring.Net
  • AutoFac
  • Unity
  • Ninject

Before we delve too much into the specifics of StructureMap I thought we should start with a little refresher course on Dependency injection and Inversion of Control.

What is Inversion Of Control?

Consider the following code:


class Class1
{
   public void SomeMethod()
   {
      var class2 = new Class2();

      class2.SomeOtherMethod();
   }
}

Class1 is always (tightly) coupled to Class2. Even if we wrap Class2 with an interface we are still coupled to the concrete implementation of Class2. Because Class1 creates our implementation of IClass2


class Class1
{
   public void SomeMethod()
  {
     IClass2 class2 = new Class2();

     class2.SomeOtherMethod();
  }
}

How do we get around this coupling? If Class1 doesn’t create Class2 but is given an instance of an object that is already created using its interface then Class1 will no longer be coupled to Class2.

We can pass into Class1 whatever implementation of IClass2 we want it could be the real implementation of Class2 or it could be a mock object. It can be anything we want it to be we have total freedom now.

When a class no longer creates the dependant classes it requires to do its work but is given them this is called dependency injection. We can do this in two ways using either the  Constructor or using properties.

In general constructor injection is the preferred approach, although there are times when you will need to use property injection. Class1 below has been refactored so that we now use constructor injection.


class Class1
{
   private readonly IClass2 _class2;

   public Class1(IClass2 class2)
   {
      _class2 = class2;
   }

   public void SomeMethod()
   {
      _class2.SomeOtherMethod();
   }
}

Poor Man’s Dependency Injection

So if we don’t create our dependencies in our classes anymore where do we create them? One solution is to use what is known as poor man’s dependency injection (PMDI), which is a technique where we incorporate two constructors on our class. One that injects our dependencies in through the constructor and a default constructor that creates the concrete implementations of our dependencies for us.

In our normal code we would use the default constructor but in our tests we would inject our mocks in through the testing constructor. See our refactored Class1 with that uses poor man’s dependency injection implemented.


// Testing Constructor – our dependencies can be
// injected using this constructor.
public Class1(IClass2 class2)
{
   _class2 = class2;
}

// Default Constructor – Our dependencies are created
// using this constructor.
public Class1():this(new Class2())
{
}

PMDI is great for implementing inversion of control for legacy code as it provides you with a way to decouple your code and test whilst limiting the extent of your refactoring because you are keeping your existing (default) constructor and hence are not breaking any existing code that depends on that class.

Why Don’t We Use Poor Man’s Dependency Injection All The Time?

Poor man’s dependency injection work’s ok, on smaller projects and as I said with legacy code. However what you find is that on larger projects with complex dependency graphs things can get out of control pretty fast and things can start hurting.

Consider the following scenario: ClassA has a dependency on ClassB, which in turn has a dependency on ClassC which in turn has a dependency on ClassD… ok you get the idea..All of a sudden the constructor for ClassA looks like this:

class ClassA
{
   public ClassA():this(new ClassB(new ClassC(new ClassD(new ClassE()))))   {}

   public ClassA(IClassB classB){}
}

Pretty ugly isn’t it. all the other classes would have equally nasty and complex constructors also. Now consider what would happen if I changed the signature of ClassE so that it now took an connection string.  This would mean that I would have to change the constructors on Classes A, B, C and D. Now all of a sudden dependency injection doesn’t seem like such a great idea and you want to strangle the guy that first ever suggested using it…and remember this is only for a trivial example.

IOC Container To The Rescue

An IOC container such as StructureMap handles these complexities and does all the heavy lifting for you.

The container knows about your interfaces and the concrete classes that implement those interfaces. It knows how to instantiate your objects in your domain and resolve their dependencies for you. It doesn’t matter how complex the dependency graph is any more because your IOC container will do it all for you. Once you start delving into IOC containers you realize that they can do loads of other cool things too but I’ll save that for later..

IIS 6 Binding Error

Monday, November 9th, 2009

I’ve just been playing around with IIS until finally I couldn’t start my web site as each time I got the following exception:

The virtual site ’1′ has been invalidated and will be ignored because valid site bindings could not be constructed, or no site bindings exist.

It turned out that I had broken the IIS Bindings.

To get it working again I had to do the following:

  1. Right click on the web site properties
  2. Navigate to the Web site tag.
  3. Select the Advanced Button.

In the end the settings on this screen had got messed up by resetting them so that they looked like this got it working again for me.

IIS


Getting Started With NServiceBus: Part 4 Integrating With StructureMap

Wednesday, November 4th, 2009

Here are the links to the previous posts in this series:

Part 1 Unicast Messaging.
Part 2 Publishing and Subscribing.
Part 3 Sagas
Part 4 Integrating With StructureMap

Out of the box NServiceBus uses the Spring.Net framework IOC container. However if you want to integrate NServiceBus into your application this does not mean that you are limited to choosing Spring.Net as your container as NServiceBus allows you to plugin your IOC container of choice.

Currently  the Beta 2 version supports the following IOC containers.

  • Unity
  • Structuremap
  • Castle
  • Autofac

In this example I will walk you through the steps to get NServiceBus working with StructureMap.

The first thing  you must do is reference the NServiceBus.ObjectBuilder.StructureMap.dll.  If you download NServiceBus you will find this assembly in the \binaries\containers\structuremap folder. Once you have done this you can initialize your StructureMap container in pretty much the same way as you normally would. Once you have done that you can then initialize NServiceBus like this passing in the instance of your container:

           Configure.With()
                .StructureMapBuilder(container)
                .... Rest of Configuration Goes Here......

If any of your classes need to access the Bus to publish or send a message an instance of IBus must be injected into your class by your IOC container. However if you try to use constructor injection on your container, StructureMap will complain that it does not have a default instance defined for IBus especially if you have unit tests over your registry that work in isolation of NServiceBus.

The best way to get round this is on the classes that need to interact with the bus to have a public property of type IBus and use property injection to inject our instance of the Bus once NServiceBus has been initialized.

In StructureMap there are a number of different approaches to doing property injection including marking up properties with StructureMap attributes, however the technique that I favour which I unashamedly stole from Jeremy Miller’s StoryTeller project works as follows:

On the class that you wish to access the Bus you add a public property of type IBus

 public IBus Bus { get; set; }

The class should also implement the empty marker interface INeedBuildUp

Now in our StructureMap registry we should set up a rule stating that any class that has a pubic property of type IBus should be set by our IOC container.

SetAllProperties(y => y.OfType<IBus>());

Now this on its own is not enough to inject our IBus instance into our classes as we need to call the IContainer.BuildUp() method passing in our instance of that class to inject in our IBus instance.

This is where the following little extension method comes in handy that can be run from your application bootstrapper once StructureMap and NServiceBus have been initialized, which queries the IOC container for any pluginTypes that implement the INeedBuildUp interface foreach instance that is returned the BuildUp method is called on the container.

 public static void BuildUpThoseThatImplementINeedBuildUp(this IContainer container)
        {
            container
                .Model
                .PluginTypes
                .Where(p => p.Implements<INeedBuildUp>())
                .Select(x => x.To<INeedBuildUp>(container))
                .Foreach(container.BuildUp);
        }

Which in turn uses the following extension methods to do its magic..

public static bool Implements<T>(this PluginTypeConfiguration configuration)
        {
            var implements = typeof (T).IsAssignableFrom(configuration.PluginType);

            return implements;
        }

 public static T To<T>(this PluginTypeConfiguration configuration, IContainer container)
        {
            return (T) container.GetInstance(configuration.PluginType);
        }

public static void Foreach<T>(this IEnumerable<T&gt items, Action<T&gt action)
        {
            foreach (var item in items)
            {
                action(item);
            }
        }

Voila! you’ve now integrated StructureMap with NServiceBus in your application.

kick it on DotNetKicks.com

Getting Started With NServiceBus: Part 3 Sagas

Tuesday, November 3rd, 2009

Here are the links to the other posts in the series.

Part 1 Unicast Messaging.
Part 2 Publishing and Subscribing.
Part 3 Sagas
Part 4 Integrating With StructureMap

Sagas are long running business processes where state needs to be shared between message handlers.

Udi gives a much better explanation of them here and there is some more information about them on the NServiceBus Wiki here.

Imagine the following scenario for a leave approval system.

  • An employee applies for leave.
  • The request for leave must be approved by the HR manager
  • The request for leave must be approved by the employees line Manager.
  • If both the HR manager and the line manager approve the request it can then be authorized.
  • Both the HR manager and the line manager will make their decisions independently of each other.

The problem with this scenario is that we don’t know how long it is going to take for either the HR manager or line manager to make their decision and we don’t know in which order we are going to receive their decisions.

NServiceBus solves these types of problems using Sagas. Lets walk through the steps we need to go through to code up this example.

Persisting Our Saga Data

Because a Saga is a long running transaction we will most probably want to persist some data. In our leave approval Saga example if we receive a decision from the HR Manager as to whether the request for leave has been approved or rejected for a particular employee then we will want to persist that information for later when a decision from the line manager arrives.

Out of the box NServiceBus will allow you save the Saga data to a SQLite database using NHibernate. To define the data we wish to persist we are going to create a class called LeaveApprovalData. Because we are using NHibernate it important to make all the properties virtual if not you’ll probably get some exception like “Database was not configured through Database method.”. We also need to implement the ISagaEntity interface. You can see the the three important properties on this class are ApprovedByHR, ApprovedByLineManager and EmployeeName.

    public class LeaveApprovalData : ISagaEntity
    {
        #region Properties

        public virtual bool? ApprovedByHR
        {
            get; set;
        }

        public virtual bool? ApprovedByLineManager
        {
            get; set;
        }

        public virtual string EmployeeName
        {
            get; set;
        }

        public virtual bool HasBeenApproved
        {
            get
            {
                var hasBeenReviewedByAll = ApprovedByHR.HasValue
                                                       && ApprovedByLineManager.HasValue;

                return (hasBeenReviewedByAll
                                                     && (ApprovedByHR.Value
                                                     && ApprovedByLineManager.Value));
            }
        }

        public virtual bool HasBeenReviewedByAllParties
        {
            get { return ApprovedByHR.HasValue && ApprovedByLineManager.HasValue; }
        }

        public virtual Guid Id
        {
            get; set;
        }

        public virtual string OriginalMessageId
        {
            get; set;
        }

        public virtual string Originator
        {
            get; set;
        }

        #endregion Properties
    }

Writing our Saga

The code sample below illustrates how we could write a Saga in NServiceBus to process whether the leave request should be accepted or rejected.

    public class LeaveApprovalSaga :
              Saga<LeaveApprovalData>,
              ISagaStartedBy<HRLeaveApproval>,
              ISagaStartedBy<LineManagerLeaveApproval>

    {
        public IBus Bus { get; set; }

        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<HRLeaveApproval>(
                                 saga => saga.EmployeeName,
                                 message => message.EmployeeName);

            ConfigureMapping<LineManagerLeaveApproval>(
                                 saga => saga.EmployeeName,
                                 message => message.EmployeeName);
        }

        public void Handle(HRLeaveApproval message)
        {
            Data.EmployeeName = message.EmployeeName;
            Data.ApprovedByHR = message.Approved;

            Process(Data.EmployeeName);
        }

        private void Process(string employeeName)
        {
            if (Data.HasBeenReviewedByAllParties == false) return;

            if (Data.HasBeenApproved)
            {
                LeaveApproved(employeeName);
            }
            else
            {
                LeaveRejected(employeeName);
            }
        }

        public void Handle(LineManagerLeaveApproval message)
        {
            Data.EmployeeName = message.EmployeeName;
            Data.ApprovedByLineManager = message.Approved;

            Process(Data.EmployeeName);
        }
    }

Lets start by looking at what the code is doing.

The first thing to note is that we have to inherit from the generic base class Saga which is closed with our

LeaveApprovalSaga data class.  This tells NServiceBus that we will persist an instance of the LeaveApprovalSaga for each saga.

Starting Our Saga

Our Saga can be started in either two ways by either a LineManagerLeaveApproval or a HRLeaveApproval message. We define this in code by implementing the following interfaces:

ISagaStartedBy<HRLeaveApproval>, ISagaStartedBy<LineManagerLeaveApproval>

We can receive either a LineManagerLeaveApproval or a HRLeaveApproval message in any order for a particular request which can start a new Saga.

However we don’t always want to start a new Saga. If for example we received an HRLeaveApproval message for the employee called Tom and then an LineManagerLeaveApproval for the same employee we would not want to create a new Saga for the second message but retrieve the original one.

So how do we tell NServiceBus to retrieve an existing Saga for a given message type? By overriding the method ConfigureHowToFindSaga and calling the method ConfigureMapping. In the example below we are stating that when we receive a HRLeaveAproval message we will look for any previously started Saga data based on our message’s  EmployeeName property. We do the same for any incoming LineManagerLeaveAproval messages to.  If either message type comes in for an employee it will start off a new saga, from then on the saga will be retrieved from the database.

        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<HRLeaveApproval>(
                                    saga => saga.EmployeeName,
                                    message => message.EmployeeName);

            ConfigureMapping<LineManagerLeaveApproval>(
                                    saga => saga.EmployeeName,
                                    message => message.EmployeeName);
        }

Handling our Messages

Handling our messages in our Saga is very similar to implementing a normal message handler in NServiceBus when we inherit from the ISagaStartedBy<T>  interface we need to implement a Handle(T) method on our Saga.

The main difference between a normal MessageHandler is that we want to pull out the relevant data from our incoming message and persist it in our SagaData. We can do this by accessing it through the Data property on the Saga. In the example above for the handler code for  LineManagerApproval message we firstly update our Saga with the name of the employee and then update whether or not the line manager has approved the request for leave. This is automatically persisted to our SQL Lite database.

Configuring Your Host To Run The Saga


1) Reference NServiceBus.dll & NServiceBus.Core.dll. I’m using StructureMap as my IOC container so I have also referenced the NServiceBus.ObjectBuilder.StructureMap.dll as well.
2)
In your Bootstrapper you need to configure NServiceBus.

Configure
                .With()
                .StructureMapBuilder(container)
                .XmlSerializer()
                .MsmqTransport()
                .IsTransactional(true)
                .PurgeOnStartup(false)
                .UnicastBus()
                .LoadMessageHandlers()
                .ImpersonateSender(false)
                .Sagas()
                .NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration()
                .CreateBus()
                .Start();

3) In the Application Config add the following


4) Now define the Host’s Input Queue and the Error Queue – where undelivered messages are put if there is an exception delivering the message in the config file


That’s it you’ve implemented your first Saga in NServiceBus!

kick it on DotNetKicks.com

Using RhinoAutoMocker with Property Injection.

Tuesday, November 3rd, 2009

I am a big fan of using StructureMap’s Automocker when unit testing as it stops me writing a lot of repetitive code.

If you haven’t used it before go and have a look, all you need to do is download StructureMap from here and reference the StructureMap.AutoMocking.dll.

What does an AutoMocking container do? Well consider the following class.

        public ExampleClass(IDependency1 dependency1, IDependency2 dependency2)
        {
            _dependency1 = dependency1;
            _dependency2 = dependency2;
        }

If we wanted to test this class we would most probably use our Mocking framework to create mocks for our dependencies and inject them into the class. This is fine buts its repetitive coding. When you use an Automocking container it looks at the constructor for you and creates the mocks for you saving you all that effort.

Derik Whittaker has a much better post on why you should use an AutoMocker here..

Anyway there is one thing that RhinoAutoMocker doesn’t do and is allow you inject your dependencies into a class using property injection. Now 99% of the time I would recommend using constructor injection however there are times when your IOC container won’t know the whole dependency chain at the time of your object creation and must inject it at a later stage..Anyway that sounds like the topic for another post.

So if you want to use RhinoAutoMocker and still be able to set any dependencies using property injection here is an extension method that will allow you to do this.

  public static void RegisterPropertyDependency<TARGETCLASS, TProperty>(
            this RhinoAutoMocker<TARGETCLASS> autoMocker, Expression<Func<TARGETCLASS, TProperty>> expression)
            where TARGETCLASS : class
        {
            var body = expression.Body as MemberExpression;

            if (body != null)
            {
                // Work out the type from our expression tree.
                var propertyInfo = (PropertyInfo) body.Member;
                var propertyType = propertyInfo.PropertyType;

                // We know the property type now so
                // we can create a Stub of it using Rhino Mocks.
                var mockDependency = MockRepository
                                   .GenerateStub(propertyType, null);

                // inject in our stub.
                autoMocker.Inject(propertyType, mockDependency);

                var propertyName = propertyInfo.Name;

                var classUnderTestType = autoMocker.ClassUnderTest.GetType();

                var dependencyPropertySetMethod = classUnderTestType.GetProperty(propertyName).GetSetMethod();

                dependencyPropertySetMethod
            .Invoke(autoMocker.ClassUnderTest, new[] {mockDependency});
            }
        }

Now consider our example class again with its second dependency being injected through a property.

    class ExampleClass
    {
        private readonly IDependency1 _dependency1;

        public ExampleClass(IDependency1 dependency1)
        {
            _dependency1 = dependency1;
        }

        public IDependency2 Dependency2 { get; private set; }
    }

To test test this class we need to tell the AutoMocker that the property is to be used for property injection like so.


        var autoMocker = new RhinoAutoMocker<ExampleClass>();

        automocker.RegisterPropertyDependency(classUnderTest =>  classUnderTest.Dependency2);

Now we can access the mock object to set its behavior through the Auto mocker as we would any other dependency created by the Auto mocker.


        var autoMocker = new RhinoAutoMocker<ExampleClass>();

        automocker.Get<IDependency2>()
                        .Stub(x =>  x.SomeMethod())
                        .Return(true);

Formatting an Xml String

Tuesday, November 3rd, 2009

Here is a useful bit of code for formatting a piece of xml as a string with all those nice indents..I find it useful when i have to log messages etc..

public static class XmlStringFormatter
    {
        ///

        /// Returns formatted xml string (indent and newlines) from unformatted XML
        /// string for display in eg textboxes.
        /// 

        ///
Unformatted xml string.
        /// Formatted xml string and any exceptions that occur.
        public static string FormatXml(this string unformattedXml)
        {
            //load unformatted xml into a dom
            var xd = new XmlDocument();
            xd.LoadXml(unformattedXml);

            //will hold formatted xml
            var sb = new StringBuilder();

            //pumps the formatted xml into the StringBuilder above
            var sw = new StringWriter(sb);

            //does the formatting
            XmlTextWriter xtw = null;

            try
            {
                //point the xtw at the StringWriter
                xtw = new XmlTextWriter(sw) {Formatting = Formatting.Indented};

                //we want the output formatted
                //get the dom to dump its contents into the xtw
                xd.WriteTo(xtw);
            }
            finally
            {
                //clean up even if error
                if (xtw != null)
                    xtw.Close();
            }

            //return the formatted xml
            return sb.ToString();
        }
    }

Testing your StructureMap Registries.

Monday, November 2nd, 2009

I find that on every project I work on which uses StructureMap I include the same three unit tests per Structuremap registry.

My TestFixture set up normally looks something like this..

        [TestFixtureSetUp]
        public void TestFixtureSetup()
        {
            // Act
            ObjectFactory.Initialize(x => x.AddRegistry(new MyRegistry()));
        }

My first tests makes use of the in built testing capabilities within StructureMap. If there are any problems with your registry they should be captured by this test.

        [Test]
        public void Assert_registry_is_valid()
        {
            // Assert
            ObjectFactory.AssertConfigurationIsValid();
        }

My second test isn’t really a test but is useful to have in your solution if you need to diagnose any StructureMap problems. Calling this will write out all the dependencies that are registered with your container to the output window.

         [Test]
        public void What_do_we_have()
        {
            Debug.WriteLine(ObjectFactory.WhatDoIHave());
        }

My third test checks that you have more than one dependency registered with your StructureMap container. What I have found is that it is possible to configure your registry incorrectly and StructureMap won’t load any dependencies at all. However when you call the AssertConfigurationIsValid method it returns true. When you run up your application you get the ‘No Default Instance defined for PluginFamily’ exception. This tests helps you get check for this scenario.

         [Test]
        public void Assert_container_is_not_empty()
        {
            // Assert
            Assert.IsTrue(ObjectFactory.Container.Model.AllInstances.Count() > 1);

        }