Archive for October, 2009

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

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 »