Archive for the ‘code snippets’ Category

Approval testing – value for the money

Monday, January 16th, 2012

I am a believer in the value of test­ing. How­ever not all tests are equal, and actu­ally not all tests pro­vide value at all. Raise your hand if you’ve ever seen (unit) tests that tested every cor­ner case of triv­ial piece of code that’s used once in a blue moon in an obscure part of the sys­tem. Raise your other hand if that test code was not writ­ten by human but generated.

 

As with any type of code, test code is a lia­bil­ity. It takes time to write it, and then it takes even more time to read it and main­tain it. Con­sid­er­ing time is money, rather then blindly unit test­ing every­thing we need to con­stantly ask our­selves how do we get the best value for the money – what’s the best way to spend time writ­ing code, to write the least amount of it, to best cover the widest range of pos­si­ble fail­ures in the most main­tain­able fashion.

Notice we’re opti­mis­ing quite a few vari­ables 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 prop­erly ful­fil its role as our safety net, alarm­ing us early when things are about to go belly up.

Test­ing conventions

What many peo­ple seem to find chal­leng­ing to test is con­ven­tions in their code. When all you have is a ham­mer (unit test­ing) it’s hard to hit a nail, that not only isn’t really a nail, but isn’t really explic­itly there to being with. To make mat­ters worse the com­piler is not going to help you really either. How would it know that Login­Con­troller not imple­ment­ing ICon­troller is a prob­lem? How would it know that the new depen­dency you intro­duced onto the con­troller is not reg­is­tered in your IoC con­tainer? How would it know that the pub­lic method on your NHiber­nate entity needs to be virtual?

 

In some cases the tool you’re using will pro­vide some level of val­i­da­tion itself. NHiber­nate knows the meth­ods ought to be vir­tual and will give you quite good excep­tion mes­sage when you set it up. You can ver­ify that quite eas­ily in a sim­ple test. Not every­thing is so black and white how­ever. One of diag­nos­tics pro­vided by Cas­tle Wind­sor is called “Poten­tially mis­con­fig­ured com­po­nents”. Notice the vague­ness of the first word. They might be mis­con­fig­ured, but not nec­es­sar­ily are – it all depends on how you’re using them and the tool itself can­not know that. How do you test that efficiently?

Enter approval testing

One pos­si­ble solu­tion to that, which we’ve been quite suc­cess­fully using on my cur­rent project is approval test­ing. The con­cept is very sim­ple. You write a test that runs pro­duc­ing an out­put. Then the out­put is reviewed by some­one, and assum­ing it’s cor­rect, it’s marked as approved and com­mit­ted to the VCS repos­i­tory. On sub­se­quent runs the out­put is gen­er­ated again, and com­pared against approved ver­sion. If they are dif­fer­ent the test fails, at which point some­one needs to review the change and either mark the new ver­sion as approved (when the change is legit­i­mate) or fix the code, if the change is a bug.

 

If the expla­na­tion above seems dry and abstract let’s go through an exam­ple. Wind­sor 3 intro­duced way to pro­gram­mat­i­cally access its diag­nos­tics. We can there­fore write a test look­ing through the poten­tially mis­con­fig­ured com­po­nents, so that we get noti­fied if some­thing on the list changes. I’ll be using Approval­Tests 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 impor­tant here is we’re set­ting up the con­tainer, get­ting the mis­con­fig­ured com­po­nents out of it, pro­duce read­able out­put from the list and pass­ing it down to the approval frame­work to do the rest of the job.

Now if you’ve set up the frame­work to pup-up a diff tool when the approval fails you will be greeted with some­thing like this:

approval_diff

You have all the power of your diff tool to inspect the change. In this case we have one new mis­con­fig­ured com­po­nent (Home­Con­troller) which has a new para­me­ter, appro­pri­ately named miss­ing­Pa­ra­me­ter that the con­tainer doesn’t know how to pro­vide to it. Now you either slap your­self in the fore­head and fix the issue, if that really is an issue, or approve that depen­dency, by copy­ing the diff chunk from the left pane to the right, approved pane. By doing the lat­ter you’re noti­fy­ing the test­ing frame­work and your team­mates that you do know what’s going on and you know it’s not an issue the way things are going to work. Cou­pled with a sen­si­ble com­mit mes­sage explain­ing why you chose to approve this dif­fer­ence you get a pretty good trail of excep­tion to the rule and rea­sons behind them.

 

