Archive for the ‘NServiceBus’ category

Doing Advanced Distributed Systems Design – A Gift from Santa

February 4th, 2010

It is the second time I have sat through Udi’s Advanced Distributed Systems Design. Unlike repeating a course at University, I was like a 6 year old waiting for Santa Claus to arrive with his presents at Christmas. Not only has the course content been refined in some sections, CQRS (In case you missed it you can watch Udi’s presentation on CQRS here) for instance. Udi’s delivery of the material is such that he always has you yearning for more. The first time i did this course it was as though someone had opened my minds eye. Since then I have made so many changes to my thinking and the way I approach development.

My reasons for attending the course again were simple

  1. Gauge my progression
  2. Hear other peoples thoughts and opinions
  3. Spend more time at the feet of the master
  4. And of course Learn some more

The beauty of this course is that despite the complexity of the architecture and the concepts the delivery makes the comprehension a breeze.  Paul Batum and Rhys Campbell who attended the course have written up their impressions, as has Simon and we all agree that it is worth its weight in gold. So if you have thought about ever doing this course and can make it to one do so, but if your not able to go to one of upcoming courses I would strongly suggest getting in touch with Udi and working other possible solutions with him. Which is why I guess Simon is owed big thanks for setting up this opportunity.

As for NServiceBus and its comparisons to Nuclear Armament, I can only say that once you have used it, there is a realization that there is great power that can be wielded without any effort. Till you can try it for yourself see what twitter has to say about NServiceBus. For me the next dose of sharing some NServiceBus love will be at Day 2 of Doing .net Days on the 27th February 2010 if you have nothing on that Saturday why not send an email to register a seat before they run out

Lessons Learned from building a Linq To Sql Saga Persister

December 9th, 2009

Simon has released the first version of the Linq To Sql Saga Persister code and the EF 1 Saga Persister in the past couple of days. In fact we started working on the saga persister mid September, so what took doing something like a Saga Persister, a fairly trivial exercise almost 3 months. To be fair Simon initially put some of the work on the persister quite quickly. However once we started to use the code in our test with the Manufacturing sample under load it would begin to creak. Seeing as that was a problem we had to switch to using the NHibernate Saga persister for our client to go into production.

The first thing that went through our minds was that we had written the persister wrong, however a persistent Simon continued to work through the issues. Along the way we discovered a few things.

  1. NHibernate is faster and therefore able to handle the load better.
  2. Proper Saga Design is important.

NHibernate is faster

Most of you already know this but the key thing here is that because its faster it fails less therefore the issues that we saw in the development of the persister was difficult to isolate.

In the Manufacturing Sample that comes with NServiceBus start up all the required services and when the partner is ready run it in simulate mode, it does not fail. doing the same thing when using the L2S persister had the same effect.

Once the number of worker threads on the Order Service Host was increased to 4 could use we started to see a whole bunch of errors. From messages not being completed to violation of primary keys and deadlocks. Using the NHibernate persister required us to increase the workers to 6 or 7 you would start to notice similar errors.This leads me to the next item.

Proper Saga Design is Important

If your not sure about what a Saga is please read the NServiceBus wiki. When considering how you build a system  though that goes into how you would like to handle long running transactions is important. Knowing how many transactions per second. What are the SLA’s? My rule of thumb the more i think about it is that a Saga message that starts the saga should be unique any subsequent messages that are part of that saga should be dealt with a more explicit message handler. So you have a CreateOrderMessage that starts a saga and subsequent messages are handled by UpdateOrderMessages for changes to the order, with CancelOrderMessages and AuthorizeOrderMessages being explicit to the saga.

In my opinion doing so produces both a simpler and more explicit design of your long lived transaction. This however is now going down the path of a different post one that warrants a post of it own.

The Benefits of Reading code became clear the deeper we went through the NServiceBus code base, the more you understand how each piece interacts with the other to provide a great framework. Despite all the hurdles L2S provided it was worth the effort. What must be said for NServiceBus is that it is highly extensible already evidenced by its existing OOB support for 4 IOC frameworks, now 3 ORM’s and in the future with version 2.1 it will support a whole raft of Queued Transports.

Service Broker – Some thoughts post hoc

December 1st, 2009

sql service broker

This post has been sitting in my drafts for a while. After my day today i felt that it was best that i put my thoughts about service broker down.
In a project that i worked on about 2 years ago Service Broker was used as part of the system to perform data validation.  If success was measured by the amount of time that a system has been in production without major issues then i can say that it was successful.

But if a system was to be judged by how much of a pain it is to maintain then l must say that its was not a glowing success. Below is a list of things that i found as good or bad about it.

 

Bad things

  1. Limited information on the internet
  2. Testing is extremely hard (compromises everywhere)
  3. Troubleshooting is a pain
  4. It could stop working and you may never know, (if using a fire and forget mechanism)
  5. Poison messages disable queues (would have been nicer if it moved the message to a error queue)

Good things

  1. Its Asynchronous
  2. Its Asynchronous
  3. Its Asynchronous

Yes this list is one sided but true. The question that is important though is

Would i use Service Broker again?

The answer to that question is strangely YES. Only in very specific circumstances where system is ok with not having some data loss because of queue being disabled

What would I use instead?

of course. It provides an answer to all the negatives of service broker and is still asynchronous.

Testing Message Handlers with NServiceBus

September 27th, 2009

One of the great things that ships with is a dll called “NServiceBus.Testing” which provides us with the ability to easily test your sagas. This enables us to move forward with greater confidence in knowing that the code that we have written will function as expected when we move the code into integration testing and then production.  Most of what i talk about here is in direct reference the 1.9 release of NServiceBus. If you have not seen how Saga’s are unit tested in NServiceBus have a read of Udi’s post on the forum. This post however is about how to test a Plain old Message Handler.

Let us being with looking at a sample handler.

   1: public class FileProcessMessageHandler:IMessageHandler<ProcessFileMessage>

   2: {

   3:     public IBus Bus { get; set; }

   4:     public IFileProcessor FileProcessor {get;set;}

   5:     public void Handle(ProcessFileMessage message)

   6:     {

   7:         if (FileProcessor.Run(message.FileIdentfier,message.FileSystemLocation))

   8:         {

   9:             var msg = Bus.CreateInstance<FileProcessedMessage>(m => {

  10:                                  m.FileIdentifier = message.FileIdentfier; });

  11:             Bus.Publish(msg);

  12:         }

  13:         else

  14:         {

  15:             Bus.Publish<UnknownFileTypeMessage>(m => { 

  16:                                 m.FileIdentifer = message.FileIdentfier; });

  17:         }

  18:     }

  19: }

This code in and of itself is highly testable. We have two interfaces that are injected into the class, excellent candidates for a mock. However when i first started down this path my first inclination was to use a manual mock, before moving on to trying to use Moq, however after spending time the fluent saga testing API in NServiceBus I realized that it was what was needed in this situation a MockBus.

MockBus is essentially the same as what is in the NServiceBus.Testing library. However because that version is geared towards testing sagas, it required changing the way the Saga class was created, and to allow for creating a version that would work with message handler. The new structure looks like the class diagram below.

 

NServiceBus Testing Class Diagram

 

What Changed

  1. The Saga class has become the MockBus class and no longer has the static method called Test() which created the Saga instance.
  2. The MockBusForSaga has the method CreateInstance<T> which replaces the Test() method in the old Saga class.
  3. Introduced a MockBusForMessageHandler which has a CreateInstance<T,TK>() method that creates the message handler.

Having this structure now enables us to write our tests for our message handlers very simply in a fashion that does not require to understand Rhino Mocks, though having a understanding of the errors you get from the mock bus is important as all the messages that are bubbled out are Rhino Mock Messages.

   1: [Test]

   2: public void when_file_processor_succeds_message_handler_will_publish_a_file_processed_message()

   3: {

   4:     FileProcessMessageHandler msgHandler;

   5:     var mock_bus = MockBusForMessageHandler.CreateInstance

   6:                             <FileProcessMessageHandler,ProcessFileMessage>(out msgHandler);

   7:     var fileID = Guid.NewGuid();

   8:     msgHandler.FileProcessor = SetupAndReturnFileProcessor(true);

   9:     mock_bus.ExpectPublish<FileProcessedMessage>(d => d.FileIdentifier == fileID)

  10:         .When(() => msgHandler.Handle(CreateProcessFileRequest(fileID)));

  11: }

 

Lets have a look  when make a call to CreateInstance<FileProcessMessageHandler,ProcessFileMessage>(out msgHandler)

   1: public static MockBusForMessageHandler CreateInstance<T, TK>(out T handler)

   2: where TK : IMessage

   3: where T : IMessageHandler<TK>, new()

   4: {

   5:     handler = (T) Activator.CreateInstance(typeof (T));

   6:     var mocks = new MockRepository();

   7:     var bus = mocks.DynamicMock<IBus>();

   8:     try

   9:     {

  10:         typeof (T).GetProperty(“Bus”, BindingFlags.Instance | BindingFlags.Public)

  11:             .SetValue(handler, bus, null);

  12:     }

  13:     catch

  14:     {/**swallow if they dont have a Bus defined in the class**/}

  15:     List<Type> typesToMap;

  16:     MessageMapper mapper = GetMapperAndInitialize(out typesToMap);

  17:     return new MockBusForMessageHandler(mocks, bus, mapper, typesToMap);

  18: }

The beauty in this code is all hidden away in the MockBus (aka NServiceBus.Testing.Saga) thank you Udi for this,

The bus is instantiated when the object is created however no expectations are recorded until the When() method is called in the test just before the delegate is run. Once the delegate is run you will get the callbacks to the ExpectPublish where you can assert that not only did you get the correct type of message but the contents as well.

The code for this is available on the or go to it NServiceBus.Extensions.Testing download here