0 Comments

It took me long enough to realize what was wrong in my Web.config so here’s a little friendly reminder: MessageEndpointMappings are case sensitive.

My Web.config had the following section:

<UnicastBusConfig>

  <MessageEndpointMappings>

    &lt;add Messages=<span style="color: #006080">&quot;Messages&quot;</span> Endpoint=<span style="color: #006080">&quot;InputQueue&quot;</span>/&gt;

  </MessageEndpointMappings>

</UnicastBusConfig>

And I had the following project:

messages

And Bus.Send gave the following error:

No destination specified for message messages.CreateUserCommand. Message cannot be sent. Check the UnicastBusConfig section in your config file and ensure that a MessageEndpointMapping exists for the message type.

After staring at the configuration for 15 minutes and rebuilding the solution 30 times without a success, I noticed the capital M. Changing it to lowercase cured my problem.

Just a small note. If the Messages is changed to point to an assembly which doesn’t exist (like noMessages), NServiceBus will throw the following exception when configuring the bus:

Exception: System.ArgumentException: Problem loading message assembly: noMessages ---> System.IO.FileNotFoundException: Could not load file or assembly 'noMessages' or one of its dependencies. The system cannot find the file specified.

Maybe the case sensitivity can be classified as a bug?

0 Comments

If you’re using Windows 7 and have downloaded a NServiceBus sample application from somewhere, it’s likely that you will encounter problems running it. For example you may get the following exception when starting NServiceBus.Host.exe:

Creating the configuration section handler for MsmqTransportConfig: request failed. SecurityException…

or…

System.IO.FileLoadException: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

This is because by default the Windows 7 restricts the permission for files which are downloaded from the net. Fixing this is fortunately really simple. Just right click every NServiceBus-dll (or .exe) which you have downloaded and click the “Unblock”-button:

unblock

0 Comments

I was battling yesterday with Lambda Expressions. I wanted to get the function’s parameter’s value out in a usable form (object). Here’s how you can do it:

<span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Run()

<span style="color: #606060" id="lnum2">   2:</span> {

<span style="color: #606060" id="lnum3">   3:</span>     System.Linq.Expressions.Expression&lt;System.Func&lt;DateTime&gt;&gt; f2 = () =&gt; DateTime.Now.AddDays(12345);

<span style="color: #606060" id="lnum4">   4:</span>  

<span style="color: #606060" id="lnum5">   5:</span>     MethodCallExpression call = (MethodCallExpression)f2.Body;

<span style="color: #606060" id="lnum6">   6:</span>     ConstantExpression arg = (ConstantExpression)call.Arguments[0];

<span style="color: #606060" id="lnum7">   7:</span>  

<span style="color: #606060" id="lnum8">   8:</span>     var <span style="color: #0000ff">value</span> = GetValue(arg);

<span style="color: #606060" id="lnum9">   9:</span>     Debug.WriteLine(<span style="color: #0000ff">value</span>);

<span style="color: #606060" id="lnum10">  10:</span> }

<span style="color: #606060" id="lnum11">  11:</span>  

<span style="color: #606060" id="lnum12">  12:</span> <span style="color: #0000ff">private</span> <span style="color: #0000ff">object</span> GetValue(ConstantExpression expression)

<span style="color: #606060" id="lnum13">  13:</span> {

<span style="color: #606060" id="lnum14">  14:</span>     Expression conversion = Expression.Convert(expression, <span style="color: #0000ff">typeof</span>(<span style="color: #0000ff">object</span>));

<span style="color: #606060" id="lnum15">  15:</span>     var getterLambda = Expression.Lambda&lt;Func&lt;<span style="color: #0000ff">object</span>&gt;&gt;(conversion);

<span style="color: #606060" id="lnum16">  16:</span>  

<span style="color: #606060" id="lnum17">  17:</span>     var getter = getterLambda.Compile();

<span style="color: #606060" id="lnum18">  18:</span>  

<span style="color: #606060" id="lnum19">  19:</span>     <span style="color: #0000ff">return</span> getter();

<span style="color: #606060" id="lnum20">  20:</span> }

Thanks goes to these and many other questions in StackOverflow:

0 Comments

I’ve always liked the specification base class for NUnit which David Tchepak introduced in his blog post “Calculators and a tale of two TDDs - Pt 2: BDD-style”. It’s simple and easy to use. Here's the code:

[TestFixture]
   2: public abstract class ConcernFor<T> {
   3:     protected T sut;
   4:  
   5:     [SetUp]
   6:     public void SetUp() {
   7:         Context();
   8:         sut = CreateSubjectUnderTest();
   9:         Because();
  10:     }
  11:  
  12:     protected virtual void Context() {}
  13:     protected abstract T CreateSubjectUnderTest();
  14:     protected virtual void Because() {}
  15: }

When using it, your tests (specs) will end up looking like this:

public class When_current_status_is_disconnected_and_connection_happens : ConnectionStatusChangerConcern
   2: {
   3:     protected string message = ":irc.server.net PONG irc.server.net :irc.server.net";
   4:  
   5:     protected override void Context()
   6:     {
   7:         connection.SetConnectionStatusTo(ConnectionStatus.Disconnected);
   8:     }
   9:  
  10:     protected override void Because()
  11:     {
  12:         sut.Handle(new ServerMessageReceived() { Message = message });
  13:     }

I wanted to use the same base class for my ASP.NET MVC 2 controller tests, but it didn’t take long to figure that something was amiss. Given the following action:

: [HttpPost]
   2: public ViewResult Index(RegistrationData registration)
   3: {
   4:     if (ModelState.IsValid)
   5:     {
   6:         services.SendRegistration(registration);
   7:         return View("ThankYou");
   8:     }
   9:  
  10:     return View();
  11: }

And the following test:

 public class When_registration_with_invalid_data_is_received : RegistrationControllerConcern
   2: {
   3:     protected override void Because()
   4:     {
   5:         sut.Index(Examples.RegistrationEmptyEmail);
   6:     }
   7:  
   8:     [Test]
   9:     public void Should_not_send_the_registration()
  10:     {
  11:         Assert.That(service.HasBeenSent, Is.False);
  12:     }
  13: }

I expected to see green balloons. Instead, I was getting all reds. This is because my model uses data annotation to specify the validation rules. And when run inside an unit test, the validation isn’t actually happening. You can read a more thorough explanation from the following posts:

To fix this, I decided to create a ControllerConcernFor-class with the help of NUnit which forces the model’s validation before the Because-method is called. Here’s how it looks like:

 

   1: [TestFixture]
   2: public abstract class ConcernForController<T, T2>
   3:     where T : Controller
   4:     where T2 : class
   5: {
   6:     protected T sut;
   7:     protected T2 model;
   8:
   9:     [SetUp]
  10:     public void SetUp()
  11:     {
  12:         Context();
  13:         model = CreateModelForTest();
  14:         sut = CreateSubjectUnderTest();
  15:
  16:         EnforceModelValidation();
  17:         Because();
  18:     }
  19:
  20:     protected virtual void Context() { }
  21:     protected abstract T CreateSubjectUnderTest();
  22:     protected virtual void Because() { }
  23:     protected virtual T2 CreateModelForTest()
  24:     {
  25:         return null;
  26:     }
  27:
  28:     private void EnforceModelValidation()
  29:     {
  30:         if (model == null)
  31:             return;
  32:
  33:         var validationContext = new ValidationContext(model, null, null);
  34:         var validationResults = new System.Collections.Generic.List<ValidationResult>();
  35:         Validator.TryValidateObject(model, validationContext, validationResults, true);
  36:         foreach (var validationResult in validationResults)
  37:         {
  38:             sut.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
  39:         }
  40:     }
  41: }

And here’s an example spec:

   1: public abstract class RegistrationControllerConcern : ConcernForController<RegistrationController, RegistrationData>
   2: {
   3:     protected RegistrationServiceStub service;
   4:     protected override void Context()
   5:     {
   6:         service = new RegistrationServiceStub();
   7:     }
   8:     protected override RegistrationController CreateSubjectUnderTest()
   9:     {
  10:         var controller = new RegistrationController(service);
  11:         return controller;
  12:     }
  13: }
  14: public class When_registration_with_empty_email_is_received : RegistrationControllerConcern
  15: {
  16:     protected override RegistrationData CreateModelForTest()
  17:     {
  18:         return Examples.RegistrationEmptyEmail;
  19:     }
  20:
  21:     protected override void Because()
  22:     {
  23:         sut.Index(model);
  24:     }
  25:
  26:     [Test]
  27:     public void Should_not_send_the_registration()
  28:     {
  29:         Assert.That(service.HasBeenSent, Is.False);
  30:     }
  31: }

Easy enough.

Download

You can download the ControllerConcernFor-class from GitHub.

0 Comments

Our current plugin sample application has one big shortcoming: The plugins can’t communicate with the main application. Showing message boxes won’t take us very far.  It’s common that a plugin requires something from the main application. That something can be a query for the application status or a request to show something on the screen. Plugins rarely survive alone. In this post we’re going to extend our sample application to allow plugins to interact with the Windows Forms client.

First, let’s define an interface for our plugins. Our plugins don’t require much from the application but it would be nice if they could print something on the screen instead of showing the message boxes. We can start from this:

   1: public interface IApplicationFeatures
   2: {
   3:     void ShowOnScreen(string message);
   4: }

Then let’s add a textbox in our app’s screen. This is where the plugins can send their messages. Here’s a screen capture from our new application:

plugin_msg

Now we need just two things:

  1. A class that implements the IApplicationFeatures-interface
  2. Some way to pass a reference of this class into our plugin

Let’s start from the first point. Because our needs are so straightforward, there’s no need to create a new class: We can use our existing MainApplication-class and make it implement the IApplicationFeatures-interface. Here’s the full implementation:

   1: public void ShowOnScreen(string message)
   2: {
   3:     this.messageFromPlugin.Text = message;
   4: }

If one of our plugins require an IApplicationFeatures-implementation, we want to pass it our MainApplication-class. For this to work, we must make sure that the MainApplication is a singleton and that the Structuremap resolves the same instance for calls for IApplicationFeatures and IMainApplication. Thanks to Structuremap, this is easy to configure. Change the CreateContainer in our Program.cs to the following:

   1: private static IContainer CreateContainer()
   2: {
   3:     var container = new Container(x =>
   4:                                       {
   5:                                           x.AddRegistry<PluginRegistry>();
   6:                                           x.For<IMainApplication>().Singleton().Use<MainApplication>();
   7:                                           x.Forward<IMainApplication, IApplicationFeatures>();
   8:                                       });
   9:
  10:     return container;
  11: }

Now, every time a class requires either IMainApplication or IApplicationFeature, the same instance is used.

After this it’s very easy to pass the reference into our plugins. Remember how our plugins are resolved by the Structuremap container? This means that we can use constructor injection. We’re going to just add the required interface into our plugin’s constructor and let the Structuremap do all the hard work. Here’s the full implementation of our plugin:

   1: public class MyPlugin : IPlugin
   2: {
   3:     private readonly IApplicationFeatures appFeatures;
   4:
   5:     public MyPlugin(IApplicationFeatures appFeatures)
   6:     {
   7:         this.appFeatures = appFeatures;
   8:     }
   9:
  10:     public void Run()
  11:     {
  12:         appFeatures.ShowOnScreen("Hello from plugin.");
  13:     }
  14: }

And here’s the result after running the program and clicking the only button:

hello_plugin

Now your plugins don’t have to survive alone.

Download

The full source code is available from the GitHub.