In our projects we’re using Castle’s Automatic Transaction Management facility (ATM). This facility allows to declaratively define transaction boundaries: by marking a method by a specific attribute the call to this method will be wrapped in a transaction, so that a transaction will be opened before calling the method and committed right after finishing method execution.

In code, it looks like this:

  1: [Transactional]
  2: public class Foo
  3: {
  4:     [Transaction]
  5:     public virtual void Bar()
  6:     {
  7:         // Do something in a transaction
  8:     }
  9: }
 10: 

Let’s suppose that later, we want to test this code. Say, we want to verify that code in Foo.Bar() method is executed in a transaction. Moreover, we want to assure that the marking attributes will not be deleted accidentally.

We can test that within two aspects. First - an integration test: a real application part will be spawned and a call will be performed. After, we should verify that changes was committed by transaction. It takes time to run such a test (integration test usually runs slower) and effort to write & verify such a test. Second way to test that - is to check presence or required attributes. This will be a fast unit test that will just check that attribute is still applied to a method.

Those methods complements each other. Ideally, it should be both written.

Let’s see how we can verify that attributes required by ATM are applied to required methods.

First, we’ve defined the API that we want to use to do our check:

  1: CustomAssertions.ShouldUseATM<Foo>(foo => foo.Bar());

Yes, you see it right, we want to make it type save, refactor-able and nice looking.

This helper class should verify next assumptions, all required by ATM:

  • Tested class should be marked with TransactionalAttribute;
  • Method should be marked by TransactionAttribute;
  • Method should be virtual.

Solution we came to this problem is the next class:

  1: public static partial class CustomAssertions
  2: {
  3:     public static void ShouldUseATM<T>(Expression<Action<T>> methodExpression) where T : class
  4:     {
  5:         ThrowIfTypeNotMarkedAsTransactional(typeof (T));
  6:
  7:         var methodInfo = ((MethodCallExpression) methodExpression.Body).Method;
  8:
  9:         ThrowIfMethodIsNotMarkedWithTransactionAttribute(methodInfo);
 10:         ThrowIfMethodMarkedWithTransactionAttributeIsVirtual(methodInfo);
 11:     }
 12:
 13:     private static void ThrowIfTypeNotMarkedAsTransactional(Type classType)
 14:     {
 15:         object[] foundAttributes = classType.GetCustomAttributes(typeof (TransactionalAttribute), false);
 16:         if (foundAttributes.Length == 0)
 17:             Assert.Fail("The type '{0}' is not marked with [Transactional] attribute", classType.Name);
 18:     }
 19:
 20:     private static void ThrowIfMethodIsNotMarkedWithTransactionAttribute(MethodInfo info)
 21:     {
 22:         var found = info.GetCustomAttributes(typeof (TransactionAttribute), false);
 23:         if (found.Length == 0)
 24:             Assert.Fail("Method '{0}' from '{1}' type is not marked with [Transaction] attribute",
 25:                         info.Name,
 26:                         info.DeclaringType.Name);
 27:     }
 28:
 29:     private static void ThrowIfMethodMarkedWithTransactionAttributeIsVirtual(MethodBase methodInfo)
 30:     {
 31:         if (methodInfo.IsVirtual && !methodInfo.IsFinal)
 32:             return;
 33:
 34:         Assert.Fail("Method '{0}' from '{1}' type is marked with [Transaction] attribute, but is not declared as virtual.",
 35:                     methodInfo.Name,
 36:                     methodInfo.DeclaringType.Name);
 37:     }
 38: }
 39: 

So far, we’re pleased with how it works for us.

As always, business requirement went over existing code base to ask for a minor change that wasn’t compatible with our existing infrastructure: all surrogate keys are unique identifiers (Guid) and all infrastructure was built around that. The business people asked to add to an existing domain entity a natural key - integer identity number (auto increment field), to serve as a reference number.

We had two choices:

  • to generate the identity from business code
  • to let database manage it for us.

The second approach it preferable for us because it’s the database’s job to generate the keys.

