Approval testing – value for the money

I am a believer in the value of testing. However not all tests are equal, and actually not all tests provide value at all. Raise your hand if you’ve ever seen (unit) tests that tested every corner case of trivial piece of code that’s used once in a blue moon in an obscure part of the system. Raise your other hand if that test code was not written by human but generated.

 

As with any type of code, test code is a liability. It takes time to write it, and then it takes even more time to read it and maintain it. Considering time is money, rather then blindly unit testing everything we need to constantly ask ourselves how do we get the best value for the money – what’s the best way to spend time writing code, to write the least amount of it, to best cover the widest range of possible failures in the most maintainable fashion.

Notice we’re optimising quite a few variables here. We don’t want to blindly write plenty of code, we don’t want to write sloppy code, and we want the test code to properly fulfil its role as our safety net, alarming us early when things are about to go belly up.

Testing conventions

What many people seem to find challenging to test is conventions in their code. When all you have is a hammer (unit testing) it’s hard to hit a nail, that not only isn’t really a nail, but isn’t really explicitly there to being with. To make matters worse the compiler is not going to help you really either. How would it know that LoginController not implementing IController is a problem? How would it know that the new dependency you introduced onto the controller is not registered in your IoC container? How would it know that the public method on your NHibernate entity needs to be virtual?

 

In some cases the tool you’re using will provide some level of validation itself. NHibernate knows the methods ought to be virtual and will give you quite good exception message when you set it up. You can verify that quite easily in a simple test. Not everything is so black and white however. One of diagnostics provided by Castle Windsor is called “Potentially misconfigured components”. Notice the vagueness of the first word. They might be misconfigured, but not necessarily are – it all depends on how you’re using them and the tool itself cannot know that. How do you test that efficiently?

Enter approval testing

One possible solution to that, which we’ve been quite successfully using on my current project is approval testing. The concept is very simple. You write a test that runs producing an output. Then the output is reviewed by someone, and assuming it’s correct, it’s marked as approved and committed to the VCS repository. On subsequent runs the output is generated again, and compared against approved version. If they are different the test fails, at which point someone needs to review the change and either mark the new version as approved (when the change is legitimate) or fix the code, if the change is a bug.

 

If the explanation above seems dry and abstract let’s go through an example. Windsor 3 introduced way to programmatically access its diagnostics. We can therefore write a test looking through the potentially misconfigured components, so that we get notified if something on the list changes. I’ll be using ApprovalTests library for that.

[Test] 
pub­lic void Approved_potentially_misconfigured_components() 
{ 
    var con­tainer = new Wind­sor­Con­tainer(); 
    container.Install(FromAssembly.Containing<HomeController>());

    var han­dlers = GetPotentiallyMisconfiguredComponents(container); 
    var mes­sage = new String­Builder(); 
    var inspec­tor = new DependencyInspector(message); 
    fore­ach (IEx­poseDe­pen­den­cy­Info han­dler in han­dlers) 
    { 
        handler.ObtainDependencyDetails(inspector); 
    } 
    Approvals.Approve(message.ToString()); 
}

pri­vate sta­tic IHan­dler[] GetPotentiallyMisconfiguredComponents(WindsorContainer con­tainer) 
{ 
    var host = container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey) as IDi­ag­nos­tic­sHost; 
    var diag­nos­tic = host.GetDiagnostic<IPotentiallyMisconfiguredComponentsDiagnostic>(); 
    var han­dlers = diagnostic.Inspect(); 
    return han­dlers; 
}

What’s important here is we’re setting up the container, getting the misconfigured components out of it, produce readable output from the list and passing it down to the approval framework to do the rest of the job.

Now if you’ve set up the framework to pup-up a diff tool when the approval fails you will be greeted with something like this:

approval_diff

