Wednesday, November 9, 2011

NHibernate 3.2 One-To-One Mapping with Foreign Key

Preface


Until recently, I'd been using FluentNhibernate to do my entity mappings in code. Recently, I decided to try the Loquacious (in-code) mapping now part of NHibernate. Since the project was already setup with NHibernate, it the mapping classes had to be converted. This was a (fairly) direct process, except for an oddball mapping we had.


The Problem

Using Loquacious (in code) mapping with NHibernate 3.2, we needed to do a one-to-one mapping of entities where the SQL Server tables had a PK<->FK relationship.

Our Design

Our tables looked like...

User
-----------
UserId (PK)
UserName

UserDetail
--------------------
UserDetailId (PK)
UserId (FK / Unique)
Notes

Our entities looked like...
public class UserInfo
{
    public virtual int Id { get; set; }
    public virtual string UserName { get; set; }
    public virtual UserDetail Details { get; set; }
}

public class UserDetail
{
    public virtual int Id { get; set; }
    public virtual UserInfo User { get; set; }
    public virtual string Notes { get; set; }
}

The important thing to note here is that the User entity does not have a List<Details> property. There will only be one UserDetail for any particular User.

What is a One-To-One Relationship?

A one to one mapping shouldn't use a foreign key. Instead, the tables should both use a synchronized primary key (the pk on both tables are the same value:

UserInfo
-----------
UserInfoId (PK)
UserName

UserDetail
-----------------
UserDetailId (PK/FK)
DetailInfo

The Solution

I failed at using Google to find a solution. There were a few mentions on Stack Overflow. One of the how-to articles on nhforge.org did get me started in the right direction. The problem with the article is that it uses xml mapping (didn't want to do that). It does not one of the major headaches I ran into: that when mapped it would fail to insert the dependent entity.

After poking around for some time, I stumbled on the solution (for our case): it was to reference the foreign key in the dependent entity. Our mapping classes turned out to look like the following:

public sealed class UserInfoMap : ClassMapping
{
    public UserInfoMap()
    {
        Table("UserInfos");

        Id(o => o.Id, map =>
        {
            map.Generator(Generators.Identity);
            map.Column("UserInfoId");
        });

        Property(o => o.UserName);

        OneToOne(o => o.Details,
                 map =>
                 {
                     map.PropertyReference(typeof(UserDetail).GetProperty("User"));
                     map.Cascade(Cascade.All);
                 });
    }
}


public class UserDetailMap : ClassMapping
{
    public UserDetailMap()
    {
        Table("UserDetails");

        Id(o => o.Id, map =>
        {
            map.Generator(Generators.Identity);
            map.Column("UserDetailId");
        });

        Property(o => o.Notes);

        ManyToOne(o => o.User,
                  o =>
                  {
                      o.Column("UserId");
                      o.Unique(true);
                      o.ForeignKey("Users_UserDetails_FK1");
                  });
    }
}

Hope this helps someone else...

Monday, October 24, 2011

NHibernate and Missing Castle dll

The Problem

MSbuild does not see a reference to the NHibernate.ByteCode.Castle assembly when building a project. Thus,  it does not copy the file into the output directory. This causes an exception when trying to execute code which relies on NHibernate.

The exception seen is usually something like: Could not load file or assembly 'NHibernate.ByteCode.Castle' or one of its dependencies...


The Solution


Bury a reference to the Castle assembly within your code:

class IncludeCastleDllInBuild : NHibernate.ByteCode.Castle.ProxyFactory
{
    //note : prevents missing dll issue with the Castle dll
}

Wednesday, October 19, 2011

FluentNhibernate and Bidirectional Relations

Preface

My last position had me using FluentNHibernate to handle my object persistence. We were using Oracle as a store. Many of the tables were quite large (100+ columns), and often did not have a primary key. The result was I often didn't have a good opportunity to use FNH's (NH's?) relationship capabilities.

My new position has me introducing FNH to some developers. The project is using SQL Server 2008 as a store, with tables that have primary keys, and other little should-haves.

The Problem

When saving new parents with new children, the children would not have their foreign key updated. The parent would save correctly. When any child object would save the database would throw an exception, because the foreign key constraint (not null) would be violated.

Our Design

Names changed to protect the innocent.

Our design was simple: a record in the database representing a file, and records being held in another table representing records within the file. After a bit of research, we realized that we needed a bi-directional relationship.

public class MyFile
{
    public virtual int MyFileId { get; set; }
    public virtual string FileName { get; set; }
    public virtual IList<Record> Records  { get; set; }
}

public class Record
{
    public virtual int MyRecordId { get; set; }
    public virtual int MyFileId { get; set; }
    public virtual MyFile SourceFile { get; set; }
    public virtual int RecordType { get; set; }
}

Our mapping classes were pretty simple too:

public sealed class MyFileMap : ClassMap<MyFile>
{
    public MyFileMap()
    {
        Table("MyFile");

         Id(o => o.MyFileID, "MyFileID").GeneratedBy.Identity();

        Map(o => o.FileName).Column("FileName");

        HasMany(o => o.Records).KeyColumn("InFileID")
            .Inverse().Cascade.All().AsBag();
    }
}

public sealed class RecordMap : ClassMap<Record>
{
    public WEXTicketRequestDetailMap()
    {
        Table("Record");

        Id(o => o.RecordID, "RecordID").UnsavedValue(0);

        References(o => o.SourceFile)
            .Column("MyFileID").Cascade.All();

        Map(o => o.RecordType).Column("RecordType");
    }
}

We'd create the classes and attempt to save them to the database:

// ... some code
var record = new Record();
var file = new MyFile{ // set some file stuffs here };
file.Records = new List<Record>{ record };
// ... more stuff here, including creating a session and transaction
session.Save(file);

This would result in an exception being thrown, as the foreign key on the Record object wasn't being set.

The Solution

A little searching (okay, a lot of searching) finally led us to a Stack Overflow post. Therein an answer by James Gregory showed us what we were doing wrong: we needed to set the parent entity on the child.

// ... some code
var record = new Record();
var file = new MyFile{ // set some file stuffs here };

record.SourceFile = file; // <-- this is the important part

// ... more stuff here, including creating a session and transaction
session.Save(file);

Once that was done, everything was good.

Monday, August 29, 2011

SpecFlow Tests and Lists

Some days I just can't see the forest for the trees...

Sometimes you just want to pass a list to check against:

Scenario: some files match
	Given I have the following files
		| FileName           |
		| test.txt           |
		| sample.txt         |
		| sample.file.txt |
		| sample.file2.txt |
		And  I have the following processes
			| Regex        | Process         |
			| sample.*.txt | TestProcess.bat |
	When I run the application
	Then The files should be processed
		| FileName           |
		| sample.file.txt |
		| sample.file2.txt |

If you're using SpecFlow and need to pass in a list to one of your bindings, here's a simple one-liner to convert a table to a list of strings:

[TestClass]
[Given(@"I have the following files")]
public void GivenIHaveTheFollowingFiles(Table table)
{
    var files = table.Rows.Select(o => o["FileName"]);
}

'files' will be a list of the strings in the table. I'm sure there's a better way, but this one works.

Monday, August 15, 2011

Useful Things

Edit: Updated Feb 2012 to reflect new stuff I'm using...

A loooong time ago, an associate asked me to come up with a list of useful things. This post is the start of that. It's a dump of some of the things I use on a daily basis along with my comments:

Development Tools
  • Visual Studio - Goes without saying.
  • NuGet - Package manager (with VS integration). Must have.
  • ReSharper - Excellent helper tool. Enhances Visual Studio's UI. Well worth the money.
  • VS10x Code Map - Adds a new view of the code file you're working in. Really useful when your mates like to have 10 classes and 2500 lines of code in one file.
  • dotPeek - Also by JetBrains. An excellent source code explorer.
TDD/BDD
  • NCrunch - Runs your unit tests while you code. Immediate feedback. Or, ZMOG! Why aren't you using this now!!
  • FluentAssertions - Make your test assertions read more like English. This really is something you should use in all your tests.
  • NSubstitute - A very good mocking framework. I use this one over Moq, because I like NSubstitute's interface better.
  • Moq - Another very good mocking framework.
OR/Ms
  • NHibernate - Flexible, powerful, and has tons of support. What more could you ask for? why aren't you using this?
  • FluentNHibernate - I used this as much for almost all my data access, until the loquacious (in-code) stuff was added to NHibernate.
UI Stuff
  • jQuery & jQueryUI - Must have when it comes to doing JavaScript stuffs.
IoC Containers
  • Castle Windsor - This has become my main IoC Container. The interceptors work well enough for AoP, and I really like the facilities.
  • Unity - IoC container from Microsoft. I've switched to this, simply because I like the intercepts for AOP better than Ninject.
  • Ninject - Open source IoC Container. I used this one a lot, still occasionally do.
Source Control
  • TFS - The main MS one.
  • Git - Open source SCM, with free project hosting options. I like this better than TFS, but I have to use TFS at work.
  • VisualHg or TortoiseHg - Mercurial for Windows types.
Misc Tools

Monday, June 6, 2011

Fluent Assertions

Fluent assertions are a way of making unit test assertions more human readable. I've been using them for some time, and have come to really appreciate the difference they make in transforming the way a unit test is read. It's a pretty simple concept, best illustrated by an example.

A traditional (if there is such a thing) unit test might look something like this:

[TestClass]
public class MyServiceLocatorSecs
{
    [TestMethod]
    public void Resolve_ResolvingAnInterface_ReturnsType()
    {
        var sut = new MyServiceLocator(new UnityContainer());
        sut.RegisterType<IServiceA, ServiceA>();

        var results = sut.Resolve<IServiceA>();

        // basic mstest assertion
        Assert.IsInstanceOfType(results, typeof (ServiceA));
    }

    public interface IServiceA { }
    public class ServiceA : IServiceA { }
}


However, if we use the built-in nUnit-style asserts, we see the assertion reads a little easier:

[TestClass]
public class MyServiceLocatorSecs
{
    [TestMethod]
    public void Resolve_ResolvingAnInterface_ReturnsType()
    {
        var sut = new MyServiceLocator(new UnityContainer());
        sut.RegisterType<IServiceA, ServiceA>();

        var results = sut.Resolve<IServiceA>();

        // nUnit-style assertion
        Assert.That(results, Is.TypeOf<ServiceA>());
    }

    public interface IServiceA { }
    public class ServiceA : IServiceA { }
}

Finally, we can use some form of helper assembly to make the a truly fluent assertion:

[TestClass]
public class MyServiceLocatorSecs
{
    [TestMethod]
    public void Resolve_ResolvingAnInterface_ReturnsType()
    {
        var sut = new MyServiceLocator(new UnityContainer());
        sut.RegisterType<IServiceA, ServiceA>();

        var results = sut.Resolve<IServiceA>();

        // fluent assertions
        results.Should().BeOfType<ServiceA>();
    }

    public interface IServiceA { }
    public class ServiceA : IServiceA { }
}

I've found that I really like the way the fluent assertions read. There are a number of ways to include these in your projects. You can include a code file, or NuGet to import an assembly. Heck, you can even roll your own if you really wanted.

The end result are tests which read very clearly. When combining fluent assertions with context/specification unit test, you wind up with tests that very much describe the code:

[TestClass]
public class WhenResolvingAContract : GivenAServiceLocator
{
    private IServiceA results;

    protected override void Context()
    {
        base.Context();
        Container.Resolve<IUnityContainer>()
            .RegisterType<IServiceA, ServiceA>();
    }

    protected override void BecauseOf()
    {
        results = Sut.Resolve<IServiceA>();
    }

    [TestMethod]
    public void ShouldReturnAnInstanceOfTheRegisteredClass()
    {
        results.Should().BeOfType<ServiceA>();
    }
}

Sunday, May 22, 2011

Unit Testing Unity 2.0 Registrations


One of the areas I don't test as well as I should are the bindings of my IoC containers. I'm making a conscious effort to change that. Really, in the end, TDD is all about not writing any code without a failing test. So I came up with a way to test the bindings that are registered by my registration class.

Here's the extension method which I'm now using to help test Unity 2.0 bindings:

public static class MappingTestExtensions
    {
        public static void ShouldHaveMapping<TFrom, TTo>(this IUnityContainer container)
        {
            var registration = container.Registrations
                .FirstOrDefault(o => o.RegisteredType.Name == typeof (TFrom).Name);
            Assert.That(registration, Is.Not.Null,
                        "Could not find the mapped type {0}",
                        typeof (TFrom));
            Assert.That(registration.MappedToType.Name == typeof (TTo).Name,
                        "Type {0} was not mapped to type {1}",
                        typeof (TFrom),
                        typeof (TTo));
        }
    } 

The names of the types are being used, because I couldn't get a direct type comparison to work. When I get a bit of time, I plan to research that further.

I've been using Context Specification style test naming for a couple months, and have really grown to like it. Rolled into the base ContextSpecification class is a an auto mocking container which is largely taken from an ElegantCode blog post. With that in mind, an example class would look like this:

public static class UnityBootstrapTests
{
        public class UnityBootstrapBehavior : ContextSpecification
        {
            protected UnityBootstrap Sut;

            protected override void Context()
            {
                Container.RegisterInstance<IUnityContainer>(new UnityContainer());

                Sut = Container.Resolve<UnityBootstrap>();
            }
        }

        [TestClass]
        public class WhenPassedAContainer : UnityBootstrapBehavior
        {
            protected override void BecauseOf()
            {
                Sut.SetDependencies(Container.Resolve<IUnityContainer>());
            }

            [TestMethod]
            public void ShouldRegisterAuthenticationFacade()
            {
                Container.Resolve<IUnityContainer>()
                    .ShouldHaveMapping<IAuthenticationFacade, AuthenticationFacade>();
            }

            [TestMethod]
            public void ShouldRegisterDaoClass()
            {
                Container.Resolve<IUnityContainer>()
                    .ShouldHaveMapping<ISupportsDataAccess, DefaultDao>();
            }
        }

    }

I then  did some googling to see how my solution stacked up. One msdn blog post used techniques which are no longer available in Unity 2.0 (but would help if you're still using 1.x). A Patterns and Practices article had a solution which very closely matched mine. It also includes how to check for a singleton registration.