Out of the box NHibernate doesn’t support such a thing. Answers to my question in NHibernate Users discussion group led to the next solution.

Given the class:

public class Entity
{
    public int Id { get; set; }
    public int Id2 { get; set; }
}

First “Id” is the primary key, the second is the key that we want to map to identity column. To have that done we should do two things:

  • Map “Id2″ property as “generated”
  • Use “database-object” to drop the column generated by NHibernate & create new one, with IDENTITY set on.

The complete mapping:

<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    namespace="NHibernate.Playground"
    assembly="NHibernate.Playground"
    default-lazy="false" xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity">
    <id name="Id">
      <generator class="increment" />
    </id>
    <property name="Id2" type="int" generated="always" insert="false" />
  </class>
  <database-object>
    <create>
      ALTER TABLE Entity DROP COLUMN Id2
      ALTER TABLE Entity ADD Id2 INT IDENTITY
    </create>
    <drop>
      ALTER TABLE Entity DROP COLUMN Id2
    </drop>
  </database-object>
</hibernate-mapping>

I like the flexibility offered by NHibernate. Even if you don’t have required feature, you can always use naked ADO.NET or raw SQL.

AnkhSVN

A mate came on me with “I found a wonderful SVN client which works from Visual Studio. It’s called AnkhSVN“. When I tried it last time it was in version 1.x, ugly & buggy. Having a well working TortoiseSVN I had no regrets uninstalling it.

Lately it passed a major update. It looks nicer, integrates well in VS and has all functions required for day-by-day work with Subversion. The mate who recommended it said that he found no problems during a week of trying it.

Ok. Having a refactoring to do that will involve moving few files I decided to give it a try. Moving/renaming files is one of the pain points when working with TortoiseSVN. After committing my changes to repository, the TeamCity server failed to build the project - few files was missing or had unmodified content when it should. AnkhSVN didn’t committed all changed files to repository. In VS they was shown as unmodified, but TortoiseSVN show them as changed files. A commit from TortoiseSVN has fixed the problem.

Still in doubts about it, worth keeping or not…

 

MBUnit Plugin for Resharper

I wanted to run test suite of Rhino.Mocks which uses MBUnit. First try - installed last version of MBUnit plugin for Resharper. It worked nice when I run a single test fixture. But failed to find any tests when I choose “Run Unit Tests” from context menu of a project or solution. Uninstalled.

 

Gallio Automation platform

Still wanted to run the Rhino.Mocks’s unit tests, installed Gallio a bundle that contains among others the MBUnit, a standalone test runner and yet another MBUnit integration into Resharper’s Test Runner. Results:

  • Integration with Resharper: didn’t discovered all test from test project, cannot run those discovered.
  • Standalone test runner - cannot run test suite, FixtureExecutionException.

The last two tools concerns MBUnit. All I wanted to do is just to run quickly a test suite. I can do it from console, but it’s painful and I want to do it from VS and have results there. I can do it with TestDriven.NET - but I don’t like it because found it too intrusive in my work environment. I think this is the reason why we haven’t moved to MBUnit from NUnit. It’s it superior as unit test framework, but weak tooling support make it unusable for us.

& no time now to check what is not working and how to fix it. May be later…

PS: I’ve seen it one more time: It’s very important the very first impression about something to be positive. If somebody tries your software and it blows up or doesn’t do what is it about, you fail. But this is another story…

After installation on my Vista box, TortoiseSVN cannot start, giving an entry in event log that says:

Activation context generation failed for “C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe”. Dependent Assembly Microsoft.VC90.CRT,processorArchitecture=”x86″,publicKeyToken=”1fc8b3b9a1e18e3b”,type=”win32″,version=”9.0.30411.0″ could not be found.

At first sight, the missing “Microsoft.VC90″ points to absence of Visual C++ Redistributable Package. Installing all of his versions didn’t help. After trying to work out this error, it magically disappeared and TortoiseSVN started successfully and worked well…

