Archive for the ‘.NET’ Category

Nunit Code Snippet

Thursday, June 24th, 2010

Here is a useful code snippet that I use all the time to create an empty unit test.

To use it go to your My Code Snippets folder, go to the snippet manager in Visual Studio (Ctrl K + Ctrl B) to get the file path if you don’t know it. Create a new text file with and appropriate name and rename the extension to .snippet and cut and paste the following xml into the file and save it.

 

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>
                NUnit Test
            </Title>
        </Header>
        <Snippet>
            <References>
                <Reference>
                    <Assembly>nunit.framework.dll</Assembly>
                </Reference>
            </References>
            <Declarations>
                <Literal>
                    <ID>Test_Name</ID>
                    <ToolTip>Replace with test method name</ToolTip>
                    <Default>Test_Name</Default>
                </Literal>
            </Declarations>
            <Code Language="CSharp">
            <![CDATA[]]>
            [Test]
            public void $Test_Name$()
            {
            }
            <![CDATA[]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets> 
 
And Bob’s your uncle it should appear in your code snippet shortcuts..Ctrl K Ctrl S to access.

ASP.Net MVC Option Group DropDown Control

Tuesday, December 15th, 2009

Option Groups for drop down lists have been an HTML feature for many years now but have never been supported in any Asp.Net control. It was a bit of a shame recently whilst working on a new Asp.Net MVC web site to find that its still not possible to do out of the box.

optiongroup

However the good thing about MVC is that its a really easy  to write your own custom controls in the shape of HTML helpers so I thought I’d go about writing my own.

What did I want the control to do?

Firstly I wanted it to be strongly typed so no magic strings. I also wanted to be able to pass the control an enumerable collection of objects and use lambda expressions to tell the control which properties to render the text, value and how to group the dropdown items by.


<%= Html.OptionGroupDropDownList(
          ViewData.Model.Cars,
          car =>  car.CountryOfOrigin,
          car => car.Brand,
          car => car.Brand,
          car => car.Brand == "BMW")%>

Line 2 above represents the collection of cars we wish to render as option items.
Line 3 is the property value of a car we wish to group them by.
Line 4 is the property value of a car we wish to use as the option value.
Line 5 is the property value a car we wish to use for the option text.
Line 6 is a condition we can supply to tell the control which drop down item should be selected.

which renders HTML that looks something a little like this:


Ok so the code looks like this..

public static string OptionGroupDropDownList<T, TProperty, TProperty1, TProperty2>
( this HtmlHelper htmlHelper,
  string name,
  string optionLabel,
  IEnumerable<T> collection,
  Func<T, TProperty> optionGroupProperty,
  Func<T, TProperty1> optionValueProperty,
  Func<T, TProperty2> optionTextProperty,
  Func<T, bool> isSelectedCondition)
{
      var groupedCollection = collection.GroupBy(optionGroupProperty);

      // We are trying to generate the Html that looks something like this...
      //<select>
      //  <optgroup label="Swedish Cars">
      //      <option value="volvo">Volvo</option>
      //      <option value="saab">Saab</option>
      //  </optgroup>
      //</select>";
      using (var stringWriter = new StringWriter())
      using (var writer = new HtmlTextWriter(stringWriter))
      {
          writer.AddAttribute(HtmlTextWriterAttribute.Name, name);
          writer.AddAttribute(HtmlTextWriterAttribute.Id, name);
          //<Select>
          writer.RenderBeginTag(HtmlTextWriterTag.Select); 

          if(string.IsNullOrEmpty(optionLabel) == false)
           {
               writer.RenderBeginTag(HtmlTextWriterTag.Option);
               writer.Write(optionLabel);
               writer.RenderEndTag();
            }

           // Group by our optGroup parameter...in the above example that would be
           // "Swedish Cars"
           foreach (var optionGroup in groupedCollection)
           {
                var optionGroupLabel = optionGroup.Key;
                // label="Swedish Cars"
                writer.AddAttribute(Label, optionGroupLabel.ToString());
                writer.RenderBeginTag(Optgroup); //<optgroup>  

                 foreach (var option in optionGroup)
                 {
                   var optionValue = optionValueProperty.Invoke(option).ToString();
                   var optionText = optionTextProperty.Invoke(option).ToString();

                   var isOptionSelected = isSelectedCondition.Invoke(option);

                   if (isOptionSelected)
                     writer.AddAttribute(HtmlTextWriterAttribute.Selected, "true");

                   // value = "volvo"
                   writer.AddAttribute(HtmlTextWriterAttribute.Value, optionValue); 

                   // <option>
                   writer.RenderBeginTag(HtmlTextWriterTag.Option);
                   // Volvo
                   writer.Write(optionText);
                   // </option>
                   writer.RenderEndTag();
                  }
                  // </optiongroup>
                   writer.RenderEndTag();
                }
                 //</Select>
                writer.RenderEndTag();

                return stringWriter.ToString();
            }
        }

Mocking HtmlHelpers in ASP.Net MVC

Friday, December 4th, 2009

NB: This post relates to version 1 of ASP.Net MVC

I recently added a static extension method for generating a custom drop down list and wanted to test it using Rhino Mocks (version 3.5).
One issue I kept banging my head against was how to create a Mock HtmlHelper in order to call the method correctly.
A number of posts later, and various attempts at using some of the sample code and I finally came across this post detailing a bunch of MVC tests.

After a minor amount of customising, I ended up with the following, which works like a charm for me to use in my tests.

        ///
        /// Creates a HTML helper for use in tests.
        ///
        private HtmlHelper CreateHtmlHelper()
        {
            var userControl = new ViewUserControl();
            var container = new ViewPage();
            container.Controls.Add(userControl);
            var context = MockRepository.GenerateMock<ViewContext>();
            userControl.ViewContext = context;

            return userControl.Html;
        }

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..

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);

        }

Getting Started With NServiceBus: Part 2 Publishing And Subscribing

Wednesday, October 28th, 2009

This post details the steps that you need to take to configure a self hosted publisher and subscriber. With the Publisher Subscriber model in NService Bus multiple clients (subscribers) can subscribe to particular messages from a publisher. The Publisher will manage the subscriptions and Publish any messages to the Bus which will be distributed to all the subscribers.

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

Configuring The Subscriber

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()
              .XmlSerializer()
              .MsmqTransport()
              .IsTransactional(true)
              .PurgeOnStartup(false)
              .UnicastBus()
              .ImpersonateSender(false)
              .LoadMessageHandlers()
              .CreateBus()
              .Start();

3) In the Application Config add the following


4) Now define the Subscribers’ Input Queue (where the subscribed to messages are sent to) and the Error Queue – where undelivered messages are put if there is an exception delivering the message in the config file


5) Now define the endpoint of the publisher that you wish to subscribe to messages from. This is a mapping between a message type and a particular publisher. You can either subscribe to all messages from an assembly or specify the type explicitly. In the example below I have specified that we wish to subscribe to every message in the Messages.dll that might be published.


    
      
    
  

Configuring The Publisher

6) Repeat steps 1) & 3) for the Server
7) Configure NServiceBus to run as a Publisher

            Configure
             .With()
             .StructureMapBuilder()
             .MsmqSubscriptionStorage()
             .XmlSerializer()
             .MsmqTransport()
             .IsTransactional(true)
             .PurgeOnStartup(false)
             .UnicastBus()
             .ImpersonateSender(false)
             .CreateBus()
             .Start();

8 ) Now define the Publishers’ Input Queue (where subscription requests are sent to) and the Error Queue – where undelivered messages are put if there is an exception delivering the message in the config file

  

9) When you run up the applications NServiceBus will create the relevant queues for you. But be careful make sure you start up the Publisher first otherwise the subscriber will throw an exception as there is no queue for it to put a subscription on.

The important thing to note with the Publisher is that we have configured it with the use MsmqSubscriptionStorage() line. NServiceBus will create an additional queue called nservicebus_subscriptions and will store each subscription as an individual message on that queue. It is possible to use NHibernate to manage your subscriptions in a database if that is required.

Pubishing a Message

Simply call the Publish method on the instance of you Bus

eg.

Bus.Publish(new Message());

or

Bus.Publish();

The documentation at the NServiceBus web site has more detailed information on this.

kick it on DotNetKicks.com