That’s quite an ele­gant approach to a quite hard prob­lem. We’re using it for quite a few things, and it’s been giv­ing us really good value for lit­tle effort it took to write those tests, and main­tain them as we keep devel­op­ing the app, and the approved files change.

 

So there you have it, a new, use­ful tool in your toolbelt.

Contextual controller injection in ASP.NET MVC with Castle Windsor

Saturday, May 22nd, 2010

I chat­ting the other day with Chris Canal, who played with reim­ple­ment­ing piece of code Jimmy Bog­ard put on his blog using Cas­tle Wind­sor.

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 con­text, as I’m only going to talk about the code.

The code here uses devel­op­ment build of Wind­sor (what will become ver­sion 2.5) and does not work with ver­sion 2.1

No child container

Jimmy used child con­tainer to scope the con­tex­tual depen­den­cies. While this is also pos­si­ble using Wind­sor, it feels like using shot­gun to kill a fly. We can use con­tex­tual meta-components that will have the sole pur­pose of scop­ing our Request­Con­text and Con­troller­Con­text and achieve the same effect as if we were using child con­tainer, 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;

    }

}

Hav­ing that we can now sim­ply use the hosts to cache their respec­tive com­po­nents. We set the Request­Con­text in ControllerFactory.

public IController CreateController( RequestContext requestContext, string controllerName )

{

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

    host.SetContext( requestContext );

    return container.Resolve<IController>( controllerName );

}

Reg­is­tra­tion

Con­troller­Con­text has a twist. Since we reg­is­ter con­trollers as tran­sient, we have to pass the con­troller to Con­troller­Con­tex­tHost right after it gets cre­ated. We use OnCre­ate 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 impor­tant how we reg­is­ter 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 reg­is­tered as per web request since that’s how we want to cache the con­texts they host. We’re only going to use the hosts inter­nally and not expose them. Hence we reg­is­ter the con­texts via Using­Fac­to­ryMethod. We also don’t reg­is­ter the Con­troller­Con­text directly, but rather via Func del­e­gate, to break cyclic depen­dency between Con­troller­Con­text and Controller.

Now we only need to reg­is­ter the remain­ing ser­vices 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 depen­dency on IFoo, which has depen­dency on our con­tex­tual ser­vices. Just for com­plete­ness, here’s code reg­is­ter­ing all the com­po­nents in the container:

this._windsorContainer = new WindsorContainer()

    .Install( FromAssembly.This() );

And now, assum­ing I didn’t mis-translate Jimmy’s Struc­tureMap code, out appli­ca­tion should work just like his sample.

Castle Windsor forwarded types and proxies

Thursday, October 22nd, 2009

Cas­tle Wind­sor allows you to use sin­gle com­po­nent for mul­ti­ple ser­vices, which is called For­warded Types.

For­warded Types

In other words, you can tell Wind­sor – when IFoo is requested use Foo­Bar as imple­men­ta­tion, and when Bar is requested also use Foo­Bar (when using default lifestyle of sin­gle­ton 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);

Prox­ies

What if you want to use prox­ies for that com­po­nent 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 hap­pens next depends on how you imple­mented the inter­face IFoo on class Foo­Bar. 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 inter­cepted. So what’s the issue here, and how do we fix it?

The What

When you for­ward a reg­is­tra­tion, Wind­sor runs just the first type through the com­plete reg­is­tra­tion pipeline, and sub­se­quent for­warded types are treated just as addi­tional piece of data “Oh, by the way, use this com­po­nent I just reg­is­tered for this type as well". Proxy reg­is­tra­tion is a part of the com­po­nent model build­ing, and since we end up hav­ing just one com­po­nent only infor­ma­tion 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 fea­ture. Forc­ing Wind­sor to fig­ure it out by itself could pretty quickly become very tricky and we might not always get what we expected. There are how­ever ways of get­ting 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 triv­ial fix would be sim­ply to make the DoFoo vir­tual – this way it would get picked when prox­y­ing Bar base class and we could suc­cess­fully proxy it. While this may not always be applic­a­ble (you may not be able to mod­ify the class) this is the only option that is avail­able if you’re using the released ver­sion. How­ever if you’re using trunk there are two more pos­si­ble ways of bend­ing it to our will.

Meet my attributes

Due to some changes in how Dynamic Proxy 2.2 (cur­rent trunk) han­dles addi­tional inter­faces to proxy, it is pos­si­ble to inter­cept non-virtually imple­mented inter­face mem­bers on a class proxy. Since Wind­sor by default will request just the class proxy (with no addi­tional inter­faces) we need to tell it to toss an IFoo attribute in as well. The quick­est way of doing it is throw­ing 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 solu­tion most peo­ple would choose any­way. Even if you can do it (your ser­vice does not come from a 3rd party library), you’re dec­o­rat­ing your ser­vice class with a Windsor-specific attribute which many con­sider an anti-pattern. There’s how­ever a third, more pure way.

Remem­ber that you need trunk ver­sion of Dynamic Proxy for this to work. If you use ver­sion 2.1 you’ll end up with this instead:

windsor_3

Wind­sor will imple­ment the inter­face, but it will treat it as inter­face proxy with­out tar­get. You can make it work by insert­ing a ded­i­cated inter­cep­tor that will for­ward the calls to your class, but it’s some­thing you’ll have to do man­u­ally all the way through.

Black belt approach

I said that for­warded types don’t get ran through whole reg­is­tra­tion pipeline. How­ever, ker­nel does raise its com­po­nent life­cy­cle events for them, so we can hook up to them and get noti­fied when our for­ward­ing han­dler gets reg­is­tered, and mod­ify its com­po­nent model.

We start by hook­ing up to ker­nels Han­dler­Reg­is­tered event, before we reg­is­ter any components.

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

In the OnHan­dler­Reg­is­tered method we check whether the han­dler at hand is a For­ward­ing­Han­dler and if so we add its inter­face to the list of addi­tional inter­faces we want to proxy, just like we did using attribute in the exam­ple 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 inter­face prox­ied with­out hav­ing to touch our com­po­nent’ code.

Tech­no­rati Tags:

Testing with NHibernate and SQLite

Wednesday, August 12th, 2009

warninglabel

There does not seem to be too much details on how to set up a test envi­ron­ment for NHiber­nate test­ing 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 pro­vide an up to date sam­ple for NHiber­nate 2.1.

Let’s first gather all the things we need:

Now we need to add ref­er­ences to all these projects. Make sure you add cor­rect ref­er­ence to System.Data.SQLite (either x86 ver­sion from the main direc­tory, or x64 ver­sion from x64 folder if you’re run­ning on 64bits).

You also can’t add ref­er­ence to sqlite3.dll, because it’s an unman­aged dll. I sim­ply add it as ele­ment to solu­tion and set it to copy to out­put direc­tory. After all, your solu­tion 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 cou­ple inter­est­ing points in this code:

I expose the Ses­sion­Fac­tory, not Ses­sion. That’s because I use this class for test­ing repos­i­to­ries in state­ful appli­ca­tion, that man­age the ses­sion themselves.

I save the data­base to file, instead of keep­ing it in mem­ory like Ayende does. That’s con­nected to the pre­vi­ous fact. Appar­ently, in-memory data­base only lives as long as ses­sion that cre­ated 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 sim­ple and so far, cov­ers my needs.

Tech­no­rati Tags: ,,

Solving a programming puzzle

Monday, August 10th, 2009

My fel­low devlicio.us blog­ger Tim Barcz posted an inter­est­ing prob­lem to solve. I think it's fun, so I decided to give it a try. Now, I don't know enough con­text to solve it for just about any case (and I don't think that's even pos­si­ble), so I made a few assumptions.

  • The strings we're gonna be han­dling are not too long. Oth­er­wise I'd prob­a­bly use a StringReader/Writer.
  • I'm look­ing at min­i­mal solu­tion. YAGNI — I could do some opti­miza­tions prob­a­bly, but I want to keep it sim­ple, because the sam­ple prob­lem (just a hand­ful of char­ac­ters) is simple.
  • Solu­tion is not con­text spe­cific. In other words, if you want to swap char­ac­ters dif­fer­ently based on con­text, it won't do it. Again, I'm keep­ing it simple.
  • I'm using a fac­tory here, to cre­ate the cleaner and feed it with map­ping but based on the needs and tools avail­able, I'd prob­a­bly use an IoC con­tainer to get the instance, and if needed get the map­ping from an exter­nal file, where it's more read­able, and can be eas­ily changed.