You have all the power of your diff tool to inspect the change. In this case we have one new misconfigured component (HomeController) which has a new parameter, appropriately named missingParameter that the container doesn’t know how to provide to it. Now you either slap yourself in the forehead and fix the issue, if that really is an issue, or approve that dependency, by copying the diff chunk from the left pane to the right, approved pane. By doing the latter you’re notifying the testing framework and your teammates that you do know what’s going on and you know it’s not an issue the way things are going to work. Coupled with a sensible commit message explaining why you chose to approve this difference you get a pretty good trail of exception to the rule and reasons behind them.

 

That’s quite an elegant approach to a quite hard problem. We’re using it for quite a few things, and it’s been giving us really good value for little effort it took to write those tests, and maintain them as we keep developing the app, and the approved files change.

 

So there you have it, a new, useful tool in your toolbelt.

Contextual controller injection in ASP.NET MVC with Castle Windsor

I chatting the other day with Chris Canal, who played with reimplementing piece of code Jimmy Bogard put on his blog using Castle Windsor.

While I’m not an ASP.NET MVC expert by no means, I decided to give it a go and try to do it myself. See Jimmy’s post first to get the context, as I’m only going to talk about the code.

The code here uses development build of Windsor (what will become version 2.5) and does not work with version 2.1

No child container

Jimmy used child container to scope the contextual dependencies. While this is also possible using Windsor, it feels like using shotgun to kill a fly. We can use contextual meta-components that will have the sole purpose of scoping our RequestContext and ControllerContext and achieve the same effect as if we were using child container, only this is far more lightweight.

public class ControllerContextHost

{

    private ControllerBase controller;

 

    public void SetController( ControllerBase controller )

    {

        if( controller != null )

        {

            throw new InvalidOperationException( "Controller was already set!" );

        }

        this.controller = controller;

 

    }

 

    public ControllerContext GetContext()

    {

        if( controller == null )

        {

            return null;

        }

        return controller.ControllerContext;

    }

}

 

public class RequestContextHost

{

    private RequestContext context;

    public void SetContext( RequestContext context )

    {

        if( context != null )

        {

            throw new InvalidOperationException( "Context was already set!" );

        }

        this.context = context;

    }

    public RequestContext GetContext()

    {

        if( context == null )

        {

            throw new InvalidOperationException( "Context was not set!" );

        }

        return context;

    }

}

Having that we can now simply use the hosts to cache their respective components. We set the RequestContext in ControllerFactory.

public IController CreateController( RequestContext requestContext, string controllerName )

{

    var host = this.container.Resolve<RequestContextHost>();

    host.SetContext( requestContext );

    return container.Resolve<IController>( controllerName );

}

Registration

ControllerContext has a twist. Since we register controllers as transient, we have to pass the controller to ControllerContextHost right after it gets created. We use OnCreate method for that.

public void Install(IWindsorContainer container, IConfigurationStore store)

{

    container.Register(AllTypes.FromAssemblyContaining<HomeController>()

                            .BasedOn<IController>()

                            .Configure(x => x.LifeStyle.Transient

                                                    .Named(GetControllerName(x.Implementation))

                                                    .OnCreate((k, c) => k.Resolve<ControllerContextHost>()

                                                                            .SetController(c as ControllerBase))));

}

It is also important how we register the services:

public void Install( IWindsorContainer container, IConfigurationStore store )

{

    container.Register( Component.For<ControllerContextHost>().LifeStyle.PerWebRequest,

                        Component.For<RequestContextHost>().LifeStyle.PerWebRequest,

                        Component.For<RequestContext>()

                            .UsingFactoryMethod( k => k.Resolve<RequestContextHost>().GetContext() ),

                        Component.For<HttpContextBase>()

                            .UsingFactoryMethod( k => k.Resolve<RequestContext>().HttpContext ),

                        Component.For<Func<ControllerContext>>()

                            .UsingFactoryMethod<Func<ControllerContext>>(

                                k => k.Resolve<ControllerContextHost>().GetContext ) );

}

Both hosts are registered as per web request since that’s how we want to cache the contexts they host. We’re only going to use the hosts internally and not expose them. Hence we register the contexts via UsingFactoryMethod. We also don’t register the ControllerContext directly, but rather via Func delegate, to break cyclic dependency between ControllerContext and Controller.

Now we only need to register the remaining services we want to use:

public void Install( IWindsorContainer container, IConfigurationStore store )

{

    container.Register(

        Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Transient,

        Component.For<IActionInvoker>().ImplementedBy<ControllerActionInvoker>().LifeStyle.Transient,

        Component.For<ITempDataProvider>().ImplementedBy<SessionStateTempDataProvider>().LifeStyle.Transient,

        Component.For<RouteCollection>().Instance( RouteTable.Routes ),

        Component.For<UrlHelper>().LifeStyle.Transient );

}

and we’re free to take dependency on IFoo, which has dependency on our contextual services. Just for completeness, here’s code registering all the components in the container:

this._windsorContainer = new WindsorContainer()

    .Install( FromAssembly.This() );

And now, assuming I didn’t mis-translate Jimmy’s StructureMap code, out application should work just like his sample.

Castle Windsor forwarded types and proxies

Castle Windsor allows you to use single component for multiple services, which is called Forwarded Types.

Forwarded Types

In other words, you can tell Windsor – when IFoo is requested use FooBar as implementation, and when Bar is requested also use FooBar (when using default lifestyle of singleton you’ll get the same instance).

Here’s some code:

var container = new WindsorContainer();
container.Register(Component.For<Bar>().Forward<IFoo>()
                       .ImplementedBy<FooBar>());
var foo = container.Resolve<IFoo>();
var bar = container.Resolve<Bar>();
Debug.Assert(foo == bar);
foo.DoFoo();
bar.DoBar();
Console.ReadKey(true);

Proxies

What if you want to use proxies for that component though?

var container = new WindsorContainer();
container.Register(Component.For<IInterceptor>()
                       .Named("interceptor")
                       .ImplementedBy<FooBarInterceptor>(),
                   Component.For<Bar>().Forward<IFoo>()
                       .ImplementedBy<FooBar>()
                       .Interceptors(new InterceptorReference("interceptor")).Anywhere);
var foo = container.Resolve<IFoo>();
var bar = container.Resolve<Bar>();
Debug.Assert(foo == bar);
foo.DoFoo();
bar.DoBar();
Console.ReadKey(true);

Now, what happens next depends on how you implemented the interface IFoo on class FooBar. Say this is FooBar:

public class FooBar : Bar, IFoo
{
    public void DoFoo()
    {
        Console.WriteLine("DoFoo");
    }
 
    public override void DoBar()
    {
        Console.WriteLine("DoBar");
    }
}

Notice that DoFoo is non-virtual. In this case, here’s what we’re gonna get.

windsor_1

DoFoo did not get intercepted. So what’s the issue here, and how do we fix it?

The What

When you forward a registration, Windsor runs just the first type through the complete registration pipeline, and subsequent forwarded types are treated just as additional piece of data “Oh, by the way, use this component I just registered for this type as well”. Proxy registration is a part of the component model building, and since we end up having just one component only information about its main type gets recorded for proxying.

While this might appear at first clearly as a bug, I think it’s rather a by-design feature. Forcing Windsor to figure it out by itself could pretty quickly become very tricky and we might not always get what we expected. There are however ways of getting what we want.

The fix no 1

Now that we know what we’re up against, how do we fix it? First and the most trivial fix would be simply to make the DoFoo virtual – this way it would get picked when proxying Bar base class and we could successfully proxy it. While this may not always be applicable (you may not be able to modify the class) this is the only option that is available if you’re using the released version. However if you’re using trunk there are two more possible ways of bending it to our will.

Meet my attributes

Due to some changes in how Dynamic Proxy 2.2 (current trunk) handles additional interfaces to proxy, it is possible to intercept non-virtually implemented interface members on a class proxy. Since Windsor by default will request just the class proxy (with no additional interfaces) we need to tell it to toss an IFoo attribute in as well. The quickest way of doing it is throwing an attribute on top of our class:

[ComponentProxyBehavior(AdditionalInterfaces = new[] { typeof(IFoo) })]
public class FooBar : Bar, IFoo
{
    public void DoFoo()
    {
        Console.WriteLine("DoFoo");
    }
 
    public override void DoBar()
    {
        Console.WriteLine("DoBar");
    }
}

If we run the code now we’ll get this:

windsor_2

This is not a solution most people would choose anyway. Even if you can do it (your service does not come from a 3rd party library), you’re decorating your service class with a Windsor-specific attribute which many consider an anti-pattern. There’s however a third, more pure way.

Remember that you need trunk version of Dynamic Proxy for this to work. If you use version 2.1 you’ll end up with this instead:

windsor_3

Windsor will implement the interface, but it will treat it as interface proxy without target. You can make it work by inserting a dedicated interceptor that will forward the calls to your class, but it’s something you’ll have to do manually all the way through.

Black belt approach

I said that forwarded types don’t get ran through whole registration pipeline. However, kernel does raise its component lifecycle events for them, so we can hook up to them and get notified when our forwarding handler gets registered, and modify its component model.

We start by hooking up to kernels HandlerRegistered event, before we register any components.

var container = new WindsorContainer();
container.Kernel.HandlerRegistered += OnHandlerRegistered;

In the OnHandlerRegistered method we check whether the handler at hand is a ForwardingHandler and if so we add its interface to the list of additional interfaces we want to proxy, just like we did using attribute in the example above.

static void OnHandlerRegistered(Castle.MicroKernel.IHandler handler, ref bool stateChanged)
{
    var forwardingHandler = handler as ForwardingHandler;
 
    if (forwardingHandler == null)
        return; //we're only interested in forwarding handlers...
 
    if(!forwardingHandler.Service.IsInterface)
        return; //we're only interested in interface services...
 
    var targetHandler = forwardingHandler.Target;
    if(!targetHandler.ComponentModel.ExtendedProperties.Contains(ProxyConstants.ProxyOptionsKey))
        return; //apparently this service is not registered for proxying
 
    var options = targetHandler.ComponentModel.ExtendedProperties[ProxyConstants.ProxyOptionsKey] as ProxyOptions;
    Debug.Assert(options != null);
 
    options.AddAdditionalInterfaces(forwardingHandler.Service);
}

Now we get our interface proxied without having to touch our component’ code.

Technorati Tags:

Testing with NHibernate and SQLite

warninglabel

There does not seem to be too much details on how to set up a test environment for NHibernate testing using SQLite. Ayende has a nice post on this, but he does not go into details of how, what and where, so I decided to fill in the blanks, and provide an up to date sample for NHibernate 2.1.

Let’s first gather all the things we need:

Now we need to add references to all these projects. Make sure you add correct reference to System.Data.SQLite (either x86 version from the main directory, or x64 version from x64 folder if you’re running on 64bits).

You also can’t add reference to sqlite3.dll, because it’s an unmanaged dll. I simply add it as element to solution and set it to copy to output directory. After all, your solution should look roughly like this:

NHibernate_tests

I also have a base class for my tests that does all the setup for me. Here’s how it looks like:

[TestFixture]
public abstract class DbTestsBase<T>
{
    protected ISessionFactory factory;
    protected T sut;
 
    private string dbFile;
 
    public void Init(params Assembly[] assembliesWithMappings)
    {
        dbFile = GetDbFileName();
        EnsureDbFileNotExists();
 
        NHibernateProfiler.Initialize();
        var configuration = new Configuration()
            .AddProperties(new Dictionary<string, string>
                               {
                                   { Environment.ConnectionDriver, typeof( SQLite20Driver ).FullName },
                                   { Environment.Dialect, typeof( SQLiteDialect ).FullName },
                                   { Environment.ConnectionProvider, typeof( DriverConnectionProvider ).FullName },
                                   { Environment.ConnectionString, string.Format( "Data Source={0};Version=3;New=True;", dbFile) },
                                   { Environment.ProxyFactoryFactoryClass, typeof( ProxyFactoryFactory ).AssemblyQualifiedName },
                                   { Environment.Hbm2ddlAuto, "create" },
                                   { Environment.ShowSql, true.ToString() }
                               });
        foreach (var assembly in assembliesWithMappings)
        {
            configuration.AddAssembly(assembly);
        }
 
        new Remapper().Remap(configuration);
 
        factory = configuration.BuildSessionFactory();
    }
 
    [TearDown]
    public void TearDownTests()
    {
        factory.Dispose();
        EnsureDbFileNotExists();
        NHibernateProfiler.Stop();
    }
 
    private string GetDbFileName()
    {
        var path = Path.GetFullPath(Path.GetRandomFileName() + ".Test.db");
        if (!File.Exists(path))
        {
            return path;
        }
 
        // let's try again
        return GetDbFileName();
    }
 
    private void EnsureDbFileNotExists()
    {
        if (File.Exists(dbFile))
        {
            File.Delete(dbFile);
        }
    }
}

There are couple interesting points in this code:

I expose the SessionFactory, not Session. That’s because I use this class for testing repositories in stateful application, that manage the session themselves.

I save the database to file, instead of keeping it in memory like Ayende does. That’s connected to the previous fact. Apparently, in-memory database only lives as long as session that created it, which does not cut it for me.

I then use the class like this:

[TestFixture]
class Entity1Tests : DbTestsBase<Entity1>
{
    [SetUp]
    public void SetUp()
    {
        base.Init(typeof(Entity1).Assembly);
    }
 
    [Test]
    public void Member_should_action()
    {
        //some code
    }
}

Pretty simple and so far, covers my needs.

Technorati Tags: ,,

Solving a programming puzzle

My fellow devlicio.us blogger Tim Barcz posted an interesting problem to solve. I think it’s fun, so I decided to give it a try. Now, I don’t know enough context to solve it for just about any case (and I don’t think that’s even possible), so I made a few assumptions.

  • The strings we’re gonna be handling are not too long. Otherwise I’d probably use a StringReader/Writer.
  • I’m looking at minimal solution. YAGNI – I could do some optimizations probably, but I want to keep it simple, because the sample problem (just a handful of characters) is simple.
  • Solution is not context specific. In other words, if you want to swap characters differently based on context, it won’t do it. Again, I’m keeping it simple.
  • I’m using a factory here, to create the cleaner and feed it with mapping but based on the needs and tools available, I’d probably use an IoC container to get the instance, and if needed get the mapping from an external file, where it’s more readable, and can be easily changed.

Now, here’s the code:

public string CleanInput( string input )
{
    StringCleaner cleaner = CleanerFactory.BuildCleaner( input );
    return cleaner.Clean( input );
}

The CleanerFactory is not important. All it does is construct an instance of a StringCleaner and feed it with the mapping. However, I’ll post it for completeness:

public static class CleanerFactory
{
    public static StringCleaner BuildCleaner( string input )
    {
 
        var cleaner = new StringCleaner();
        BuildMapping( cleaner );
        return cleaner;
    }
 
    private static void BuildMapping( StringCleaner cleaner )
    {
        /*
         *  Character         Correct ASCII Value     Bad Values
            Hyphen             45                         8208, 8211, 8212, 8722, 173, 8209, 8259
            Single Quote     39                         96, 8216, 8217, 8242, 769, 768
            Double Quote     34                         8220, 8221, 8243, 12291
            Space             32                         160, 8195, 8194
         */
        cleaner.AddMapping( (char) 45, (char) 8208, (char) 8211, (char) 8212, (char) 8722, (char) 173, (char) 8209, (char) 8259 );
        cleaner.AddMapping( (char) 39, (char) 96, (char) 8216, (char) 8217, (char) 8242, (char) 769, (char) 768 );
        cleaner.AddMapping( (char) 34, (char) 8220, (char) 8221, (char) 8243, (char) 12291 );
        cleaner.AddMapping( (char) 32, (char) 160, (char) 8195, (char) 8194 );
    }
}

The cleaner itself looks like this:

public class StringCleaner
{
        private IDictionary<char,char> mappings = new Dictionary<char, char>();
 
        public string Clean( string input )
        {
            if( string.IsNullOrEmpty( input ) )
            {
                return string.Empty;
            }
 
            var buffer = new StringBuilder( input );
            for( int i = 0; i < buffer.Length; i++ )
            {
                var character = buffer[i];
                char validCharacter;
                if( this.mappings.TryGetValue( character, out validCharacter ) )
                {
                    buffer[ i ] = validCharacter;
                }
            }
 
            return buffer.ToString();
        }
 
        public void AddMapping( char validValue, params char[] invalidValues)
        {
            if( invalidValues == null )
            {
                throw new ArgumentNullException( "invalidValues" );
            }
 
            foreach( var invalidValue in invalidValues )
            {
                this.mappings[ invalidValue ] = validValue;
            }
        }
}

Since strings are immutable, I’m using a StringBuilder to iterate over all the characters in the string, and replace these I want. I’m using Dictionary for the mapping, because it has a readable API, and O(1) search time.

WCF service host builder

When you have a WCF service that is not a singleton, and you want to use non-default constructor, you enter a world of pain. There’s a lot of hoops that you have to go through to plug an IInstanceProvider into the service. Even worse if you have many services. To alleviate the pain, I created a small helper method.

private ServiceHost GetService<TService>( string address, Func<TService> createServiceInstance )
{
    var service = new ServiceHost( typeof( TService ) ); 
 
    var serviceInstanceFactoryBehavior = new ServiceInstanceFactoryBehavior( () => createServiceInstance() );
    var endpoint = service.AddServiceEndpoint( typeof( TService ).GetInterfaces().Single(), this.GetBinding(), address );
    endpoint.Contract.Behaviors.Add( serviceInstanceFactoryBehavior );
    return service;
}
 

It is based on few assumptions:

  • All service types implement just one contract (which I think you should strive for anyway).
  • All services use the same binding.

ServiceInstanceFactoryBehavior plugs a custom IInstanceProvider into the host, that uses the provided delegate to fabricate new instances.

As a sidenote, Castle WCF integration facility can do this (in a much more flexible manner), but unfortunately we can’t use it.

Technorati Tags:

Framework Tips XII: Advanced .NET delegates

All .NET delegates inherit (indirectly) from System.Delegate class (and directly from System.MulticastDelegate) which has a static CreateDelegate method. The method has two powerful characteristics that are not widely known.

All delegate types are implemented by the runtime. What do I mean by that? Let’s have a look at how any delegate type looks at the IL level:

delegateInIL

All methods are runtime managed, meaning that, in a similar fashion you provide implementation for interface methods, runtime provides implementation for delegate methods. Take a look at the constructor. Regardless of delegate type it always has two arguments: object (on which a method will be invoked via the delegate) and a handle to that method.

While trying (with great help of Kenneth Xu) to find a way of providing proxying of explicitly implemented interface members in Dynamic Proxy, I saw this as a possible way of being able to implement the feature. The problem in this case is, that proxy is an inherited class, that has to call a private method on the base class. So given that Dynamic Proxy works in IL, I tried to call that constructor in IL passing required parameters, but unsurprisingly, runtime does access checks so what I got instead of working delegate was this:

MethodAccessException

 

 

Kenneth suggested another approach – using Delegate.CreateDelegate, because as it turns out, you can successfully use that method to bind delegates to private methods. That is the first important characteristic that may be a life saver in certain cases.

So, instead of this (which won’t compile):

public override int BarMethod(int num1)
{
    Func<int, int> d = new Func<int, int>(this.DynamicProxy.Program.IFoo.BarMethod);
    return d(num1);
}

You can use this, which will both compile and work:

public override int BarMethod(int num1)
{
    Func<int, int> d = Delegate.CreateDelegate(typeof(Func<int, int>), this, barMethodInfo) as Func<int, int>;
    return d(num1);
}

It has a drawback though – it’s order of magnitude slower than creating the delegate via its constructor. Solution brings us to the second characteristic I wanted to talk about – open instance methods.

