1 Comments

When using NHibernate (v. 2.1.2) with Linq to NHibernate (v. 1.1.0) you may encounter some problems if you use VB.NET as your coding language. Something as simple as the following example will throw a System.ArgumentException:

<span id="lnum1" style="color: #606060">   1:</span> <span style="color: #0000ff">Dim</span> customers = From c <span style="color: #0000ff">in</span> Customer.Queryable _

<span id="lnum2" style="color: #606060">   2:</span>         Where c.FirstName = searchCrit.FirstName _

<span id="lnum3" style="color: #606060">   3:</span>         <span style="color: #0000ff">Select</span> c

The full exception is: System.ArgumentException : Expression of type 'System.Int32' cannot be used for return type 'System.Boolean’

This is because the Linq to NHibernate doesn’t handle the string comparisons correctly. Or VB.NET doesn’t. To fix this, you have to replace the = operator comparison with a call to Equals:

<span id="lnum1" style="color: #606060">   1:</span> <span style="color: #0000ff">Dim</span> customers = From c <span style="color: #0000ff">in</span> Customer.Queryable _

<span id="lnum2" style="color: #606060">   2:</span>         Where c.FirstName.Equals(searchCrit.FirstName) _

<span id="lnum3" style="color: #606060">   3:</span>         <span style="color: #0000ff">Select</span> c

 

Thanks to @pettys for posting a helpful post on this subject.

3 Comments

We have a .NET-application which support two different versions of IBM WebSphere MQ. At the moment this means that we have to compile two versions of our solution: one with a support for the older 5.3 version and one for the newer 7.0 version. Changing the version isn’t very hard: We just open the project’s properties in Visual Studio and change the file reference to point to the correct external assembly. But doing this 15 times a day is still too much, and more so when considering that we would like to use TeamCity to do the builds for us. Luckily there’s a way to to automate the process by using different build configurations.

Note. You can use the same process if you have to change the project references based on the solution platform (x86 vs x64).

Sample applicationproject_ref1

Let’s create a sample application which demonstrates on how to change the project’s file references based on the build configuration.  The sample application has one button which will report the version of an external assembly when clicked.

The code looks like the following:

   1: private void button1_Click(object sender, EventArgs e)
   2: {
   3:     var testClass = new MyTestClass();
   4:
   5:     var message = string.Format("Version {0} of external assembly", testClass.MyVersion());
   6:
   7:     MessageBox.Show(message, "Information", MessageBoxButtons.OK);
   8: }

MyTestClass is located in an external assembly called testLibrary.dll. We have two different version of it: 1.0 and 1.5. By default we’re using the 1.5 version but in some cases our application should reference the 1.0 version. MyTestClass.MyVersion checks the version of the assembly and reports it back to the caller:

   1: public string MyVersion()
   2: {
   3:     return this.GetType().Assembly.GetName().Version.ToString();
   4: }

When a user clicks the “I’m using” button, the version is printed on a message box:

project_ref2

Creating a new build configuration

We want to automate the process of switching the referenced assembly and this can be done by creating a new build configuration for the sample application. You can do this through the Configuration Manager. By default all the applications have a build configuration for the debug and release versions. Our application also has a configuration called WithV1.0.

config_manager

Project references

By default our sample application references the testLibrary.dll inside the libv1.5-folder.

v1.5ref

We want to change this if the WithV1.0 is selected. This can be achieved by manually editing the project file.

Editing the project file

In order to achieve our goal, we have to manually edit the project file by using our favorite text editor. Inside the file you can find all the project’s build configurations as a xml format. Here’s how the Release and WithV1.0 configurations look like:

&lt;PropertyGroup Condition=<span style="color: #006080">" '$(Configuration)|$(Platform)' == 'Release|x86' "</span>&gt;

  <PlatformTarget>x86</PlatformTarget>

  <DebugType>pdbonly</DebugType>

  &lt;Optimize&gt;<span style="color: #0000ff">true</span>&lt;/Optimize&gt;

  <OutputPath>binRelease</OutputPath>

  <DefineConstants>TRACE</DefineConstants>

  <ErrorReport>prompt</ErrorReport>

  <WarningLevel>4</WarningLevel>

</PropertyGroup>

&lt;PropertyGroup Condition=<span style="color: #006080">"'$(Configuration)|$(Platform)' == 'WithV1.0|x86'"</span>&gt;

  <OutputPath>binx86WithV1.0</OutputPath>

</PropertyGroup>

And here’s how our project’s external references are presented:

&lt;Reference Include=<span style="color: #006080">"System.Windows.Forms"</span> /&gt;

&lt;Reference Include=<span style="color: #006080">"System.Xml"</span> /&gt;

&lt;Reference Include=<span style="color: #006080">"testLibrary"</span>&gt;

  <HintPath>..libv1.5testLibrary.dll</HintPath>

</Reference>

The trick is to make the testLibrary’s HintPath to change based on the selected build configuration. This can be achieved by creating a new property inside all the build configuration sections. The name of the property doesn’t matter but it should be something meaningful. We will use TestLibraryPath in our example:

<TestLibraryPath>..libv1.5testLibrary.dll</TestLibraryPath>

And then we just have to change the HintPath to read it’s value from the property:

&lt;Reference Include=<span style="color: #006080">"testLibrary"</span>&gt;

  <HintPath>$(TestLibraryPath)</HintPath>

</Reference>

After these changes our project file looks like this:

&lt;PropertyGroup Condition=<span style="color: #006080">" '$(Configuration)|$(Platform)' == 'Release|x86' "</span>&gt;

  <PlatformTarget>x86</PlatformTarget>

  <DebugType>pdbonly</DebugType>

  &lt;Optimize&gt;<span style="color: #0000ff">true</span>&lt;/Optimize&gt;

  <OutputPath>binRelease</OutputPath>

  <DefineConstants>TRACE</DefineConstants>

  <ErrorReport>prompt</ErrorReport>

  <WarningLevel>4</WarningLevel>

  <TestLibraryPath>..libv1.5testLibrary.dll</TestLibraryPath>

</PropertyGroup>

&lt;PropertyGroup Condition=<span style="color: #006080">"'$(Configuration)|$(Platform)' == 'WithV1.0|x86'"</span>&gt;

  <OutputPath>binx86WithV1.0</OutputPath>

  <TestLibraryPath>..libv1.0testLibrary.dll</TestLibraryPath>

</PropertyGroup>

<ItemGroup>

  &lt;Reference Include=<span style="color: #006080">"System.Windows.Forms"</span> /&gt;

  &lt;Reference Include=<span style="color: #006080">"System.Xml"</span> /&gt;

  &lt;Reference Include=<span style="color: #006080">"testLibrary"</span>&gt;

    <HintPath>$(TestLibraryPath)</HintPath>

  </Reference>

</ItemGroup>

After saving the project file and reopening it inside the Visual Studio, you can change the build configuration and the application will be compiled against the correct testLibrary.dll. Please note that the Visual Studio UI will not update reference’s information correctly when switching between the build configurations. But you will get the correct results when compiling your application.

v1.0ref

Alternative methods

There’s some other ways to do this but they also require one to manually edit the project files. One way is to specify conditions to PropertyGroup-sections. This StackOverflow question highlights the use of conditions.

Conclusion

Making the Visual Studio to change the project’s references based on the build configuration isn’t as straightforward as it should be. Fortunately it’s easy to go around this problem with a help of a text editor.

You can download the sample application from GitHub.

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.