Now, here's the code:

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

The Clean­er­Fac­tory is not impor­tant. All it does is con­struct an instance of a String­Cleaner and feed it with the map­ping. How­ever, 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 String­Builder to iter­ate over all the char­ac­ters in the string, and replace these I want. I'm using Dic­tio­nary for the map­ping, because it has a read­able API, and O(1) search time.

WCF service host builder

Thursday, July 23rd, 2009

When you have a WCF ser­vice that is not a sin­gle­ton, and you want to use non-default con­struc­tor, you enter a world of pain. There's a lot of hoops that you have to go through to plug an IIn­stan­ce­Provider into the ser­vice. Even worse if you have many ser­vices. To alle­vi­ate the pain, I cre­ated 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 ser­vice types imple­ment just one con­tract (which I think you should strive for anyway).
  • All ser­vices use the same binding.

Ser­vi­ce­In­stance­Fac­to­ry­Be­hav­ior plugs a cus­tom IIn­stan­ce­Provider into the host, that uses the pro­vided del­e­gate to fab­ri­cate new instances.

As a side­note, Cas­tle WCF inte­gra­tion facil­ity can do this (in a much more flex­i­ble man­ner), but unfor­tu­nately we can't use it.

Tech­no­rati Tags:

Framework Tips XII: Advanced .NET delegates

Saturday, July 18th, 2009

All .NET del­e­gates inherit (indi­rectly) from System.Delegate class (and directly from System.MulticastDelegate) which has a sta­tic Cre­at­eDel­e­gate method. The method has two pow­er­ful char­ac­ter­is­tics that are not widely known.

All del­e­gate types are imple­mented by the run­time. What do I mean by that? Let’s have a look at how any del­e­gate type looks at the IL level:

delegateInIL

All meth­ods are run­time man­aged, mean­ing that, in a sim­i­lar fash­ion you pro­vide imple­men­ta­tion for inter­face meth­ods, run­time pro­vides imple­men­ta­tion for del­e­gate meth­ods. Take a look at the con­struc­tor. Regard­less of del­e­gate type it always has two argu­ments: object (on which a method will be invoked via the del­e­gate) and a han­dle to that method.

While try­ing (with great help of Ken­neth Xu) to find a way of pro­vid­ing prox­y­ing of explic­itly imple­mented inter­face mem­bers in Dynamic Proxy, I saw this as a pos­si­ble way of being able to imple­ment the fea­ture. The prob­lem in this case is, that proxy is an inher­ited class, that has to call a pri­vate method on the base class. So given that Dynamic Proxy works in IL, I tried to call that con­struc­tor in IL pass­ing required para­me­ters, but unsur­pris­ingly, run­time does access checks so what I got instead of work­ing del­e­gate was this:

MethodAccessException

 

 

Ken­neth sug­gested another approach – using Delegate.CreateDelegate, because as it turns out, you can suc­cess­fully use that method to bind del­e­gates to pri­vate meth­ods. That is the first impor­tant char­ac­ter­is­tic that may be a life saver in cer­tain 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 com­pile 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 draw­back though – it’s order of mag­ni­tude slower than cre­at­ing the del­e­gate via its con­struc­tor. Solu­tion brings us to the sec­ond char­ac­ter­is­tic I wanted to talk about – open instance methods.

Each instance method at IL level has an addi­tional argu­ment, implic­itly passed this pointer. Armed with this knowl­edge, let’s read what MSDN says about Delegate.CreateDelegate and open instance methods:

If firstAr­gu­ment is a null ref­er­ence and method is an instance method, the result depends on the sig­na­tures of the del­e­gate type type and of method:

  • If the sig­na­ture of type explic­itly includes the hid­den first para­me­ter of method, the del­e­gate is said to rep­re­sent an open instance method. When the del­e­gate is invoked, the first argu­ment in the argu­ment list is passed to the hid­den instance para­me­ter of method.

  • If the sig­na­tures of method and type match (that is, all para­me­ter types are com­pat­i­ble), then the del­e­gate is said to be closed over a null ref­er­ence. Invok­ing the del­e­gate is like call­ing an instance method on a null instance, which is not a par­tic­u­larly use­ful thing to do.

This basi­cally says that we can bind method to del­e­gate that passes the ‘this’ argu­ment explic­itly, so that we can reuse the del­e­gate for mul­ti­ple 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 del­e­gate cre­ation only once per life­time of the type.

I was curi­ous how all these approaches would per­form, so I cre­ated a quick poor-man’s benchmark.

I invoked an instance method 100 times using four approaches:

  1. directly
  2. via del­e­gate cre­ated using its constructor
  3. via del­e­gate cre­ated using Cre­at­eDel­e­gate pass­ing first argu­ment explic­itly (not null).
  4. via del­e­gate cre­ated once using Cre­at­eDel­e­gate and then reusing it for sub­se­quent 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 per­for­mance as when using the delegate’s con­struc­tor, which, given we can use in broader spec­trum of cases, is pretty amazing.

If you want to run the tests for your­self, the code is here.

Tech­no­rati Tags: ,,,

The biggest hack I have ever written

Wednesday, May 20th, 2009

Not that I’m proud of that, but to cir­cum­vent the lim­i­ta­tions of CLR and C# I some­times had to use reflec­tion, code gen­er­a­tion, chang­ing behav­ior depend­ing on who’s call­ing etc.

How­ever 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 asyn­cro­nous calls on WCF prox­ies cre­ated via Chan­nelFac­tory. You can see the whole code here.

Read only collections and properties with NHibernate

Tuesday, May 12th, 2009

warningsign

I’ve been work­ing with NHiber­nate for the last cou­ple of days, and as I make my way though it, I find out about things, that were not so obvi­ous to me at first, so I decided to post them here, so that some­one else can ben­e­fit as well.

First thing you learn about NHiber­nate (well ok – first thing I learned about NHiber­nate, but most of you prob­a­bly as well) is that it requires you to mark your prop­er­ties vir­tual, have para­me­ter­less con­struc­tor, and pay spe­cial atten­tion to your GetH­ash­Code() and Equals() methods.

With all that in mind (and fol­low­ing many tuto­r­ial that are out there) you may start crunch­ing 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 map­ping 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 per­sis­tence igno­rant. You usu­ally don’t want to expose a set­ter for your col­lec­tions, so that they can be swapped. Also the set acces­sor on HasPets prop­erty is noth­ing short of an ugly hack. Although we have no explicit sign of NHiber­nate in the code, it is any­thing but per­sis­tence ignorant.

You can how­ever 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 “nor­mal” class. Will it work with NHiber­nate now though? – Absolutely*. The trick is to use map­ping 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 attrib­utes to the mappings.

For HasPets I set it to read­only. That way NHiber­nate will read the prop­erty and use its value when doing INSERTs and UPDATEs, but will not include it in SELECTs.

For Pets one-to-many map­ping I used value that tells NHiber­nate to use the get­ter to read the value of the prop­erty, and to write to the field directly, and that field name is _pets (by con­ven­tion). There are quite a few more options, and you can use them to do some pretty pow­er­ful things, like enforc­ing con­sis­tency in two-way *-to-many mappings.

 

* the access=”readonly” is new to NHiber­nate v2.1

DNK Tags:

Creating tree of dependencies with MEF

Thursday, November 6th, 2008

As a fol­low up to my pre­vi­ous post, here’s the sim­pli­fied – Con­sole based ver­sion of the code.

Dis­claimer.

This is a solu­tion. Not the best one, not rec­om­mended by any­one, just the one that hap­pened to solve my prob­lem. So take it with a (big) grain of salt, and if you know a bet­ter one, use the Leave your com­ment func­tion 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 IShel­lView is not pro­vided directly by any type imple­ment­ing the inter­face. Instead it its exported by the pre­sen­ter, as a field that gets set by MEF via con­struc­tor. That way, when the Shell needs the “View” MEF sees that it needs to cre­ate a Pre­sen­ter for that, and in order to cre­ate pre­sen­ter it needs to use the Import­ing­Con­struc­tor, and pro­vide it with IMyView and IModel. Since the type imple­ment­ing the IView is IMyView it gets injected into the Pre­sen­ter. Also, since it imple­ments IShel­lView as well, it sat­is­fies the needs of Shell and gets injected into it.

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

Tech­no­rati Tags: