March 2008 - Posts

UPDATE: More posts on the subject
UPDATE: xUnit.NET RC2 New Drop includes ASP.NET MVC support and better GUI runner.  Details here.
UPDATE: Added Static Methods mention and F# - Thanks to DevHawk!


I've been a big fan of such testing frameworks as NUnit and MbUnit, but recently I've found myself getting pulled more towards xUnit.net at least to play around with for any of my code samples that I write for this blog and on my own time.  I'm not really a fan of MSTest and many I think would agree about its deficiencies.  I won't go as far as say Jay Flowers and wear the shirt though...

Another Release?

Recently, Brad Wilson and Jim Newkirk recently announced the release of xUnit.net RC2 on CodePlex.  I'd encourage you download the latest bits here.  For those wondering what changes happened between RC1 and RC2, Brad has a good writeup on his blog here.  What's interesting about this is the removal of the Assert class methods which take a user defined message should it fail.  I was never really a fan of those in the first place though. 

Another interesting added features was the IUserFixture<T> which allows you to have a startup and teardown for your fixtures in a separate class and therefore reusable, unlike the current way of using no parameter constructors as your startup and the IDisposable.Dispose for your teardown.  See the tests in the FixtureExample for details.  But here's a snipped version of that code:

    public class DatabaseFixture : IDisposable

    {

        SqlConnection connection;

        int fooUserID;

 

        public DatabaseFixture()

        {

            string connectionString = ConfigurationManager.ConnectionStrings["DatabaseFixture"].ConnectionString;

            connection = new SqlConnection(connectionString);

            connection.Open();

            string sql = @"INSERT INTO Users VALUES ('foo', 'bar'); SELECT SCOPE_IDENTITY();";

 

            using (SqlCommand cmd = new SqlCommand(sql, connection))

                fooUserID = Convert.ToInt32(cmd.ExecuteScalar());

        }

 

        public SqlConnection Connection

        {

            get { return connection; }

        }

 

        public int FooUserID

        {

            get { return fooUserID; }

        }

 

        public void Dispose()

        {

            string sql = @"DELETE FROM Users WHERE ID = @id;";

 

            using (SqlCommand cmd = new SqlCommand(sql, connection))

            {

                cmd.Parameters.AddWithValue("@id", fooUserID);

                cmd.ExecuteNonQuery();

            }

 

            connection.Close();

        }

    }


What the above code allows us to do is to define a class that holds the data from the initialization of the first test, to the cleanup after the last test.  Our state is therefore maintained in a reusable manner.  As you will note, the startup logic resides in the default no parameter constructor and all teardown logic is in the IDisposable.Dispose method.

    public class FixtureTests : IUseFixture<DatabaseFixture>

    {

        DatabaseFixture database;

 

        public void SetFixture(DatabaseFixture data)

        {

            database = data;

        }

  

        [Fact]

        public void FooUserWasInserted()

        {

            string sql = "SELECT COUNT(*) FROM Users WHERE ID = @id;";

 

            using (SqlCommand cmd = new SqlCommand(sql, database.Connection))

            {

                cmd.Parameters.AddWithValue("@id", database.FooUserID);

                int rowCount = Convert.ToInt32(cmd.ExecuteScalar());

                Assert.Equal(1, rowCount);

            }

        }

    }


Then we can go ahead with our tests, while using the SqlConnection as defined on our DatabaseFixture.  After we're done with our test, it goes ahead and calls Dispose on the fixture.  I tend to like this approach and it's definitely growing on me.

Why xUnit.net?

For those new to xUnit.net, there are some decent links to help you along.  Some of the more interesting ones can be found here:
But, why am I interested in it?  Well, let's just say that I think it tackles things in a slightly different manner.  I think one of the key pieces that I really like is the Assert.Throws instead of the clumsy ExpectedExceptionAttribute which you must clutter your tests with on the top.  I would rather assert that such a thing happened programmatically, so that I may analyze the exception.  I can also specify which line I expect during my test will throw the exception, instead of taking on blind faith that my test threw an exception.  It may be of the right type, but that may not have been the one you wanted, thus giving a false sense of security.

To use this, just simply use the Assert.Throws<TException>(Assert.ThrowsDelegate) which I've found to be very helpful.  Let's look at a quick test of that being used.

    [Fact]

    public void PopEmptyStack()

    {

        Stack<string> stack = new Stack<string>();

        Assert.Throws<InvalidOperationException>(() => stack.Pop());

    }


As you can see, we're pretty explicit about what line will throw the exception, and that's really the key to this scenario.  There are a good number of samples provided on the releases page that you should check out.  As always with most products that I talk about, I highly recommend reading the tests to really fully understand what's going on underneath the covers.  Not only does it help you understand the intent of the program, but you can learn about good coding techniques, design patterns, testing patterns and so on.

Another point that xUnit.net separates itself from the pack is the ability to decorate static methods as facts.  This frees you from having to create an instance of your test class in order to call them.  Harry Pierson, aka DevHawk, demonstrates its use with regards to F# and testing the parse buffer here.  It definitely opened my eyes and a few more avenues as I pursue more F# related work items in the future.  Here's just a quick and dirty sample of showing how you can use xUnit.net with F# quite easily, just as Harry's post did.

#light

#R @"E:\Tools\xunit-build-1223-samples\Samples\xunit\xunit.dll"

open System
open System.Collections.Generic
open Xunit

type Stack<'t> = class
  val elements : LinkedList<'t>
 
  new() = { elements = new LinkedList<'t>() }
 
  member x.IsEmpty
    with get() = x.elements.Count = 0
   
  member x.Push element =
    x.elements.AddFirst(element:'t)
   
  member x.Top
    with get() =
      if x.elements.Count = 0 then
        raise (InvalidOperationException("cannot top an empty stack"))
      x.elements.First.Value
     
  member x.Pop =
    let top = x.Top
    x.elements.RemoveFirst()
    top
end

[<Fact>]  
let NoElementsShouldBeEmpty () =
  let stack = new Stack<string>()
  Assert.True(stack.IsEmpty)


If you notice, the FactAttribute is placed on a static method called NoElementsShouldBeEmpty and sure enough it works like a champ through xUnit.net.  I like this approach instead of the pomp and circumstance required for creating classes as shown above with my Stack class.  Note the use of the empty parans which forces it to be a void method with no values passed either.  But if you run it through the xunit.console sure enough it succeeds like a champ.

What are we missing though?  Well, I'm in favor of having a standalone GUI Test Runner much like NUnit and MbUnit have.  In fact, Brad has started this and you can get these features from the latest commits here.  Mind you I haven't gotten it to work just right yet, but it's a work in progress.

Conclusion

There is a lot to like about xUnit.net and takes a lot of lessons learned from the use of NUnit, MbUnit and others and I think they're doing a good job incorporating issues.  This project isn't as active as MbUnit and NUnit, but it's definitely one to keep an eye on.  Recent releases of NUnit and Gallio Automation Platform will probably be also covered in the short while as well as they have a lot to offer.  Until next time...

kick it on DotNetKicks.com
In my previous posts I have talked a bit about Inversion of Control (IoC) containers with respect to Interception and Aspect Oriented Programming (AOP).  It's not only important to understand the uses and strategies for implementing your solutions using it, but also how interception and AOP works deep down in .NET.  Instead of a long, drawn out post, I think I'll just include some articles and posts that do a very good job of explaining some of the ideas behind it.

Articles and Posts

I think it'd be good if we just start out with some basic MSDN articles and such regarding AOP and interception.  Some of them may be older but the concepts will still apply to this day:

Just Read the Code

There are many AOP frameworks out there in the wild right now for .NET.  To understand them pretty well, it's best if you just crack open the code and follow the unit tests.  Most of these are no longer active.  Let's cover some of the AOP frameworks out there:
Many containers also implement AOP through the IoC container such as:
Conclusion

For those willing and able to go ahead and learn about AOP, it's actually quite interesting.  it's also quite a challenge especially when dealing with IL emitting.  Go ahead and look at the source code and samples and give some of it a try.  Next time we pick up, I'll be talking about AOP in the Enterprise and Spring.NET.  Until next time...

kick it on DotNetKicks.com
In my previous post about Unity and IoC containers, I made note of some changes in the latest drop of the Unity Application Block.  As Grigori Melnik, the PM of the Unity and Enterprise Library team noted, Unity should be released in its final form on April 7th, so stay tuned.  In the mean time, the latest drop of Unity was on March 24th, so go ahead and it pick it up.

Configuration Changes

As I noted from above, the public APIs really haven't changed all that much.  Instead, most of the efforts recently have been around performance improvements in the ObjectBuilder base and the configuration of the container itself.  I must admit that previous efforts left me a little cold with having to decorate my classes with the DependencyAttribute.  Well, you shouldn't have to do that anymore, now that the TypeInjectionElement has been added so that you can map your constructor arguments and so on.  Let's walk through a simple example of doing so.

First, let's go through my basic anti-corruption container that I use for Unity and any other container that I use for registration and so on.

namespace UnitySamples

{

    public static class IoC

    {

        private static IDependencyResolver resolver;

 

        public static void Initialize(IDependencyResolver resolver)

        {

            IoC.resolver = resolver;

        }

 

        public static T Resolve<T>()

        {

            return resolver.Resolve<T>();

        }

 

        public static T Resolve<T>(string name)

        {

            return resolver.Resolve<T>(name);

        }

    }

}


Remember this is just a quick spike sample of my anti-corruption container which was taken from Ayende.  And then in order to configure my UnityContainer through the implementation of my IDependencyResolver interface.  Let's take a brief look at that:

namespace UnitySamples

{

    public interface IDependencyResolver

    {

        T Resolve<T>(string name);

 

        T Resolve<T>();

    }

}


And then the implementation of the interface for Unity would look like:

using System.Configuration;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

 

namespace UnitySamples

{

    public class UnityDependencyResolver: IDependencyResolver

    {

        private IUnityContainer container;

 

        public UnityDependencyResolver()

        {

            container = new UnityContainer();

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers.Default.Configure(container);

        }

 

        public T Resolve<T>()

        {

            return container.Resolve<T>();

        }

 

        public T Resolve<T>(string name)

        {

            return container.Resolve<T>(name);

        }

    }

}


Now, if you look at the constructor for the UnityDependencyResolver above, I am using the default container in order to configure my container.  But, I have the option of specifying a name for it as well or even just an index.  I could just easily change that code to this and it would work if I name my container default.  This is a little bit of a change from before when I had to use the GetConfigCommand() method in order to configure the container which was a bit too chatty for my tastes.

            container = new UnityContainer();

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers["default"].Configure(container);


So, the idea that I want to do is create an object graph so that I have classes with dependencies that have dependencies.  Without doing AOP and some basic interception, we could take the approach of keeping around something like an IContext which would have our cross-cutting concerns in one location such as logging and whatnot in one area so your objects don't sit there with 16 constructor parameters, and instead has a context from which it can pull.  This approach has worked for me in the past, so let's just go through that one right now.

First, let's look at the context that has those cross-cutting concerns and the actual implementation:

namespace UnitySamples

{

    public interface IContext

    {

        ILogger Logger { get; }

    }

}


And then the concrete implementation might look something like this:

namespace UnitySamples

{

    public class UnityContext : IContext

    {

        private readonly ILogger logger;

 

        public UnityContext(ILogger logger)

        {

            this.logger = logger;

        }

 

        public ILogger Logger

        {

            get { return logger; }

        }

    }

}


So, what I do here is inject my logger into my context, and probably anything else that might be cross-cutting as well.  So, now in one of my classes, then I can accept the IContext in to do what I need it to do.  That would look something like this.

namespace UnitySamples

{

    public class Customer

    {

        public string CustomerId { get; set; }

 

        public string FirstName { get; set; }

 

        public string MiddleName { get; set; }

 

        public string LastName { get; set; }

    }

 

    public class CustomerTasks

    {

        private readonly IContext context;

 

        public CustomerTasks(IContext context)

        {

            this.context = context;

        }

 

        public void SaveCustomer(Customer customer)

        {

            // Save customer

            context.Logger.LogEvent("Saving customer", LogLevel.Information);

        }

    }

}


I'm not doing anything special, instead, just showing how this pattern might apply.  And then just tying it all together is my console application (sometimes my favorite UI for quick spikes).

namespace UnitySamples

{

    class Program

    {

        static void Main(string[] args)

        {

            IoC.Initialize(new UnityDependencyResolver());

            CustomerTasks tasks = IoC.Resolve<CustomerTasks>();

            tasks.SaveCustomer(new Customer{ CustomerId = "12345", FirstName = "Joe", LastName = "Smith", MiddleName = "Frank"});

        }

    }

}


But the more interesting part about this is the XML configuration.  I know many people such as Ayende have declared war on XML configuration, but I think for this quick example it does quite well.  If we start talking about complex object graphs, then I'd certainly agree and I'd rather do it programmatically.  But, let's first look at how I'd wire up the whole thing in the app.config file.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <configSections>

        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

    </configSections>

 

    <unity>

        <typeAliases>

            <typeAlias alias="string" type="System.String, mscorlib" />

            <typeAlias alias="ILogger" type="UnitySamples.ILogger, UnitySamples" />

            <typeAlias alias="ConsoleLogger" type="UnitySamples.ConsoleLogger, UnitySamples" />

            <typeAlias alias="DebugLogger" type="UnitySamples.DebugLogger, UnitySamples" />

            <typeAlias alias="IContext" type="UnitySamples.IContext, UnitySamples" />

            <typeAlias alias="UnityContext" type="UnitySamples.UnityContext, UnitySamples" />

            <typeAlias alias="CustomerTasks" type="UnitySamples.CustomerTasks, UnitySamples" />

        </typeAliases>

        <containers>

            <container>

                <types>

                    <type type="ILogger" mapTo="ConsoleLogger" name="defaultLogger"/>

                    <type type="ILogger" mapTo="DebugLogger" name="debugLogger"/>

                    <type type="IContext" mapTo="UnityContext">

                        <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">

                            <constructor>

                                <param name="logger" parameterType="ILogger">

                                    <dependency name="debugLogger"/>

                                </param>

                            </constructor>

                        </typeConfig>

                    </type>

                    <type type="CustomerTasks">

                        <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">

                            <constructor>

                                <param name="context" parameterType="IContext">

                                    <dependency/>

                                </param>

                            </constructor>

                        </typeConfig>

                    </type>

                </types>

            </container>

        </containers>

    </unity>

</configuration>


As you may notice from above, Unity gives us the ability to give type aliases so that we can reference the short names instead of the long ugly fully qualified type names by using the <typeAliases><typeAlias> nodes in the configuration.  Much as before, we still register our types with a name, type and so on. 

But, what's interesting is that we now have the ability to do type injection through a Unity extension called the TypeInjectionElement.  This allows us to inject into the constructor and put in our parameters as need be.  But we could also replace that with <method> or <property> in order to do method injection and property setter injection respectively. 
Within the <param> element, we can specify our given injection element parameters.  This allows us to specify the name of our given parameter, the type, but also for the dependency check, we can specify the name and type to alias the other <type> elements that we wish to get a reference of.  We can also specify the values if we so desire of strings, integers and so on.  Below is a simple example of using both dependency references and values.

<constructor>

    <param name="logger" parameterType="ILogger">

        <dependency name="debugLogger"/>

    </param>

    <param name="dbName" parameterType="string">

        <value value="AdventureWorks" />

    </param>

</constructor>


I find the best way to learn about these features usually isn't through documentation, although it's a nice thing to do, but instead the tests.  I look for the functionality that I'm interested in and go deep.  A project this size without good unit tests == FAIL in my opinion.  Anyhow, this is better looking than it used to be and much more intuitive.

Interception Revisited

As Chris Tavares, the developer of Unity noted on my blog before was the fact that he could easily put in the interceptors from the ObjectBuilder2 since ObjectBuilder2 is modular and Unity is built upon it.  It shouldn't have been news, because I've been working on that myself to get lightweight interception to work on it.  Maybe when I get it fully implemented I'll share it.  But in the mean time, it's just a spike.

Conclusion

I think this approach has helped in the XML configuration goo that had been a bit confusing.  I didn't want to clutter my domain models and processing code with excess attributes stating intent, and would rather keep it clean.  This makes a step in that direction.  In the next installation of looking at IoC will revolve around Spring.NET and AOP in the Enterprise, so stay tuned...  Until next time...

kick it on DotNetKicks.com
As I've discussed before with my dive into functional programming and F#, there is a user group of language geeks that specialize in Haskell, Lisp, Scheme, OCaml, Erlang and so on, within the Washington DC area called FringeDCBrent Yorgey, well known in the Haskell community and contributor to XMonad, presented an introduction to Haskell and explained a bit about extending XMonad.  Fortunately for those who couldn't attend like myself due to scheduling conflicts, Conrad Barski recorded this session and posted it to Google Video.  The slides have also been made available as well here.  For those not aware of XMonad, it's a tiling window manager for X that is extensible in Haskell.  Unfortunately, the opening talk by Philip Fominykh on The Zipper, a purely functional data structure in Haskell for manipulating the location of structure instead of the data, was not recorded. 

If you want to get your language geek on, come check it out for their next informal meeting on May 10th over a beer or two.  More details on the site here.  Until next time...

kick it on DotNetKicks.com
I realize it's been a while since my last post on Inversion of Control containers and looking at Unity as one of them.  Since that time, Scott Hanselman linked to some of the comparisons that I did for IoC containers here.  I'll be the first to admit that the look was a bit naive, but to get you all interested in looking at IoC container and how they can improve your applications.  It was suggested here that my posts weren't a complete comparison, although in my previous posts I covered a lot of those topics.  Even so, after talking with said individual, I need to cover more ground on the basics and dive deeper into the details.

Where We Are

Before we begin today, let's see what we've already covered in the past:
So, we have a bit of back history, but I think I dived too far into things without giving some of the back story.

DI Frameworks Galore

As Scott Hanselman noted, there are a number of IoC containers in the .NET Space.  Most of these I was already aware of and played with, so I'm only going to list the ones I've played with.  Here they are in no particular order:
So, as you can see, there are plenty to choose from.  They all serve basic IoC needs and I'll talk about that a little bit more later.

Getting Back to Basics

When we talk about Inversion of Control and dependency inversion principle, we're talking about loosely coupled applications.  It follows the Hollywood Principle which is the trite "Don't call use, we'll call you" mantra.  In a way it means that those dependencies that you have inside your class, say your Logger and its associated formatter.  In the tightly coupled world, you would have a private member of a Logger.  Instead, what you would have in the other case is an interface or abstract class that would represent the functionality of that logger, and that instance given to your class.  Throw on top of that a container to manage those dependencies to those interfaces and mappings to concrete classes.  Also, your container can manage the object lifetimes as well.   Ayende shows how easy it is to create a simple container, although it misses an important point about lifetime management.

To put it succinctly, to be a container should satisfy the following requirements:
  • Configuration - Registering types and mappings through code, XML or script
  • Lifetime Management - How the lifetime of the objects are managed, singleton, transient, etc
  • Resolution - Resolve dependencies and instantiate
  • Extensibility - Be able to add new facilities for additional features (interception, AOP, and so on)
Before we get into any advanced topics, let's get into more detail.  James Kovacs wrote in the March 2008 edition of MSDN Magazine called "Loosen Up - Tame Your Software Dependencies For More Flexible Apps".   This article is a great start for those trying to understand dependency inversion and dependency injection.  James walks through a simple application with tight coupling, and then works to loosen it.  Once that is complete, Castle Windsor is introduced and walks through the XML configuration or using Binsor to auto-wire the container.

One of the more key points in this article and it came from Ayende is to have an anti-corruption layer for your IoC container.  Yes, that's the same Domain Driven Design term in which we isolate things that don't conform to our given architecture and can translate from one context to another.  Let's throw up a simple example of using this.  Remember it's just a quick spike of an anti-corruption layer.

namespace UnitySamples

{

    public static class IoC

    {

        private static IDependencyResolver resolver;

 

        public static void Initialize(IDependencyResolver resolver)

        {

            IoC.resolver = resolver;

        }

 

        public static T Resolve<T>()

        {

            return resolver.Resolve<T>();

        }

 

        public static T Resolve<T>(string name)

        {

            return resolver.Resolve<T>(name);

        }

    }

}


So, what we have is an IDependencyResolver given to the singleton IoC container.  Like I said, this isn't best practice as I haven't done any checking on whether the resolver was initialized or not.  But, what we want is to expose the way of resolving dependencies.  Now let's take a look at the IDependencyResolver interface and how that's used.

namespace UnitySamples

{

    public interface IDependencyResolver

    {

        T Resolve<T>(string name);

 

        T Resolve<T>();

    }

}


Not much to this but gives us the ability to resolve our dependencies by type, or by type and name.  Pretty simple code here once again.  But, if I wanted to suddenly use Unity as the backing store, I'd simply implement it as the following:

using System.Configuration;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

 

namespace UnitySamples

{

    public class UnityDependencyResolver: IDependencyResolver

    {

        private IUnityContainer container;

 

        public UnityDependencyResolver()

        {

            container = new UnityContainer();

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers.Default.GetConfigCommand().Configure(container);

        }

 

        public T Resolve<T>()

        {

            return container.Resolve<T>();

        }

 

        public T Resolve<T>(string name)

        {

            return container.Resolve<T>(name);

        }

    }

}


So, all I'd have to do to switch from one container to another is just swap out the IDependencyResolver and I'm finished.  But, unfortunately, there are some techniques that are partial to one container or another, so there may be some things I'd lose there.  But for most cases, this pattern works and works well at that.

Of course loose coupling, dependency injection and using IoC containers are nice in terms of making unit tests easier, but as you can see, there's a bit more to it than that, including the lifetime management, interception, the flexibility of changing implementations and so on.

Interception and Aspect Oriented Programming

Aspect Oriented Programming (AOP) and basic interception are interesting pieces of some containers.  This technique allows us to handle cross-cutting concerns such as logging, transaction management, security and so on at a different level instead of littering our code and domain model with checks everywhere.  Instead, we centralize those concerns and have them intercept calls and do their work.  Let's get some jargon straight here before we go any further.  An aspect is the part that encapsulates the cross-cutting concern such as logging.  These aspects can give advice, which is to alter the behavior of a given program.  The advice is given at certain join points which is where the aspect advice and the program intersect.  A group of these join points are called a pointcut.

Interception is a feature of some of the IoC containers out there.  A few come to mind such as Castle Windsor, Spring.NET, LinFu, S2Container, Puzzle.NET and even ObjectBuilder2.  These containers provide at least a basic level of interception, meaning that you can intercept calls to methods, analyze the contents of the method call, proceed with the call and even modify the return value.  Since most containers support simple interception, I haven't found it more useful than logging or enforcing security on various things.  However, it can be extended to support more robust Policy Injection style of programming such as you would find in the Policy Injection Application Block.

Interception in Unity?

Quite a bit has changed with Unity since I last blogged about it in terms of the configuration.  You can grab the latest bits here.  It would be nice to have changesets and such checked i