…until today, when I’ve upgraded to 1.5.2. Same error. Didn’t want to start. Now on two PC’s from office.

After searching for solution, found on a TortoiseSVN’s discussion lists a recipe that worked OK for me. I’ll cite it here with explanation, is given by Stefan Küng, one of TortoiseSVN developers:

try this:
uninstall TSVN, reboot, install it again.

There’s a problem with the new CRT merge module from MS: it does not recognize always that is has to update itself.

The good old way: uninstall, reboot, install. So windows95-ish.

I’m evaluating the NServiceBus communication framework for using it in some parts of application that we’re working on. I like the messaging infrastructure that it offers and how it all is implemented - behind a simple interface is hidden a modular, extensible, reliable and extremely powerful messaging engine. Sure, like any other framework, it has his own pitfalls and places that requires a special knowledge about how things works to use it efficiently.

One of those tricky places is his configuration system. To start use NServiceBus you have to do few steps to properly configure it. You have to use 2-3 “app.config” configuration sections with approximately 10-15 various parameters and few configuration classes provided by NServiceBus.

Another place that make me stuck is his integration with IoC (Inversion of Control) container. It has an abstraction over all container stuff, so you can pretty easily create an adapter to use it with container of your choice. I don’t like how this abstraction is used and implemented, a bit unnatural for my habits on how to put container to work.

Anyway, we have to deal with it, and use the NServiceBus with Castle Windsor container. As I said to do that you have to create an adapter for IBuilder interface. The NServiceBus Contrib project contains a patch that do this, but it is done in a completely wrong way - by mimicking the adapter for Spring framework. Bad, bad, bad…

So let’s take our big gun - Binsor from Rhino.Tools (I wrote about here) that should do all dirty work by configuring NServiceBus and integrating it in our existing Windsor container. The link to VS solution with all code shown here is provided at the end of the page.

Here we go - how to configure a subscriber for Pub/Sub interactions:

1. Binsor configuration (.boo file):

import System.Reflection
import NServiceBus
import NServiceBus.Unicast
import NServiceBus.Serialization
import NServiceBus.Serializers.Binary
import NServiceBus.Unicast.Transport
import NServiceBus.Unicast.Transport.Msmq
import NServiceBus.Unicast.Subscriptions
import NServiceBus.Unicast.Subscriptions.Msmq

import ObjectBuilder
import nServiceBus.CastleIntegration

component IBus, NServiceBus.Unicast.UnicastBus:
    MessageOwners = {"Messages":"messagebus"}
    MessageHandlerAssemblies = [Assembly.Load("Subscriber1")]

component ITransport, MsmqTransport:
    InputQueue = "worker"
    ErrorQueue = "error"
    NumberOfWorkerThreads = 1
    MaxRetries = 5
    IsTransactional = false
    PurgeOnStartup = false

component IMessageSerializer, MessageSerializer
component IBuilder, Builder

 

2. Program initialization:

var container = new WindsorContainer();

BooReader.Read(container, "nServiceBus.boo");

container.Register(SagasAndMessageHandlers.From(typeof(EventMessageHandler).Assembly));

var bus = container.Resolve<IBus>();

bus.Start();

 

That’s all. Now you can start send/receive messages.

For my taste this is much more readable and maintainable than traditional NServiceBus configuration. Less code, no XML, much cleaner, container friendly.

To make this work you have need for adapter class itself. His responsibility is to forward IBuilder.Build<T> calls to Castle’s Resolve<T> methods. Also, a small helper class that will register Sagas and MessageHandlers in container. Here it is:

public static class SagasAndMessageHandlers
{
    public static IRegistration[] From(params Assembly[] assemblies)
    {
        var registrations = new List<ComponentRegistration>();
        foreach (var assembly in assemblies)
        {
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                var implementedInterfaces = type.GetInterfaces();
                foreach (var interf in implementedInterfaces)
                {
                    if (!interf.IsGenericType)
                        continue;
                    var genericArguments = interf.GetGenericArguments();
                    if (genericArguments.Length != 1)
                        continue;

                    if (!typeof(IMessage).IsAssignableFrom(genericArguments[0]))
                        continue;

                    var sagaHandlerType = typeof(ISaga<>).MakeGenericType(genericArguments[0]);
                    if (sagaHandlerType.IsAssignableFrom(interf))
                    {
                        registrations.Add(CreateRegistration(type, sagaHandlerType));
                        registrations.Add(CreateRegistration(type, type));
                    }

                    var messageHandlerType = typeof (IMessageHandler<>).MakeGenericType(genericArguments[0]);
                    if (messageHandlerType.IsAssignableFrom(interf))
                        registrations.Add(CreateRegistration(type, type));
                }
            }
        }
        return registrations.ToArray();
    }

    private static ComponentRegistration CreateRegistration(Type type, Type handlerType)
    {
        string componentName;
        if (type == handlerType)
            componentName = type.FullName;
        else
            componentName = type.FullName + handlerType.FullName;

        return (ComponentRegistration)Component
                                          .For(handlerType)
                                          .ImplementedBy(type)
                                          .LifeStyle.Is(LifestyleType.Transient)
                                          .Named(componentName);
    }
}

 

One thing to notice here, NServiceBus required that a saga to be registered as a saga handler ( ISaga<Message>) and as a Saga class itself. A better way will be to use Castle’s newly added forwarding ability, when a component implementation can be accessed through multiple interfaces all forwarded to component’s instance. Bud I had no time to play with this feature yet, so this duplication will still here some time given the fact that no bugs showed up.

You can download a Visual Studio solution with all code shown here from this place. It contains all infrastructure code and two working sample projects ported from original NServiceBus samples - Pub/Sub & Saga.

Generally, the goal of integration tests is to verify that different application parts are glued well together and interacts as expected. Thus, they are a bit different thing from unit tests that tends to test how a small, separate part is acting. Below are two tests that I can’t classify to be pure integration tests because they touch a sensible part of application/infrastructure configuration like Windsor’s configuration files and NHibernate’s mappings. These simple tests can save a lot of time at very initial development stage when application bits are changed frequently and later, as a guarantee that you’ve not broken something in a recent refactoring.

Can_resolve_all_services_in_container()

Bill Simser wrote some time ago about the first test to be written when using Castle’s Windsor Container. It’s a real gem that let’s you verify if any of services registered in container can be resolved (have all required dependencies). Here is it, a bit improved for skipping verification for generic types, since, at that moment, we don’t know the generic argument for type to be constructed:

[Test]
public void Can_resolve_all_services_in_container()
{
    var container = new WindsorContainer("container.xml");
    foreach (IHandler handler in container.Kernel.GetAssignableHandlers(typeof(object)))
    {
        if (handler.ComponentModel.Service.IsGenericType)
            continue;

        container.Resolve(handler.ComponentModel.Service);
    }
}

Can_compile_NHibernate_mapping_configuration()

This test was sitting for a long time in our codebase, but I’ve seen it recently in this post of David Larebee. I wrote it in times when writing our first mappings and the only one way to verify if you don’t have any faults was to write one of CRUD operations and run the test. But that’s a long process. Shorter response cycle is always better. Here it is:

[Test]
public void Can_compile_NHibernate_mapping_configuration()
{
    ISessionFactory factory =
        new Configuration()
            .Configure()
            .AddAssembly("MyApp.MyDomainAssembly")
            .BuildSessionFactory();

    Assert.IsNotNull(factory);
}

This test suppose that you have HNibernate configuration in your app.config and tries to register all mappings from given assembly file.

 

In our projects we’re using Binsor to configure services in our Windsor container. Main reason to do that is Binsor’s extreme expressiveness. It’s much easier to write and maintain next fragment:

import MyApp.Services
component IMyService, MyService


compared with standard way of configuring components in Windsor:

<component
    id="my_service"
    type="MyApp.Services.IMyService, MyApp"
    service="MyApp.Services.MyService, MyApp" />

Difference is more evident when you have to maintain files with tens and hundreds of components. Sure, you can use some kind of “autoregistration” for components, this can reduce dramatically size of configuration files.

But, since Binsor is a kind of DSL, is not always evident how to configure complex components that have dependencies and configuration properties to specify. The Binsor’s unit tests are the place where to look for samples, but they don’t cover everything.

Today, I had to configure a NHibernateIntegration facility from Castle with Binsor. After some time I had next solution for configuring two factories:

import Castle.Facilities.NHibernateIntegration
import Rhino.Commons
import NHibernate.Playground
facility NHibernateFacility:
    configuration:
        factory:
            @id = 'factory_1'
            settings(keymap):
                dialect = 'NHibernate.Dialect.MsSql2005Dialect'
                connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
                connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
                connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test;Integrated Security=SSPI"
            assemblies:
                assembly = 'NHibernate.Playground'
    configuration:
        factory:
            @id = 'factory_2', alias = 'test2'
            settings(keymap):
                dialect = 'NHibernate.Dialect.MsSql2005Dialect'
                connection.provider = 'NHibernate.Connection.DriverConnectionProvider'
                connection.driver_class = 'NHibernate.Driver.SqlClientDriver'
                connection.connection_string = "Server=.\\SQLEXPRESS;initial catalog=test2;Integrated Security=SSPI"
            assemblies:
                assembly = 'NHibernate.Playground'

You can see here the XML way to configure NHibernate facility.

This time it’s about useful macro that speeds up writing test names. Although we’re not using yet BDD development style (BDD is for Behavior Driven Design) I like to give to my test BDD-style names. You know, something like

[Test]
public void When_user_pressed_OK_message_should_be_prepared_and_sent()
{
}

Writing down these names, when words are separated by underscores is not easy and error prone.

Fortunately, Jean-Paul S. Boodhoo has posted in his blog an updated macro for formatting test names in BDD-style manner:

Using this macro you can write test name as an usual sentence, having words separated by spaces. After running the macro it will replace all space characters by underscores.

For me it was first macro written for Visual Studio, but after some rambling within VS I have the macro running and working well. Thereafter, found these links than can help to setup and use VS macros:

It seems to be that Patterns & Practices team continues to do what they do the best - creating guidance within different development areas.

The last release of this group is the WCF Security Guidance. It contains description for a few application scenarios & a list of various How-Tos, including few video walkthroughs of common WCF solutions.

It’s different from usual way to dig into WCF infrastructure details. It’s not crawling over hundreds of MSDN pages, it’s not like reading MSDN samples trying to understand what’s going on.

It is a very detailed step-by-step description on how to do some tasks touching different aspects of WCF, starting from opening a certificates store, and ending with deployment advices.

Keep it going, P&P!

I have shown today few tricks with ReSharper to one of my teammates. I think it worth to be shared/stored in the blog.

1. View the code used from a referenced assembly

Very often you want to see how a referenced assembly is used in your project. We can use dedicated tools to work this out (for example, NDepend) or you can just click on a project in solution explorer, expand “References” node, select an assembly, right-click and select “Find Dependent Code“. You will see a nice “Find Results” window with all places where this referenced assembly is used.

Same way, you can analyze project dependencies in a multi-project solution. I think you will be rewarded in future if your presentation assemblies will not depend from a project with database stuff.

2. Setting a keyboard shortcut to run a unit test

I’m sure that any keyboard ninja knows it. Do you want to learn a bit of kung-fu? Go to keyboard settings configuration in Visual Studio (Tools > Options… > Environment > Keyboard), find a command named “ReSharper.UnitTest_ContextRun” and assign a shortcut to it. I hang it to “Ctrl+1″.

Now, when you’re editing a class containing unit tests, you can just press your newly created shortcut and ReSharper will run the tests: if you’re inside a test method (method marked with [Test]) only the current test will run; if you’re somewhere in the class, but outside of a test method, R# will run all tests from this class.