The Inquisitive Coder - Davy Brion’s Blog

Trying to walk that thin line between intelligence and ignorance

Archive for April, 2008

Introduction to IoC with Windsor

Posted by Davy Brion on 29th April 2008

As you may or may not know, i’m a bit of a fan of dependency injection. If you’re only using it on a small scale, you don’t really need any tools to use the technique. But once you’re used to this design technique, you’ll quickly start using it in many places of your code. If you do, it quickly becomes cumbersome to deal with the real instances of your runtime dependencies manually. This is where tools like Inversion Of Control (IoC) containers come in to play. There are a few solid containers available for the .NET world, and even Microsoft has released their own container. Basically, what the IoC container does for you, is take care of providing dependencies to components in a flexible and customizable way. It allows clients to remain completely oblivious to the dependencies of components they use. This makes it easy to change components without having to modify client code. Not to mention the fact that your components are a lot easier to test, since you can simply inject fake dependencies during your tests.

How about some code to demonstrate? Suppose we have a class called OrderRepository which exposes methods such as GetById, GetAll, FindOne, FindMany and Store. Obviously, the OrderRepository has a dependency on a class that can actually communicate with some kind of physical datastore, either a database or an xml file or whatever. Either way, it needs another object to access the Order data. Suppose we have an OrderAccessor class which implements an IOrderAccessor interface. The interface declares all the methods we need to retrieve or store our Orders. So our OrderRepository would need to communicate with an object that implements the IOrderAccessor interface. Instead of letting the OrderRepository instantiate that object itself, it will receive it as a parameter in it’s constructor:

        private readonly IOrderDataAccessor _accessor;

 

        public OrderRepository(IOrderDataAccessor accessor)

        {

            _accessor = accessor;

        }

This makes it easy to test the OrderRepository class, and it’s also easy to make it use different implementations of IOrderDataAccessor later on, should we need to. Now obviously, you really don’t want to do this when you need to instantiate the OrderRepository in your production code:

OrderRepository repo = new OrderRepository(new OrderDataAccessor());

As a consumer of the OrderRepository, you shouldn’t need to know what its dependencies are and you most certainly shouldn’t need to pass the right dependencies into the constructor. Instead, you just want a valid instance of OrderRepository. You really don’t care how it was constructed, which dependencies it has and how they’re provided. You just need to be able to use it. That’s all. This is where the IoC container comes in to help you. Suppose we wrap the IoC container in a Container class that has a few static methods to help you with instantiating instances of types. We could then do this:

OrderRepository repository = Container.Resolve<OrderRepository>();

That would leave you with a valid OrderRepository instance… one that has a usable IOrderDataAccessor but you don’t even know about it, nor do you care how it got there. In other words, you can use the OrderRepository without knowing anything about its underlying implementation.

Let’s take a look at the implementation of the Container class:

    public static class Container

    {

        private static readonly IWindsorContainer _container;

 

        static Container()

        {

            _container = new WindsorContainer();

            _container.AddComponent<IOrderDataAccessor, OrderDataAccessor>();

            _container.AddComponent<OrderRepository>();

        }

 

        public static T Resolve<T>()

        {

            return _container.Resolve<T>();

        }

    }

It just uses a static instance of Windor’s Container and it registers the types we need… let’s examine the following line:

_container.AddComponent<IOrderDataAccessor, OrderDataAccessor>();

this basically sets up the container to return a new instance of OrderDataAccessor whenever an instance of IOrderDataAcessor is requested.

We still have to make sure the Windsor container knows about the OrderRepository class by adding it as a known component like this:

            _container.AddComponent<OrderRepository>();

By doing this, the Windsor container will inspect the type (in this case, OrderRepository) and it will see that its constructor requires an IOrderDataAccessor instance. We ‘registered’ the IOrderDataAccessor type with the container to return an instance of the OrderDataAccessor type. So basically, whenever someone asks the container to return an instance of an OrderRepository class, the container knows to instantiate an OrderDataAccessor instance to pass along as the required IOrderDataAccessor object to the OrderRepository constructor.

At this point, you may be wondering: “Why go through all this trouble to register the concrete implementation of IOrderDataAccessor to be used in code? We could just as well instantiate the type ourselves!”. That’s certainly true. The code would be slightly uglier, but you’d get the same behavior. Of course, the Windsor container supports XML configuration (either in the app.config or web.config or in a custom configuration file) as well as explicit configuration through code. So you can configure the container through code explicitly, but if there is a config file present, the container will use that configuration instead of the one provided through code. So you could define the defaults in code, and should you need to change it later on, you can just provide a config file.

You know what bothers me about our current implementation? We’re still communicating with an OrderRepository instance. If we wanna be really flexible, it would be better if we were communicating with an object that implemented an IOrderRepository interface. So let’s just define the following interface:

    public interface IOrderRepository

    {

        Order GetById(Guid id);

        IEnumerable<Order> GetAll();

        Order FindOne(Criteria criteria);

        IEnumerable<Order> FindMany(Criteria criteria);

        void Store(Order order);

    }

After all, that’s all we care about as consumers of a IOrderRepository type. We shouldn’t really care about the concrete implementation. We just need an interface to program to. So let’s change the OrderRepository definition to this:

    public class OrderRepository : IOrderRepository

And then when we configure our IoC container we do it like this:

        static Container()

        {

            _container = new WindsorContainer();

            _container.AddComponent<IOrderDataAccessor, OrderDataAccessor>();

            _container.AddComponent<IOrderRepository, OrderRepository>();

        }

Now we can no longer ask the contianer for an OrderRepository interface. But we can ask for an instance that implements the IOrderRepository interface like this:

IOrderRepository repository = Container.Resolve<IOrderRepository>();

So now our client is completely decoupled from the implementation of IOrderRepository, as well as the dependencies it may or may not have.

Ok, lets suppose that this implementation makes it to the production environment. Everything’s working but for some reason, someone makes a decision to retrieve the orders from a specially prepared XML file instead of the database. Unfortunately, your OrderDataAccessor class communicates with a SQL server database. Luckily, the OrderRepository implementation doesn’t know which specific implementation of IOrderDataAccessor it’s using. We just need to make sure that every time someone needs an IOrderRepository instance, it uses the new xml-based IOrderDataAccessor implementation instead of the one we originally intended.

Because we’re using Dependency Injection and an IoC container, this only requires changing one line of code:

            _container.AddComponent<IOrderDataAccessor, XmlOrderDataAccessor>();

Actually, if we’d put the mapping between the IOrderDataAccessor type and the XmlOrderDataAccessor implementation in an xml file, we wouldn’t even have to change any code! Well, except for the XmlOrderDataAccessor implementation obviously.

We can even take this one step further… After the change to the xml-based OrderDataAccessor went successfully, they (the ‘business’) all of a sudden want to log who retrieves or saves each order for auditing purposes.

Hmmm, alright then… We create an implementation of IOrderRepository which keeps extensive auditing logs so they can be retrieved later on. We could just inherit from the default OrderRepository implementation and add auditing logic before each method is executed. Then we’d only have to configure our IoC container to return a different instance of the IOrderRepository type whenever someone requests it:

        static Container()

        {

            _container = new WindsorContainer();

            _container.AddComponent<IOrderDataAccessor, XmlOrderDataAccessor>();

            _container.AddComponent<IOrderRepository, OrderRepositoryWithAuditing>();

        }

Again, our client code does not need to be modified in any way, yet we did modify the runtime behavior of the application. Instead of retrieving the Orders from a SQL database, it’s now retrieving them from an XML file, and the repository is performing auditing as well, without having to change any client code.

And if we were using the xml-configuration features of Windsor, we could get all of this working without even having to recompile the client-assemblies.

This was just an introduction to using an IoC contianer (Castle’s Windsor specifically) and we briefly touched on benefits that you can achieve with this way of working. The Windsor container can do much more, but you’ll either have to figure that stuff out yourself, or wait for future posts about its other features/possibilities :)

Share/Save/Bookmark

Tags: ,
Posted in Castle Windsor, Dependency Injection, Inversion Of Control, Software Development, Test Driven Development | 4 Comments »

Stream.CopyTo method

Posted by Davy Brion on 29th April 2008

No, Stream does not have a useful CopyTo method :(
unless…. :

    public static class Extensions

    {

        public static void CopyTo(this Stream source, Stream target)

        {

            if (!source.CanRead) throw new ArgumentException(“source can not be read”, “source”);

            if (!target.CanWrite) throw new ArgumentException(“target can not be written to”, “target”);

 

            source.Position = 0;

 

            while (source.Position < source.Length)

            {

                var buffer = new byte[4096];

                int bytesRead = source.Read(buffer, 0, buffer.Length);

                target.Write(buffer, 0, bytesRead);

            }

        }

    }

now you can do:

stream.CopyTo(fileStream);

If there is a way to copy the contents of one stream to another in the .NET framework, please let me know ;)

Share/Save/Bookmark

Posted in Software Development | No Comments »

XDocument’s WriteTo method gotcha

Posted by Davy Brion on 25th April 2008

Suppose you have an xml document in memory using an XDocument instance. Then you need to write the contents of the xml document to an XmlWriter… no worries, the XDocument class provides the WriteTo method which takes an XmlWriter as a parameter. The contents of the xml document are then nicely written to the XmlWriter.

Unless… you’re using an XmlWriter which was created with an XmlWriterSettings instance with OutputMethod set to XmlOutputMethod.Text and your xml document is larger than 6144 bytes! The writer will only write the first 6144 bytes and after that, it just stops. No exception, no nothing. The method returns as if everything was OK. But the underlying stream your XmlWriter wrote to contains faulty data. A very nice way to spend a friday afternoon ;)

In case you’re wondering why: The XmlWriter’s static Create method creates an instance of XmlUtf8RawTextWriter when OutputMethod is set to XmlOutputMethod.Text. This specific Writer has an internal buffer which is initialized in its constructor to be 6144 bytes long. Apparantly, it doesn’t think it’s worth throwing an exception if you try to write too much data…

Share/Save/Bookmark

Posted in .NET bugs | 1 Comment »

The perfect workplace

Posted by Davy Brion on 24th April 2008

The perfect workplace for me is a place where:

  • People have the required skills and motivation to perform their jobs competently
  • People are honest about mistakes they make… after all, we all make them so we might as well all be honest about them
  • People who play the political game are fired, or if possible, not hired
  • People aren’t offended when told that something they did was not good or could be better
  • People who are sick just stay home instead of infecting others
  • It is accepted that developers spend a little of their worktime to read blogs, mailinglists, etc… to learn
  • People are judged on what they do, not how busy they look
  • People who work together on something are located in the same room
  • People have enough common sense to go to a meeting room or a more secluded area to discuss something that is specific to their project, so they won’t bother everyone else in the room. If that’s not possible, a little bit of voice control would be nice
  • People don’t engage in Buzzword Driven Development ( = claiming to do certain practices or activities while in reality hardly doing them or doing a half-assed job of them)
  • Managers trust the developers
  • Managers don’t make promises they know they can’t keep
  • Managers prefer a long-term vision instead of going for the quick short-term win while completely ignoring the negative consequences that will pop up after they have been reassigned
  • They have proper airconditioning
  • You have access to cheap (or free) drinks and snacks of a wide variety

Unfortunately I was sentenced to Enterprise Hell about 5.5 years ago so I’m not used to most of the stuff mentioned in the list… luckily i’m up for parole in about 2 months!

Share/Save/Bookmark

Posted in Off Topic, Rants | 4 Comments »

Kent Beck’s Implementation Patterns

Posted by Davy Brion on 21st April 2008

A new book from Kent Beck about writing code? I just couldn’t resist ordering it. Implementation Patterns is a (very short) book with the goal of helping you communicate your intentions as a developer through your code. The patterns in this book are all very short, and usually are nothing more than simple descriptions of different implementation choices that you as a developer can make.

Don’t think that these patterns are similar to design patterns or anything like that… these patterns are about how and when you should create classes, how to deal with state in classes and methods, how to implement behaviour, dealing with exceptional flow and exceptions, different ways of defining and implementing methods, choosing between collection types, and there’s even a chapter that deals with some of the complications of developing frameworks and allowing the framework to evolve while minimizing or avoiding breaking code for clients of the framework.

This book is just filled with a lot of great insight on how to write code that clearly expresses the intent of what it’s supposed to do. And while it is a very short book (only 130 pages), it’s one of those books that’ll teach you something new every time you read it. Must read!

Share/Save/Bookmark

Posted in Books | No Comments »

Testing Exceptions

Posted by Davy Brion on 20th April 2008

Just read a post from a former co-worker about how to test exceptions. He uses the ExpectedException attribute (of MS Test) which has at least the following issues (IMO):

  • There is some confusion about the message parameter in the attribute. In NUnit, the message you provide is the expected exception message that you want to test. With MS Test, it is the message that should be displayed when the exception is not thrown. This effectively removes the possibility to use the attribute to test the message of the exception when using MS Test. And yes, it can definitely be useful to test the content of the message.
  • It is not immediately clear which line of code is supposed to throw the exception. In the example he provides, when you only have 2 lines of code (one of which is instantiating the object) it’s not hard to figure out where the exception is thrown. But when you have larger test methods, it’s often confusing to see where the exception should be thrown. And yes, we all like to avoid large test methods, but sometimes it’s hard to avoid. And with large, i mean 10+ lines.
  • You can’t test for the general Exception type. Whether it is a good idea or not to throw a general Exception is not really relevant to this discussion. But i do want to be able to test for it when the situation calls for it
  • If you have a custom exception with contains some properties that you want to test, using the ExpectedException attribute is insufficiant… yes, you can test that the exception is thrown, but if the exception has extra properties, the contents of those properties should be validated as well

Let’s use his Order example, but with some more logic, to show some better ways to test exceptions. Suppose we have the following code:

    public class Order

    {

        public IEnumerable<OrderLine> OrderLines { get; set; }

        public Customer Customer { get; set; }

 

        public Order() : this(null, null) {}

 

        public Order(Customer customer) : this(customer, null) {}

 

        public Order(Customer customer, IEnumerable<OrderLine> orderLines)

        {

            Customer = customer;

            OrderLines = orderLines;

        }

 

        public decimal CalculateTotal()

        {

            return OrderLines.Sum(o => o.Price) * Customer.DiscountRate;

        }

    }

For maximum flexibility, we’ve provided 3 ways to create an Order object: without any of its dependencies, with one dependency (Customer) and with both dependencies (Customer and OrderLines). Depending on which constructor you’ve used, you might need to provide one or two dependencies through their setters before you can call the CalculateTotal method. With the code as it is right now, we’ll get a NullReferenceException if one of the dependencies hasn’t been provided. So we’ll modify the CalculateTotal method to guard against this. I don’t like creating Exception-derived types for everything that could possibly go wrong, so i’ll define an enum with the validation problems that the Order class could have:

    public enum OrderValidationProblem

    {

        OrderLinesNotSet,

        OrderLinesHasNoItems,

        CustomerNotSet

    }

Now we introduce an OrderValidationException type which will contain the type of validation problem:

    public class OrderValidationException : Exception

    {

        public OrderValidationProblem Problem { get; set; }

 

        public OrderValidationException(OrderValidationProblem problem)

        {

            Problem = problem;

        }

    }

Since we try to be responsible programmers, we immediately write the tests so we can’t ever forget to properly guard against these conditions:

    [TestFixture]

    public class OrderValidationTests

    {

        [Test]

        [ExpectedException(typeof(OrderValidationException))]

        public void CustomerNotSetThrowsValidationException()

        {

            var order = new Order();

            order.OrderLines = EntityTestFactory.CreateDummyOrderLines();

            order.CalculateTotal();

        }

 

        [Test]

        [ExpectedException(typeof(OrderValidationException))]

        public void OrderLinesNotSetThrowsValidationException()

        {

            var order = new Order(new Customer());

            order.CalculateTotal();

        }

 

        [Test]

        [ExpectedException(typeof(OrderValidationException))]

        public void OrderLinesWithNoItemsThrowsValidationException()

        {

            var order = new Order(new Customer(), new OrderLine[] {});

            order.CalculateTotal();

        }

    }

Now it’s time to make the tests pass… so we modify the CalculateTotal method to provide the necessary guard clauses:

        public decimal CalculateTotal()

        {

            if (OrderLines == null) throw new OrderValidationException(OrderValidationProblem.OrderLinesNotSet);

            if (OrderLines.Count() == 0) throw new OrderValidationException(OrderValidationProblem.OrderLinesHasNoItems);

            if (Customer == null) throw new OrderValidationException(OrderValidationProblem.CustomerNotSet);

 

            return OrderLines.Sum(o => o.Price) * Customer.DiscountRate;

        }

At this point, the tests pass… but what do they prove? Sure, we throw the right exception when we need to. But we still don’t know if the exception has been constructed properly. If we want to test that, we have to stop using the ExpectedException attribute. But i don’t wan’t to litter my tests with try/catch constructs either. We could create a helper method to perform the necessary check:

        private void CheckExceptionAndProblem(Func<Decimal> function,

            OrderValidationProblem expectedOrderValidationProblem)

        {

            try

            {

                function();

            }

            catch (OrderValidationException e)

            {

                Assert.AreEqual(expectedOrderValidationProblem, e.Problem);

                return;

            }

            Assert.Fail(“Exception was not thrown”);

        }

The generic Func type allows us to easily pass a delegate to the CalculateTotal method instead of having to declare a specific delegate for it first.

Then we’d modify our tests like this:

        [Test]

        public void CustomerNotSetThrowsValidationException()

        {

            var order = new Order();

            order.OrderLines = EntityTestFactory.CreateDummyOrderLines();

            CheckExceptionAndProblem(order.CalculateTotal, OrderValidationProblem.CustomerNotSet);

        }

 

        [Test]

        public void OrderLinesNotSetThrowsValidationException()

        {

            var order = new Order(new Customer());

            CheckExceptionAndProblem(order.CalculateTotal, OrderValidationProblem.OrderLinesNotSet);

        }

 

        [Test]

        public void OrderLinesWithNoItemsThrowsValidationException()

        {

            var order = new Order(new Customer(), new OrderLine[] {});

            CheckExceptionAndProblem(order.CalculateTotal, OrderValidationProblem.OrderLinesHasNoItems);

        }

That’s already much better i think… We can test that the exception is thrown, and that its Problem property is set correctly, and we only have one try/catch clause in our tests.

I’m still not happy with it though… The CheckExceptionAndProblem method is not reusable for anything other than OrderValidation, yet testing exceptions is a common problem so we should strive to provide something that’ll help us anytime we need to test exceptions.

How about a custom assert method that asserts that any piece of code that is passed to it throws the expected exception, and then returns the exception so you can easily assert anything else you wanna check in the returned exception? Sounds pretty good to me… let’s give it a shot:

        private T GetThrownException<T>(Action code) where T : Exception

        {

            try

            {

                code();

            }

            catch (T expectedException)

            {

                return expectedException;

            }

            catch (Exception e) {}

 

            Assert.Fail(“Expected exception of type {0} was not thrown”, typeof(T).FullName);

            return null;

        }

This method runs the code that was passed in, catches the expected exception and returns it. If the expected exception is not caught, it fails the current test.

Now we can modify our CheckExceptionAndProblem method so it looks like this:

        private void CheckExceptionAndProblem(Func<Decimal> function,

            OrderValidationProblem expectedOrderValidationProblem)

        {

            var expectedException = GetThrownException<OrderValidationException>(() => function());

            Assert.AreEqual(expectedOrderValidationProblem, expectedException.Problem);

        }

Now we can use the GetThrownException method pretty much anywhere where want to test exceptions and their properties.

Anyways, this is just one possible approach of testing exceptions in a much better way than the ExpectedException attribute offers us.

Btw, i think the xUnit.Net testing framework already provides similar approaches to what i used in this post

Share/Save/Bookmark

Posted in Test Driven Development | No Comments »

Stubbing with Rhino Mocks

Posted by Davy Brion on 7th April 2008

Rhino Mocks is an excellent mocking framework, but it makes simple stubbing very easy as well… I’m working on some code that has to retrieve data from AzMan services. These classes are basically just horrible wrappers around legacy COM stuff so they’re not really easy to work with. Luckily, these classes all return interface types so it is easy to mock/stub.

So for one of my tests, i wanted to create an IAzApplication instance which had an IAzScopes collection with 2 IAzScope instances. The IAzScopes interface pretty much only offers an indexer property, a Count property, and the GetEnumerator method. There’s also no concrete AzScopes type or something that you can create yourself for easy testing. Oh, and the IAzApplication interface defines no way of setting the IAzScopes instance to use… Joy!

Enter Rhino Mocks:

        public static IAzApplication CreateAzApplicationWithTwoAzScopes(string name, string scope1, string scope2)

        {

            MockRepository mockRepo = new MockRepository();

 

            IAzApplication app = mockRepo.Stub<IAzApplication>();

            IAzScopes scopes = mockRepo.Stub<IAzScopes>();

 

            var fakeScopes = new []

            {

                CreateAzScope(scope1, null, mockRepo),

                CreateAzScope(scope2, null, mockRepo)

            };

 

            SetupResult.For(scopes.GetEnumerator()).Return(fakeScopes.GetEnumerator());

            SetupResult.For(scopes.Count).Return(fakeScopes.Count());

            SetupResult.For(app.Scopes).Return(scopes);

            mockRepo.ReplayAll();

 

            return app;

        }

 

        public static IAzScope CreateAzScope(string name, string description, MockRepository repo)

        {

            IAzScope scope = repo.Stub<IAzScope>();

            scope.Description = description;

            scope.Name = name;

            return scope;

        }

 

        public static IAzScope CreateAzScope(string name, string description)

        {

            return CreateAzScope(name, description, new MockRepository());

        }

This allows me to (pretty) easily create the instances i need to perform my test:

        [TestMethod]

        public void Map_IAzApplicationWithScopes_ReturnsApplicationWithScopes()

        {

            IAzApplication azApplication =

                AzManEntityHelper.CreateAzApplicationWithTwoAzScopes(“myApp”, “scope1″, “scope2″);

 

            Application application =

                IAzApplicationToApplicationMapper.Map(azApplication, new AzManSidHelper(),

                “domain”, new MemberRepository());

 

            Assert.IsNotNull(application.GetChildren<Scope>().FirstOrDefault(s => s.Name == “scope1″));

            Assert.IsNotNull(application.GetChildren<Scope>().FirstOrDefault(s => s.Name == “scope2″));

        }

Works like a charm :)

Share/Save/Bookmark

Posted in Software Development, Test Driven Development | 5 Comments »

Bye Bye Noma

Posted by Davy Brion on 6th April 2008

As you may have noticed, i’ve been pretty quiet about Noma lately… I haven’t worked on it for weeks (or is it months now?), mostly because the project just doesn’t interest me anymore, and also because i haven’t had a lot of free time lately. When i do have some free time, i like to spend it on learning new things or just experimenting with different libraries or ideas instead of trying to work on something that no longer interests me, or feeling somewhat guilty about not working on it :)
So, the noma project can pretty much be considered dead from now on…

With that said, one of the things i’m playing around with now is setting up a sample application based on my northwind nhibernate mappings. The idea is basically to just use it as a playground to experiment with new techniques or libraries and come up with good design and architecture ideas. Obviously, i plan on posting about these experiments quite a lot ;) … depending on how much free time i’ll have obviously :)

Share/Save/Bookmark

Posted in Uncategorized | No Comments »

Upgrading to NHibernate 2.0 alpha 1

Posted by Davy Brion on 6th April 2008

I just wasted time on something really stupid while i was upgrading to NHibernate 2.0 alpha 1, so i’m posting it here just in case someone else runs into this…

With NHibernate 1.2, i created my SessionFactory like this:

                Configuration configuration = new Configuration()

                    .AddAssembly(“MyMappingAssembly”);

                _sessionFactory = configuration.BuildSessionFactory();

But it didn’t work with NHibernate 2.0, i got the following exception:

failed: NHibernate.MappingException : Could not compile the mapping document: Northwind.Domain.Mappings.Region.hbm.xml
  ----> System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.
TearDown : System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> System.NullReferenceException : Object reference not set to an instance of an object.
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(262,0): at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(436,0): at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(1557,0): at NHibernate.Cfg.Configuration.ProcessMappingsQueue()
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(1548,0): at NHibernate.Cfg.Configuration.AddDocumentThroughQueue(NamedXmlDocument document)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(1541,0): at NHibernate.Cfg.Configuration.AddXmlReader(XmlReader hbmReader, String name)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(506,0): at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(544,0): at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(615,0): at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(601,0): at NHibernate.Cfg.Configuration.AddAssembly(String assemblyName)
	C:\mydocs\src\Northwind\trunk\Northwind\Northwind.Tests\Domain\Mappings\NHibernateTest.cs(27,0): at Northwind.Tests.Domain.Mappings.NHibernateTest.SetUp()
	--KeyNotFoundException
	at System.ThrowHelper.ThrowKeyNotFoundException()
	at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Dialect\Dialect.cs(173,0): at NHibernate.Dialect.Dialect.GetDialect(IDictionary`2 props)
	c:\DATA\Projects\nhibernate\2.0.x\copy1\nhibernate\src\NHibernate\Cfg\Configuration.cs(428,0): at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc)

Apparently, it failed when trying to instantiate the Dialect class to use. So i figured something must have changed in the configuration so i checked everything and it looked alright to me. I tried a few things but i just couldn’t get it working, so i downloaded the alpha 1 code so i could step through it and see why it wouldn’t configure properly… turns out that it just didn’t read the configuration settings at all. In NHibernate 1.2, it automatically did this, but now it’s a required explicit step. Changing my above code to this worked:

                Configuration configuration = new Configuration()

                    .Configure()

                    .AddAssembly(“MyMappingAssembly”);

                _sessionFactory = configuration.BuildSessionFactory();

Share/Save/Bookmark

Posted in NHibernate | 12 Comments »