Each instance method at IL level has an additional argument, implicitly passed this pointer. Armed with this knowledge, let’s read what MSDN says about Delegate.CreateDelegate and open instance methods:

If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:

  • If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

This basically says that we can bind method to delegate that passes the ‘this’ argument explicitly, so that we can reuse the delegate for multiple instances. Here’s how that works:

private static Func<Foo, int, int> d;
 
static Foo()
{
    d = Delegate.CreateDelegate(typeof(Func<Foo, int, int>), barMethodInfo) as Func<Foo, int, int>;
}
 
public override int BarMethod(int num1)
{
    return d(this, num1);
}

With this approach we pay the price of delegate creation only once per lifetime of the type.

I was curious how all these approaches would perform, so I created a quick poor-man’s benchmark.

I invoked an instance method 100 times using four approaches:

  1. directly
  2. via delegate created using its constructor
  3. via delegate created using CreateDelegate passing first argument explicitly (not null).
  4. via delegate created once using CreateDelegate and then reusing it for subsequent calls.

Here are the results (times are in ticks):

poormansDelegateBenchmark

As you can see, when reusing the instance after 100 calls we can achieve the same performance as when using the delegate’s constructor, which, given we can use in broader spectrum of cases, is pretty amazing.

If you want to run the tests for yourself, the code is here.

Technorati Tags: ,,,

The biggest hack I have ever written

Not that I’m proud of that, but to circumvent the limitations of CLR and C# I sometimes had to use reflection, code generation, changing behavior depending on who’s calling etc.

However I think this code beats all that.

public static class HandleProvider
{
    private static int _currentToken = typeof(object).GetConstructors()[0].MetadataToken;
    private static ModuleHandle _moduleHandle = typeof(object).Module.ModuleHandle;
 
    /// <summary>
    /// This is an ugly hack to circumvent lack of useful public constructor on RuntimeMethodHandle struct
    /// </summary>
    /// <returns>Method handle of some method from mscorlib</returns>
    [MethodImpl(MethodImplOptions.Synchronized)]
    public static RuntimeMethodHandle GetNextHandle()
    {
        /* Since we need RuntimeMethodHandles and the struct does not have a constructor we can use, we need some other way of obtaining these.
         * We're stealing them from mscorlib. We can (hopefully) do this, because it's only for AsyncType's Begin/End methods.
         * Their handles are used (not that this is just internal implementation detail which can change and thus breaking my code) only
         * as keys in the dicionary so we only need to have different ones, and we should be fine.
         */
 
 
        return _moduleHandle.GetRuntimeMethodHandleFromMetadataToken(_currentToken++);
    }
}

It’s a part of my effort to enable asyncronous calls on WCF proxies created via ChannelFactory. You can see the whole code here.

Read only collections and properties with NHibernate

warningsign

I’ve been working with NHibernate for the last couple of days, and as I make my way though it, I find out about things, that were not so obvious to me at first, so I decided to post them here, so that someone else can benefit as well.

First thing you learn about NHibernate (well ok – first thing I learned about NHibernate, but most of you probably as well) is that it requires you to mark your properties virtual, have parameterless constructor, and pay special attention to your GetHashCode() and Equals() methods.

With all that in mind (and following many tutorial that are out there) you may start crunching your entity classes to look like this:

public class Person
{
    public virtual Guid Id { get; set; }
    public virtual ISet<Pet> Pets{ get; set; }
    public virtual bool HasPets 
    { 
        get { return Pets.Count > 0; } 
        set { /*do nothing*/}
    }
}

with mapping like this:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="ConsoleApplication1" assembly="ConsoleApplication1">
  <class name="Person">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <property name="HasPets"/>
    <set name="Pets" cascade="all" >
      <key column="OwnerId" />
      <one-to-many class="Pet" />
    </set>      
  </class>
</hibernate-mapping>

This gets the job done, but it’s far from being persistence ignorant. You usually don’t want to expose a setter for your collections, so that they can be swapped. Also the set accessor on HasPets property is nothing short of an ugly hack. Although we have no explicit sign of NHibernate in the code, it is anything but persistence ignorant.

You can however make it so.

public class Person
{
    private readonly ISet<Pet> _pets = new HashedSet<Pet>();
 
    public virtual Guid Id { get; protected set; }
 
    public virtual ISet<Pet> Pets { get { return _pets; } }
 
    public virtual bool HasPets
    {
        get { return Pets.Count > 0; }
    }
}

Now it looks like a “normal” class. Will it work with NHibernate now though? – Absolutely*. The trick is to use mapping files appropriately.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="ConsoleApplication1" assembly="ConsoleApplication1">
  <class name="Person">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <property name="HasPets" access="readonly"/>
    <set name="Pets" cascade="all" access="nosetter.camelcase-underscore" >
      <key column="OwnerId" />
      <one-to-many class="Pet" />
    </set>      
  </class>
</hibernate-mapping>

 

What’s changed? I added the access attributes to the mappings.

For HasPets I set it to readonly. That way NHibernate will read the property and use its value when doing INSERTs and UPDATEs, but will not include it in SELECTs.

For Pets one-to-many mapping I used value that tells NHibernate to use the getter to read the value of the property, and to write to the field directly, and that field name is _pets (by convention). There are quite a few more options, and you can use them to do some pretty powerful things, like enforcing consistency in two-way *-to-many mappings.

 

* the access=”readonly” is new to NHibernate v2.1

DNK Tags:

Creating tree of dependencies with MEF

As a follow up to my previous post, here’s the simplified – Console based version of the code.

Disclaimer.

This is a solution. Not the best one, not recommended by anyone, just the one that happened to solve my problem. So take it with a (big) grain of salt, and if you know a better one, use the Leave your comment function below.

using System;
using System.ComponentModel.Composition;
using System.Reflection;
 
[assembly:AllowNonPublicComposition]
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ComposablePartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
 
            var container = new CompositionContainer(catalog.CreateResolver());
 
            var shell = new Shell();
 
            container.AddPart(shell);
            container.Compose();
            shell.View();
 
            Console.ReadKey(true);
        }
    }
 
    public class Shell
    {
        [Import("View")]
        private IShellView _view;
 
 
        public void View()
        {
            if (_view == null)
            {
                Console.WriteLine("view is null");
            }
            else
            {
                _view.Show();
            }
 
        }
    }
 
    public interface IShellView
    {
        void Show();
    }
 
    [Export(typeof(IMyView))]
    class ShellView : IShellView, IMyView
    {
        public void Show()
        {
            Go(this, EventArgs.Empty);
            Console.WriteLine(SomeProperty);
        }
        public event EventHandler Go;
        public string SomeProperty
        {
            set;
            private get;
        }
    }
 
 
    public interface IMyView
    {
        event EventHandler Go;
        string SomeProperty { set; }
    }
 
    public class Presenter
    {
        [Export("View")]
        private IMyView _view;
 
        [ImportingConstructor]
        public Presenter(IMyView view, IModel model)
        {
            this._view = view;
            _view.Go += delegate { _view.SomeProperty = model.Text; };
        }
    }
 
    public interface IModel
    {
        string Text { get; }
    }
 
    [Export(typeof(IModel))]
    class Model : IModel
    {
        public string Text
        {
            get { return DateTime.UtcNow.ToString(); }
        }
    }
}

The thing to note is, that the Export with the key “View” and of type IShellView is not provided directly by any type implementing the interface. Instead it its exported by the presenter, as a field that gets set by MEF via constructor. That way, when the Shell needs the “View” MEF sees that it needs to create a Presenter for that, and in order to create presenter it needs to use the ImportingConstructor, and provide it with IMyView and IModel. Since the type implementing the IView is IMyView it gets injected into the Presenter. Also, since it implements IShellView as well, it satisfies the needs of Shell and gets injected into it.

Pretty sweet, and no code was required to achieve this (except for some Attribute magic).

Technorati Tags: