Archive for the ‘.net’ category

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

Introducing Fluent WCF

March 31st, 2009

About 2 weeks ago Simon and I started to work on building a fluent interface to configure WCF. Our main aim in doing so is to cover the the scenarios of configuring Services and Clients 80% (or 20%) of the time.

Our goals at this stage are

  1. Services over Basic HTTP or TCP
  2. Either No Security and Windows Transport Security
  3. No message level Security
  4. Include Service Meta Data

What this should enable us to do on the Service Host end would look like

var host = new WCFHost()
        .AtAddress("http://localhost:8080/")
        .UsingContract(typeof (IHelloService))
        .WithBinding(new BasicHttpBinding())
        .EnableMex()
        .Start();

I expect more on this shortly.

del.icio.us Tags: ,

LINQ To SQL – Needs our support.

October 31st, 2008

A While back Ian Cooper blogged about the need for active development of LINQ To SQL, he had this to say

As a community, as people begin to realize the suprising power of LINQ to SQL, I would like to see us dispel many of the myths that seem to have grown up around that product. I would like to see us put pressure on the Data Platform team to provide the support for LINQ to SQL that we want going forward. Community reaction is everything and if the LINQ to SQL community remains silent in the face of the more vocal, but probably less numerous, EF community, we won’t get the product we deserve

David Hayden has made a call to Microsoft to Open Source the development of LINQ to SQL in response to the ADO.NET Teams announcement on the future of the Entity Framework and its forgotten other LINQ To SQL.

The ADO.net team says that they will improve LINQ to SQL based on community feedback then there is please head what David Hayden and Ian Cooper are saying.

Simon Segal has previously made a Save LINQ to SQL badge which apart from bring really cool is apt.

So if you want to keep POCO objects free of the IPOCO interface (at least in V1 of EF), I would ask the Data Dudes to set LINQ To SQL Free as per David Hayden’s Suggestion.

PDC 08 – Day 2

October 30th, 2008

So like me your one of the many that are not at PDC this year, but you still want to know what’s going check out http://notatpdc.com/

Also check out Jim O’Neil’s PDC Day 2 Wrap Up post.  I have been reading been doing my fair share of reading about all the Oslo, Windows 7 , Azure posts, not forgetting the PDC08 video’s on Chanel 9.  My favourite video so far has been The Future of C# by Anders Hejlsberg 

BTW if you cant find the videos for the session Julia Lerman has taken the effort to describe how to best find the PDC 08 sessions videos.

 

Technorati Tags: ,

Silverlight Flickr Image Browser

October 27th, 2008

In my last post about I mentioned creating a simple Flickr Image Browser in Silverlight. Feedback is required please.

Technorati Tags: ,,

Flickrlight – Silverlight 2 compatible Flickr API

October 26th, 2008

In learning Silverlight 2 I needed some self imposed tasks, one such task was to build a simple Flickr image browser, among other things. In doing so as most people would I found a .net Flicker API called FlickrNet. However when you try to add a reference to FlickrNet from my Silverlight 2 project I encountered a few issues with projects not loading. However after some research and hacking I was able to . Converting the project was the easy part but it was going to be just too hard to get the entire library working because of its reliance on a lot of calls to methods that are not available in the Silverlight Core CLR.

Therefore I have had to strip the existing FlickrNet functionality down, I have decided to christen it Flickrlight and now have a simple working demo of the Flickr Browser Application.

Flickrlight Demo

  The code is fairly similar to what FlickrNet, for those of you who are familiar with the existing API.

   1: private void btnGetPhoto_Click(object sender, RoutedEventArgs e)
   2: {
   3:     PhotoSearchOptions pso = new PhotoSearchOptions();
   4:     pso.Tags = feedURL.Text;
   5:     Photo p = new Photo();
   6:     p.ApiKey = ApiKey;
   7:     p.Secret = SharedSecret;
   8:     p.OnResponseCompleted += p_OnResponseCompleted;
   9:     p.BeginPhotosSearch(pso);
  10: }

One of the few changes is that the calls being made are Asynchronous and hence require the subscription to the Completed Event.

   1: private void p_OnResponseCompleted(FlickrResponseRecievedCompleteEventArgs<FlickrBase> e)
   2: {
   3:     Action bindToList = () => imageList.ItemsSource = ((Photos)e.ResultValue).PhotoCollection;
   4:     this.Dispatcher.BeginInvoke(bindToList);
   5: }

 

At this stage all I have done was to begin to move the Search for Photos functionality, however over the next few weeks I will move some more of this functionality across. I will also make Flickrlight available on Codeplex (unless someone tells me otherwise). Seeing as this will be my first foray into the world of open source if anyone has any experience with what I should be doing here, your help will be greatly appreciated.