Archive for the ‘.NET’ Category

Getting Started With NServiceBus: Part 1 Unicast Messaging

Tuesday, October 27th, 2009

I’ve been doing a bit of work with NServiceBus recently on a project and found it to be a really powerful and robust tool once you get it working. However like most open source projects and Udi will admit this himself the documentation is somewhat lacking.

I haven’t done anything too complicated with NServiceBus and these are more notes for myself rather than anything else but I thought i’d put up a series of posts on some of the basic scenarios.

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

Configuring The Client

This is your basic point to point messaging and is very similar to your typical wcf client calling a wcf service. This example show how to get NServiceBus working in your own application rather than using the self host.

1) Reference NServiceBus.dll & NServiceBus.Core.dll
2) In your Bootstrapper you need to configure NServiceBus

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

3) In the Application Config add the following


4) Now define the Client’s Input Queue (where response 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 you wish to send the messages to this is essentially a mapping between a message type and an endpoint queue. You can either send all messages from an assembly to a particular
endpoint queue or you can specify a specific type. In the example below I have specified that every message in the Messages.dll should be sent to the Server_Input queue.


    
      
    
  

Configuring The Server

6) Repeat steps 1) & 3) for the Server
7) Configure NServiceBus to run as a server the important difference between this and the client is the
LoadMessageHandlers() line which means we will handle the incoming messages.


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

8 ) Now define the Server’s Input Queue (where request 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


9) That’s it! when you run up the applications NServiceBus will create all the queues automatically for you (you can specify it not to do this if you wish)

Refactoring Switch Statements With StructureMap

Friday, October 23rd, 2009

Switch statements are commonly regarded as code smells, especially when the number of switch statements becomes very large. For this example I’m going to show you the traditional approach to refactor out a switch statement in C# and how you can further refine this approach using StructureMap though this would be possible using any IOC container.

Consider the following switch statement which I’ve kept fairly simple for the purpose of  demonstration:

public void ProcessCommand(Command command)
        {
            switch (command)
            {
                case Command.Go:
                    Console.WriteLine("Go");
                    break;

                case Command.Pause:
                    Console.WriteLine("Pause");
                    break;

                case Command.Stop:
                    Console.WriteLine("Stop");
                    break;

                default:
                    throw new Exception("Unhandled Command");
            }
        }

The Classic Approach To Refactoring Switch Statements

Normally when refactoring a switch statement we would perform the following steps:

1) Create an abstract/interface for a handler e.g.

public interface ICommandHandler
{
    void Handle();
}

2) For each case statement create a concrete implementation of our abstract handler  e.g.

 public class GoHandler:ICommandHandler
    {
        public void Handle()
        {
            Console.WriteLine("Go");
        }

        public bool Handles(Command type)
        {
            return Command.Go == type;
        }
    }

3) Create a Dictionary of our handlers using our switch statement key for our dictionary key e.g.

    public class RefactoredWithDictionary
    {
        private readonly Dictionary _commandHandlers;

        public RefactoredWithDictionary()
        {
            _commandHandlers = new Dictionary
                                   {
                                       {Command.Go, new GoHandler()},
                                       {Command.Pause, new PauseHandler()},
                                       {Command.Stop, new StopHandler()}
                                   };
        }

        public void DoSomethingWithTheSwitchStatement(Command command)
        {
            _commandHandlers[command].Handle();
        }
    }

Ok this is a big improvement from our previous switch statement it helps us get a bit closer to our S.O.L.I.D code Nirvana by adhering to our single responsibility principle and encapsulating our logic in specific handlers. However if we need to add a new handler we will need to modify the code by adding a new handler to the dictionary which violates our Open Closed Principle.

StructureMap To The Rescue!

The first thing we need to do is modify our ICommandHandler interface slightly.

public interface ICommandHandler
{
        void Handle();
        bool Handles(Command command);
        bool IsDefault { get; }
}

We have added two methods to the Interface. The new Handles method means each concrete implementation can now return whether or not it can handle a specific Command and the IsDefault property tells us whether or not our Handler is the default handler or not.

Our concrete implementation would now look like this:

    public class GoHandler:ICommandHandler
    {
        public void Handle()
        {
            Console.WriteLine("Go");
        }

        public bool Handles(Command type)
        {
            return Command.Go == type;
        }

        public bool IsDefault
        {
            get { return false; }
        }
    }

Now our class that can take an IEnumerable collection of  ICommandHandlers and query the collection for a handler that can handle the particular command.  It can also query the collection for the default handler if there is no handler defined for the particular Command.

Our class that originally contained the switch statement now looks like this:

    public class RefactoredWithStructureMap
    {
        private readonly IEnumerable _commandHandlers;

        public RefactoredWithStructureMap(IEnumerable commandHandlers)
        {
            _commandHandlers = commandHandlers;
        }

        public void DoSomethingWithTheSwitchStatement(Command command)
        {
            var defaultHandler = _commandHandlers.Where(handler => handler.IsDefault).First();

            var commandHandler = _commandHandlers
                .Where(handler => handler.Handles(command))
                .DefaultIfEmpty(defaultHandler)
                .FirstOrDefault();

            commandHandler.Handle();
        }
    }

Great but we need to make one more change so that we can get StructureMap to inject in our Handlers. We Need to modify our StructureMap Registry to do two things. Firstly we need to tell StructureMap to load all implementations of ICommandHandler. Secondly we need to tell StructureMap how to satisfy any requests for IEnumerable<ICommandHandler> and how to construct that collection.

To do this we need to add the following lines to our Registry.

    internal class StructureMapRegistry : Registry
    {
        public StructureMapRegistry()
        {
            Scan(scanner =>
                     {
                         scanner.TheCallingAssembly();
                         scanner.WithDefaultConventions();
                         scanner.AddAllTypesOf();
                     });

            ForRequestedType>()
                .TheDefault.Is.ConstructedBy(x => ObjectFactory.GetAllInstances());
        }
    }

The beauty of this approach is now if we need to add a new handler all we have to do is write a new handler and it will automatically be injected into our class by StructureMap!

kick it on DotNetKicks.com

Tags: ,
Posted in .NET, S.O.L.I.D | No Comments »

Back To Basics With Integration Testing

Wednesday, June 3rd, 2009

A lot gets written about unit testing and test driven development these days. However I feel integration testing get overlooked sometimes. Everybody seems to know what integration tests are but very few seem to know how to write a good integration tests or  really what are the true differences between integration and unit tests are.

Integration Tests Masquerading As Unit Tests

One of the most common things I see in the industry today is developers writing unit tests that are in fact integration tests. The giveaway signs are batch files copying configuration files,  connection strings and urls to web services all over the place. The tests pass on one developers machine but fail on an others. When you try to set up the solution on your machine it takes you half a day to get the tests to pass. Does any of this sound familiar?

In my opinion these are the worst kind of tests. The tests themselves tend to be very fine grained. They might be trying to test a very discrete portion of code in the same way that a unit test might. But because the code we are testing has so much freedom to access so much of our system. The set up for our test, to put our system into the correct state, in order to execute the code we wish to test is huge.

The problem with these type of tests are that they are incredibly hard to maintain. The fact that this piece of data must be in this table and this web service must do such and such when we call it in order to make our test pass may have made sense to the developer who wrote the code at the time, but for the guy trying to maintain that test six months down later the task can sometimes feel like a Sherlock Holmes mystery trying to fathom out why that test is failing and  how to get it to pass.

What is a Unit Test

From Wikipedia “In computer programming, unit testing is a method of testing that verifies the individual units of source code are working properly. A unit is the smallest testable part of an application.”

In C# a unit test should be aimed at testing the logic at the class level and that classes interactions with the other dependent objects within your system. That means I don’t really want my unit test to be interacting with any databases, web services, smtp servers, file systems etc.. The reason why is that I want my unit tests to be small, fast, robust, simple and easy to maintain. I don’t want to have write 500 lines of code to set up my system to allow my code to execute. I want to control the class under test’s interactions with the other objects in the system in a controlled  and repeatable manner.

When writing a unit test most of the time I am only concerned with the logic contained within that class. I’m looking at writing tests that can exercise as much of the code, within that class and to to execute it in as many different possible ways in order to find those subtle and hard to find bugs. How does the code behave if this or that happens. My unit tests will certainly include the happy logic path but they will also include the unhappy path through my code as well. It is with my unit tests that I can determine how my code will behave in those unusual circumstances. And it is this process of looking at your code under a microscope that helps you build that robustness into your code at the building block level.

To have the freedom to execute our class under test in anyway I choose. The easiest way is to isolate our class from its external dependencies. This is where the tricks of the trade like Inversion of Control and mocking frameworks come in useful. For example if our code needs to make a call of to our data access layer to in order to get a list of customers we can hide our data access dependency away behind an abstraction.Which can be replaced with a mock object that has the desired behaviour we need to satisfy our test and inject it into the class we wish to test.

What Is An Integration Test

So unit tests are great, you can have 100% code coverage but sometimes when you look down the microscope you miss the big picture. Have you set those bindings up correctly on that WCF endpoint? or has the database been set up correctly?

The key to a good integration test is in the name – your testing how all those different components in your system integrate together. Now when I’m writing an integration test I’m not really thinking about uncovering those devious hard to find bugs but trying to test if my system works as expected. I’m looking for those blaring obvious problems, and testing a few of the main logic paths through my application.

I would argue that integration tests have the following characteristics:

Given these characteristics you typically don’t want to writing too many integration tests. I remember having a discussion with a colleague a few years ago who argued that integration tests were a far more efficient use of time as you could test a lot more code with far fewer tests – more bang for your buck.

He wasn’t wrong but he missed the point totally. With an integration test it is very difficult to test all your code in your system, such as those hard to reach if statements or that rarely used catch block. Rob Connery blogged the other day about the fact that 80% of all bugs was caused by 20% of code. The risk of not having tests over that code could cause you major problems in the long run. A few integration tests can provide you with a pretty good code coverage figures for very little effort. The problem is to increase that code coverage using integration tests alone the effort involved in writing and maintaing those tests goes up exponentially.

What Makes A Good Integration Test

Summary

So what I hope I’ve highlighted that unit tests and integration tests are very different creatures and sometimes in the real world the edges between them become blurred. Unit tests do some thing better than integration tests and vice versa. You really can’t afford to rely on one without the other if you want confidence in the system your testing and when you understand those differences you can use them more effectively to target your testing against your code base

Posted in .NET, Testing | No Comments »

Common Service Locator To The Rescue

Tuesday, May 26th, 2009

After spending the last few hours trying to get an Asp.net MVC site working in medium trust, unfortunately I just couldn’t get StructureMap the IOC container I had decided to use to work, as it appears to call off to some code  deep down in it’s bowels that uses some reflection.

Fortunately we had decided to use the Common Service Locator an abstraction layer over your IOC so swapping out the IOC container with Unity which I know does work in medium trust was a doddle. It’s funny because when I put in the Common Service Locator code I did question its relevance as I could never envisage a reason why I would want to swap out my IOC container.

You live and learn I guess.

Posted in .NET | 5 Comments »

One Tangible Benefit of S.O.L.I.D Development

Saturday, May 16th, 2009

So S.O.L.I.D development seems to be the new buzz word at the moment. Now even though we all know that code that is loosely-coupled and highly cohesive leads to greater maintainability and  testability, sometimes it is difficult to tangibly measure the benefits that well structured code can actually bring to the business.

For this post I’m going to mainly concentrate to on the first two rules of S.O.L.I.D development namely the Single Responsibility Principle and the Open Closed Principle

A code base that follows the S.O.L.I.D principles will typically have the following characteristics:

Now when I contrast this with the very typical, legacy code base that I am currently working with things are very different.

Where I’m working currently we have a large team working on a number of concurrent projects all working in the same code base. Because of the way our code is structured we typically have a lot of problems merging our code because there are many classes that have to much responsibility, do too much and know about too many other classes. This means that the same classes time after time are modified for different projects. This in turn causes us far more merge conflicts when trying to reintegrate our code. Now problems merging code means longer project timelines and increased costs to the customer.

When S.O.L.I.D principles are adhered to the way we write code is far different. To add functionality to our system we normally try to achieve this by adding new code and classes rather than modifying existing code (Open Closed Principle – where our system is open for extension but closed for modification). Typically because our classes do less and are smaller the chances of two projects working on the exact same class is also reduced, thus reducing the chances of merge conflicts.

S.O.L.I.D and good OO design principles in your code are  not just wooly concepts banded around by academic types but are good sound principles that can save your organization time and money in the long run.

kick it on DotNetKicks.com

Posted in .NET, S.O.L.I.D, Software Architecture | No Comments »

Mocking LightSpeed Units Of Work

Tuesday, May 12th, 2009

One of my colleagues asked me the other day how he could mock a LightSpeed UnitOfWork. Apparently he couldn’t find any good examples out there on the InterWeb so I thought I’d post this short code sample to show how its done.

The most important thing is that you should not create your UnitOfWork yourself but use the CreateUnitOfWork() factory method on your LightSpeedContext. See code example below.

using (var unitOfWork = Repository.Context.CreateUnitOfWork())
 {
        var customerOverEighteenYearsOld = unitOfWork
                              .Customers
                              .Where(customer => customer.Age > 18);
       return customerOverEighteenYearsOld.ToList();
 }

Now if we wanted to test this code by mocking our UnitOfWork we can substitute our IQueryable<Customers> with an in memory collection rather than hitting the database directly.

So our unit test setup code would look something like this. The example below uses Rhino Mocks to mock the Unit Of Work.

[SetUp]
public void TestSetUp()
{
         // Customer Collection
         var customers = new List<Customer>{
                                new Customer{Age = 10},
                                new Customer{Age = 18}
                                }; 

         var unitOfWorkFactory = MockRepository.GenerateStub<IUnitOfWorkFactory>();
         var unitOfWork = MockRepository.GenerateStub<CustomersUnitOfWork>(); 

         // Replace the normal UnitOfWorkFactory with our implementation.
         Repository.Context.UnitOfWorkFactory = _unitOfWorkFactory; 

         // Stub the behaviour of our unit of work factory to
         // return our mocked UnitOfWork
         unitOfWorkFactory
                    .Stub(uowf => uowf.Create(Arg<LightSpeedContext>.Is.Anything))
                    .Return(unitOfWork ); 

         // Stub our unit of work to return our in memory customer collection.
         unitOfWork.Stub(uow => uow.Customers()).Return(customers);
}

So all we really need to do is to mock our LightSpeed UnitOfWork Factory replacing the default factory on our LightSpeed Context with our mocked version.  

We can then stub out the Create method on our mocked UnitOfWork factory to return our own implementation of our UnitOfWork (which is also a mock).  

We can now get our UnitOfWork to behave as we want it to without ever having to hit a database.

kick it on DotNetKicks.com

Posted in .NET, LightSpeed, ORM, TDD, Unit Testing | 1 Comment »

.Net TimeBombHack

Friday, May 8th, 2009

I love this code which I found when digging around in some of Ayende’s source code , so I thought i’d share it with you, but I can’t take the credit for it.

Its called the TimeBombHack class and you can use it for those times when your writing code when you would usually put in a  //TODO:  comment.

However as is often the case sometimes these todos get forgotten and never get implemented and can make it into production. You can put the TimeBombHack into your code specifying a date and message. When the date arrives the code throws an exception, simple as that.

 TimeBombHack.Until(new DateTime(2009, 5, 14), "Add exception handling");

Anyway the code looks like this:


 public static class TimeBombHack
 {
     #region Public Methods

     public static void Until(DateTime expiredAt, string message)
     {
          var hackExpiredMessage = string
             .Format("The hack ({0}) expired on ({1}). You really should fix it already",
                 message,
                 expiredAt);

          if (DateTime.Today > expiredAt)
             throw new HackExpiredException(hackExpiredMessage);
     }

        #endregion Public Methods
 }

kick it on DotNetKicks.com

Posted in .NET | 2 Comments »

Asp.Net MVC Conditional TextBox

Wednesday, April 8th, 2009

So I’m really enjoying working with the new Asp.Net MVC framework its refreshing to not be fighting the Asp.Net page life cycle for a change.

One of the things that I don’t like about the MVC Framework is it love affair with strings.  Jeremy Miller puts it far more eloquently than I ever could so I definitely recommend you read that article on his approach with working with the MVC framework even if it is a few months old now.

So like Jeremy I’m a big fan of passing strongly typed objects between my view and my controller.  The other day I was working on a page where I wanted to send an email.  Before the email had been sent I wanted to render out a series of TextBoxes to capture the email information. Once it had been  sent I then wanted to make the textbox read-only.  I thought it  would be good to write an HtmlHelper extension method with a fluent interface so that I could pass a condition (as a Lambda) into it so that I could make a declaration something like code below.

This code example uses the MVC Futures assembly which you can utilize by referencing the Microsoft.Web.Mvc assembly in your solution.

 <%= Html.ConditionalTextBoxFor(model => model.FromEmail)
      .MakeReadOnlyIf(() => Model.Sent) %>

So how did I implement this. First of all I had to write the HtmlHelper extension method which looks like this.

 public static IControlForOptions ConditionalTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> action)
           where TModel : class
{
   return new TextBoxForOptions<TModel, TProperty>(helper, action);
}

 

This method returns an IControlForOptions interface which looks like this. Using an interface means we can provide different concrete implementations for different controls.

public interface IControlForOptions{
string MakeReadOnlyIf(Func<bool> predicate);}

Our concrete implementation of  our IControlForOptions for our TextBox looks like this:

 public class TextBoxForOptions<VIEWMODEL, TProperty> : IControlForOptions where VIEWMODEL : class
 {
private readonly Expression<Func<VIEWMODEL, TProperty>> _expression;
private readonly HtmlHelper<VIEWMODEL> _helper;
/// <summary>
/// Initializes a new instance of the <see cref="TextBoxForOptions&lt;VIEWMODEL, TProperty&gt;"/> class.
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="expression">The action we will use </param>
 public TextBoxForOptions(HtmlHelper<VIEWMODEL> helper, Expression<Func<VIEWMODEL, TProperty>> expression)
    {
     _helper = helper;
 _expression = expression;
}

/// <summary>
/// Based upon our predicate condition we will either render out a textbox or a readonly textbox
/// </summary>
/// <param name="predicate">The condition we wish to test.</param>
/// <returns>Either a normal textbox or an readonly textbox</returns>
public string MakeReadOnlyIf(Func<bool> predicate)
{
var makeReadOnly = predicate();
if (makeReadOnly)
{
return _helper.TextBoxFor(_expression, new { ReadOnly = true });
}

return _helper.TextBoxFor(_expression, null);
}
}

In this example I have created a fluent interface that can conditionally out put a Textbox which is readonly. Using this approach you could easily extend this to any HTML control and modify any attribute you wanted to.

kick it on DotNetKicks.com

Posted in .NET, Asp.Net MVC | 5 Comments »

Unit Testing LightSpeed Entities

Thursday, April 2nd, 2009

If you have not heard of LightSpeed or had a play with it then you should check out the excellent lightweight ORM from the boys at Mindscape.  I have worked with it for a couple of years now and really like it for certain type of projects, I think its simplicity is a good stepping stone for developers making that transition from old data access strategies to ORM technologies.

The one thing I don’t like about it is that your domain objects are not persistant ignorant of the underlying ORM technology, and have to inherit from an Entity base class.

I have run into problems when trying to unit test code that use my Lightspeed entities because I cannot just create a new entity without hitting the database.  Normally when you request an entity from the database the construction of that entity is handled by the Lighspeed framework.

Some of the things that were causing me problems were:

In the end I created a LightSpeedEntityFactory and some helper methods for testing purposes to create my entities and get around some of these issues.  I hope you find the following code useful.

    ///

    /// Factory class for building LightSpeedEntity, that are are divorced from a real UnitOfWork.
    /// 

    /// To be used for Unit Testing purposes only!
    internal class LightSpeedEntityFactory
    {
        #region Methods

        ///

        /// Build a LighSpeed Entity with the chosen Id, and a Fake UnitOfWork.
        /// 

        /// 
        /// 
        public static T Build<T>(object id) where T : Entity
        {
            var lightSpeedEntity = Build<T>();

            lightSpeedEntity.SetId(id);

            return lightSpeedEntity;
        }

        ///

        /// Build a LighSpeed Entity with a Fake UnitOfWork.
        /// 

        /// 
        /// 
        public static T Build<T>() where T : Entity
        {
            var lightSpeedEntity = (T)Activator.CreateInstance(typeof (T));

            IUnitOfWork unitOfWork = new UnitOfWork();

            lightSpeedEntity.SetUnitOfWork(unitOfWork);

            return lightSpeedEntity;
        }

        #endregion Methods
    }
   ///

    /// Some helper extension methods for changing the internals of a LightSpeed entity.
    /// 

    /// 
    /// We do some very naughty stuff in here using reflection and these methods
    ///  should only be used for the purposes of Unit Testing.
    /// 
    public static class LightSpeedHelper
    {
        #region Methods

        ///

        /// Set the Id of a LightSpeed Entity. This is usually only a read-accessible property.
        /// 

        public static void SetId(this Entity entity, object id)
        {
            var setIdInternalMethod = entity.GetType().GetMethod("SetIdInternal", BindingFlags.NonPublic | BindingFlags.Instance);

            setIdInternalMethod.Invoke(entity, new[] {id});
        }

        ///

        /// Sets a read-only property on a LightSpeed Entity.
        /// For setting up an object for testing purposes only.
        /// 

        /// lightspeedEntity.SetProperty(a => a.Addresses).SetValue(addresses)
        /// 
        /// The type of the ESULT.
        /// 
        public static IPropertySetter<RESULT> SetProperty<T, RESULT>(this T entity, Expression<Func<T, RESULT>> action) where T : Entity
        {
            var outerMember = (MemberExpression)action.Body;

            var outerProp = (PropertyInfo)outerMember.Member;

            var propertyName = outerProp.Name;

            IPropertySetter<RESULT> propertySetter = new PropertySetter<RESULT>(entity, propertyName);

            return propertySetter;
        }

        ///

        /// Sets the unit of work on a LighSpeed Entity.
        /// 

        public static void SetUnitOfWork(this Entity entity, IUnitOfWork unitOfWork)
        {
            var uowProperty = entity.GetType().GetProperty("UnitOfWork", BindingFlags.NonPublic | BindingFlags.Instance);

            uowProperty.SetValue(entity, unitOfWork, null);
        }

        #endregion Methods
    }
    public class PropertySetter<T> : IPropertySetter<T>
    {
        #region Fields

        private readonly object _parent;
        private readonly string _propertyName;

        #endregion Fields

        #region Constructors

        public PropertySetter(object parent, string propertyName)
        {
            _parent = parent;
            _propertyName = propertyName;
        }

        #endregion Constructors

        #region Methods

        public void SetValue(T value)
        {
            var fieldName = FormatPropertyName(_propertyName);

            var fieldInfo = _parent.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);

            fieldInfo.SetValue(_parent, value);
        }

        private static string FormatPropertyName(string propertyName)
        {
            // get the first letter of the property name.
            var sb = new StringBuilder();

            sb.Append("_");
            sb.Append(char.ToLower(propertyName[0]));
            sb.Append(propertyName.Substring(1));

            return sb.ToString();
        }

        #endregion Methods
    }

UPDATE – ADDED CODE FOR IPROPERTY SETTER THAT WAS MISSING

    public interface IPropertySetter<T>
    {
        #region Methods

        void SetValue(T value);

        #endregion Methods
    }

Posted in .NET, LightSpeed, ORM, TDD, Unit Testing | 6 Comments »