sharp bites

standing on the shoulders of giants

AltNerDinner: Part 4. Introducing NHibernate. Because POCO is enough

It’s time already to introduce a proper persistence solution. NHibernate can be a little intimidating at first for a new-comer, but I undoubtedly think it’s the way to go. And it’s not really more difficult than the other contenders anymore. Its two major drawbacks (hand writing all that XMhelL mapping and not strongly typed queries) are solved (or in serious process of it) by Fluent NHibernate and NHibernate.Linq.

Other than that, the only difficulty relies in learning a few concepts inherent to OR/Ms. Most notably the Unit of Work pattern and Lazy Loading, and all the stuff around them (namely repositories, query objects, persistence ignorance, POCOs, DTOs, entities/value objects and equality, inheritance mapping, dynamic proxies, caching, anemic domains, active record, transactions, concurrency, session lifetime, unit testing, select n+1 problems and other pitfalls to avoid,  …). [NOTE: If you need more info on this topics I’d recommend you to visit the official nhibernate site.]

Sounds scary? It might seem using an OR/M brings in more problems that the ones it solves, but I don’t think it is the case, except for maybe the most trivial apps (like AltNerdDinner, hehe, I know). Even if you are writing a relatively simple app, you can still greatly benefit from using NHibernate (or Active Record on top of it). If your app has inherent complexity, well, of course you’ll have to do your homework and learn a few concepts, but that’s not your OR/M’s fault. Using a hand-rolled DAL won’t make your problems go away (quite the opposite, I’d dare to say).

As I said, most (if not all) of this problems exist in all OR/M, it’s just that some of them somehow try to hide this complexity in one or another way. The problem is, this is a can of worms that can lead to very bad practices and slap on your face at any moment. And this is were I think this is were NHibernate excels at, its flexibility. It gets out of your way.

Ok, enough talking! Show me the code!

To use NHibernate and NH.Linq we need to add a reference in our project to the following dll’s: NHibernate, NHibernate.Linq, FluentNHibernate (if we hadn’t already) and lastly NHibernate.ByteCode.Castle if we want to use Castle’s dynamic proxy as our proxy generator of choice.

Here is the code for my DinnerRepository implementation using NHibernate:

public class NhDinnerRepository : IDinnerRepository
{
private readonly ISession _session;

public NhDinnerRepository(ISession session)
{
_session = session;
}

private INHibernateQueryable<Dinner> GetDbContext()
{
return _session.Linq<Dinner>();
}

public IQueryable<Dinner> FindAllDinners()
{
return GetDbContext().AsQueryable();
}

public IQueryable<Dinner> FindByLocation(float latitude, float longitude)
{
return GetDbContext().Where(d => d.Distance(latitude, longitude) < 100).AsQueryable();
}

public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in GetDbContext()
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}

public Dinner GetDinner(int id)
{
return GetDbContext().SingleOrDefault(d => d.DinnerID == id);
}

public void Save(Dinner dinner)
{
if (!dinner.IsValid)
{
throw new ApplicationException("Rule violations");
}

_session.SaveOrUpdate(dinner);
}

public void Delete(Dinner dinner)
{
_session.Delete(dinner);
}


As you see, I am returning IQueryable<Dinner> instead of traditional .NET collections. Some people think IQueryable is the best thing since slice bread, others are ditching repositories entirely, some prefer using query objects, others advocate for explicit repositories, some use generic ones and I just don’t know yet, but decided to go at least with repositories because I want to take control of how entities are persisted.



To instantiate my NHibernate repository, I need to supply it with an ISession. I don’t create the ISession inside the repository, since this is considered a bad practice. Instead, I create a new Session per request. To do that, I expected I would have some infrastructure in place in MvcContrib, but that was not the case. Jeffrey Palermo posted a NHibernate wrapper to manage ISession, but I thought that class had too many responsibilities, so I separated it in the following.



public class SessionFactoryBuilder
{
private static ISessionFactory _sessionFactory;

private readonly IPersistenceConfigurer _dbConfiguration;

public SessionFactoryBuilder(IPersistenceConfigurer dbConfiguration)
{
_dbConfiguration = dbConfiguration;
}

public ISessionFactory Build()
{
if (_sessionFactory == null)
{
_sessionFactory = GetDbConfiguration().BuildSessionFactory();
}

return _sessionFactory;
}

public Configuration GetDbConfiguration()
{
return Fluently.Configure()
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Dinner>())
.Database(_dbConfiguration)
.BuildConfiguration();
}
}


This builds the session factory and also returns the configuration (useful to create the schema). It needs an IPersistenceConfigurer, which I supply from the constructor, in order to be able to switch between different configurations (i.e. MSSQL and SQLite), as shown below:



public class MsSqlPersistenceConfigurerFactory : IPersistenceConfigurerFactory
{
private string _connectionString;

public MsSqlPersistenceConfigurerFactory(string connectionString)
{
_connectionString = connectionString;
}

public IPersistenceConfigurer GetPersistenceConfigurer()
{
return MsSqlConfiguration.MsSql2005
.ConnectionString(c => c.Is(_connectionString))
.ShowSql()
.FormatSql()
.ProxyFactoryFactory<ProxyFactoryFactory>();
}
}


Life of a Session



We need to create the aforementioned ISession somehow. In Web applications, it’s generally a good practice to create a new Session on every request. For that, Ayende recently suggested to just stick it in the global.asax, but I prefer to put it in a separate  IHttpModule.



public class NhSessionPerRequestModule : IHttpModule
{
private readonly ISessionFactory _sessionFactory;

public NhSessionPerRequestModule(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public void Init(HttpApplication application)
{
application.BeginRequest += delegate
{
CurrentSession = _sessionFactory.OpenSession();
};

application.EndRequest += delegate
{
if (CurrentSession != null)
{
CurrentSession.Dispose();
}
};
}

public static ISession CurrentSession
{
get { return (ISession)HttpContext.Current.Items["current.session"]; }
private set { HttpContext.Current.Items["current.session"] = value; }
}

public void Dispose()
{
}
}



In my Global.asax, I configure it as follows:



private static readonly ISessionFactory SessionFactory = CreateSessionFactory();
private static IWindsorContainer _container;

private static ISessionFactory CreateSessionFactory()
{
string connString = ConfigurationManager.ConnectionStrings["AltNerdDinner"].ConnectionString;
return new SessionFactoryBuilder(
new MsSqlPersistenceConfigurerFactory(connString)
.GetPersistenceConfigurer())
.Build();
}

private readonly NhSessionLifetimeModule _nhSessionLifetimeModule =
new NhSessionLifetimeModule(SessionFactory);

public override void Init()
{
base.Init();
_nhSessionLifetimeModule.Init(this);
}


Lastly, this is my current configuration of the container in order to register the components:



private void RegisterComponents()
{
_container = new WindsorContainer();
_container.AddFacility<FactorySupportFacility>();

ControllerBuilder.Current.SetControllerFactory(
new WindsorControllerFactory(_container));

_container.Register(
Component.For<ISession>()
.UsingFactoryMethod(() => NhSessionLifetimeModule.CurrentSession)
.LifeStyle.Transient);

_container.Register(
Component.For<IDinnerRepository>()
.ImplementedBy<NhDinnerRepository>().LifeStyle.Transient);

_container.RegisterControllers(Assembly.GetExecutingAssembly());
}

Java and (the lack of) CoC

"Java is a DSL to transform big Xml documents into long exception stack traces."

Scott Bellware

AltNerdDinner: Part 3. Introducing Fluent NHibernate. Mapping, the easy way

This is part 3 of the AltNerdDinner Series.

One of the things I always disliked the most when exploring NHibernate was the need of declaring all the mappings in XMhelL. And don’t know about you, but that’s not something I want to be spending my time creating, modifying, hand-refactoring or debugging tedious tons of this crap.

Fast forward to 2008 and say hello to Fluent NHibernate. (And don’t forget to thank Jeremy Miller, James Gregory et al!). It is basically a way to programmatically declare the mappings, allowing you to go from this:

<?xml version="1.0" encoding="utf-8" ?>  
<
hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="QuickStart" assembly="QuickStart">

<
class name="Cat" table="Cat">
<
id name="Id">
<
generator class="identity" />
</
id>

<
property name="Name">
<
column name="Name" length="16" not-null="true" />
</
property>
<
property name="Sex" />
<
many-to-one name="Mate" />
<
bag name="Kittens">
<
key column="mother_id" />
<
one-to-many class="Cat" />
</
bag>
</
class>
</
hibernate-mapping>


To this:



public class CatMap : ClassMap<Cat>
{
public CatMap()
{
Id(x => x.Id);
Map(x => x.Name)
.Length(16)
.Not.Nullable();
Map(x => x.Sex);
References(x => x.Mate);
HasMany(x => x.Kittens);
}
}


What it gives you, you may ask? Compile-time checks and refactoring support, for a start.



But wait, there is more!



Fluent NHibernate is built with Convention over Configuration in mind. So, if you adhere to it, you can greatly reduce the amount of mapping needed, by virtue of auto mapping. And you can combine that with explicit ClassMap mappings, like the one above, they are not mutually exclusive.



Mapping your domain can be as simple as:



AutoMap.AssemblyOf<Product>();


And if you call within the next 5 minutes we throw in Conventions for free!



"Ok, that might be great for a greenfield project, but I am working in a big brown piece of … code", I hear you saying. So you may not have the choice to call your Id’s "Id" or name your tables exactly after your classes. Conventions can greatly help here, allowing you to define your own conventions. That is, if your database naming follows any convention at all, and wasn’t defined by a bunch of monkeys typing at random.



For further info, check the site, wiki and mailing list.



AltNerdDinner’s mappings



Here are the mapping files for AltNerdDinner.



public class DinnerMap : ClassMap<Dinner>
{
public DinnerMap()
{
Id(x => x.DinnerID);
Map(x => x.Address).Not.Nullable();
Map(x => x.ContactPhone).Not.Nullable();
Map(x => x.Country).Not.Nullable();
Map(x => x.Description).Not.Nullable();
Map(x => x.EventDate).Not.Nullable();
Map(x => x.HostedBy).Not.Nullable();
Map(x => x.Latitude).Not.Nullable();
Map(x => x.Longitude).Not.Nullable();
Map(x => x.Title).Not.Nullable();
HasMany(x => x.RSVPs).Cascade.AllDeleteOrphan();
}
}



public class RSVPMap : ClassMap<RSVP>
{
public RSVPMap()
{
Id(x => x.RsvpId);
Map(x => x.AttendeeName).Not.Nullable();
References(r => r.Dinner).Nullable();
}
}


One gotcha that had me fiddling around for a while was that Nullable part on the Dinner reference in RSVPMap. If you don’t set it to nullable, you’ll get an exception when trying to persist the entities. And even if you set it to nullable, you’ll find out, NHibernate executes two queries to insert the RSVP.




    INSERT INTO  [RSVP] (AttendeeName, Dinner_id) VALUES (@p0, @p1);

    select SCOPE_IDENTITY();


    @p0 = ‘alberto’,


    @p1 = 9


    UPDATE [RSVP] SET Dinner_id = @p0 WHERE RsvpId = @p1; @p0 = 9, @p1 = 21




You can find more info about this behavior in the official nhibernate site.



So, what I have done instead is to set the RSVP as the managing part of the relationship, changing it back to not nullable and using Inverse() on the Dinner’s mapping side.




It is not possible to make the "many part" responsible for this. What this means is that we have to persist our entities calling:



Dinner dinner = _dinnerRepository.GetDinner(id);
var rsvp = new RSVP{ AttendeeName = username };
rsvp.Dinner = dinner;
dinner.Rsvps.Add(rsvp);
_dinnerRepository.Save(dinner);


That’s not very ideal, so I have included an AddRsvp() method in Dinner to handle that. Now I have:



Dinner dinner = _dinnerRepository.GetDinner(id);
dinner.AddRsvp(new RSVP{ AttendeeName = User.Identity.Name });
_dinnerRepository.Save(dinner);


Much cleaner! In order to avoid confusion when adding an RSVO, I have changed the type of the collection to an IEnumerable<RSVP>, so that the collection cannot be modified directly, but only by means of Dinner (which is a good practice if you want to follow DDD, anyway). Because of that, I had to modified the DinnerMap to use a backing field for it. In the future I might revisit this relationship to include the User in the domain again and change it to a less CRUD-y style. You can read more on Domain-Driven fluency from Udi Dahan.



Anyway, here is the final mapping I have come up with:



public class RSVPMap : ClassMap<RSVP>
{
public RSVPMap()
{
Id(x => x.RsvpId);
Map(x => x.AttendeeName).Not.Nullable();
References(r => r.Dinner).Not.Nullable();
}
}



public class DinnerMap : ClassMap<Dinner>
{
public DinnerMap()
{
Id(x => x.DinnerID);
Map(x => x.Address).Not.Nullable();
Map(x => x.ContactPhone).Not.Nullable();
Map(x => x.Country).Not.Nullable();
Map(x => x.Description).Not.Nullable();
Map(x => x.EventDate).Not.Nullable();
Map(x => x.HostedBy).Not.Nullable();
Map(x => x.Latitude).Not.Nullable();
Map(x => x.Longitude).Not.Nullable();
Map(x => x.Title).Not.Nullable();
HasMany(x => x.Rsvps).Access.CamelCaseField(Prefix.Underscore)
.Inverse().Cascade.AllDeleteOrphan();
}
}

AltNerdDinner: Part 2. Rich Man’s Dependency Injection

This is part 2 of the AltNerdDinner Series.

The classes in NerdDinner use dependency injection (constructor injection, to be more precise), which is a form of Inversion of Control that allows you to break the dependencies between classes, minimizing coupling (i.e. a Good Thing ™). Instead having classes with direct dependencies  on other classes, and instantiating them directly, classes are dependent on interfaces, and the concrete implementation is injected via the constructor, in this case, or via a setter in the case of setter injection. Constructor injection is preferred for required dependencies, as it makes dependencies more explicit, and setter injection is usually reserved for optional dependencies.

Using this technique, the responsibility of providing the dependencies is delegated to the calling object (hence the term Inversion of Control).

Poor Man’s Dependency Injection

The problem with the NerdDinner codebase is that, besides the constructor that accepts the required dependencies, they added a default constructor that news up those dependencies. Here is an example:

public DinnersController() : this(new DinnerRepository())
{
}

public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}


This may look like a good compromise. You get the decoupling needed to run your tests (by means of the constructor accepting parameters) and you are also able to instantiate you classes calling the default constructor, without the added complexity of an IoC container. However this technique is considered an anti-pattern (although not everybody agrees) leading to many headaches. By adding this constructor we’re almost at square one again. Our classes are still coupled, and if we need to add new dependencies, we’ll have to go hunting around to fix all the constructor calls.



If I were a rich man



So now you are convinced to use an IoC container, you can have a look this container guidelines by Jimmy Bogard. He may not consider his recommendations as best practices, but I do (and so should you, IMHO). I picked Castle Windsor as my framework of choice. As usual, there are plenty of alternatives. Even though the API is not the cleanest of all the frameworks, I favored Windsor because it is very mature, is widely adopted, it also supports .NET 2.0, and has good integration with NHibernate. It also is the container used in S#arp Architecture, which is something I will probably end up using. Otherwise, my choice would be StructureMap.



In order to use Windsor, you have to reference on your project Castle.Core, Castle.MicroKernel and Castle.Windsor. To ease the configuration of the container, I also downloaded MvcContrib (which I was planning to use anyway) and added a reference to MvcContrib.Castle.



This is the code needed to register the controllers and the Repository.



private void RegisterComponents()
{
_container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(
new WindsorControllerFactory(_container));
_container.RegisterControllers(Assembly.GetExecutingAssembly());
_container.Register(
Component.For<IDinnerRepository>()
.ImplementedBy<InMemoryDinnerRepository>());
}


To allow the creation of the controllers by the MVC framework, you need to supply a ControllerFactory that can instantiate them, as they now take dependencies on their constructors. MvcContrib provides one for Windsor, as well as the method RegisterControllers to, guess what, registering all the controllers in a specified assembly. I also registered my DinnerRepository, so that Windsor can resolve the references to it.

AltNerdDinner: Part 1. Removing unwanted dependencies

The first thing I have done is to set up the project on github, so if you want to have a look at the code, check the AltNerdDinner repository. Then I set up the project following the guidelines of my series Continuous Integration series.

Now we are set, there is some stuff I don’t want in AltNerdDinner, so I am mercilessly going to get rid of it.

Bye, MSTest

MSTest gives nothing useful beyond integration in VS (for which I prefer ReSharper’s Test Runner or TDD.NET). I won’t say it sucks, but Phil Haack did. It’s just there to satisfy MS-Only shops. It’s slow, and it evolves slowly too. It lags behind the alternative frameworks. Oh, and it requires VS to be installed on your build server (crazy!), and…

So I replaced it with good ol’  NUnit. It basically involves replacing:

using Microsoft.VisualStudio.TestTools.UnitTesting; by using NUnit.Framework;

[TestClass] and [TestMethod] by [TestFixture],  and [Test]

and a bunch of calls to Assert.IsInstanceOfType(object, type); by Assert.IsInstanceOf(type, object); (pay attention to the signature change!).

We don’t need no membership provider

Right now I don’t want to deal with membership provider. I think it’s bloated and I don’t want to have to mess with the authentication right now, so I am going to replace it with a FakeMembershipService for the moment and leave the decision of whether revisiting it or completely replacing it (probably the latter) for a later time.

LINQ to SQL is dead, long live NHibernate

L2S is probably a decent option for this kind of simple app, and it’s very easy to quickly duct-tape a simple app. It has some goodies, like the visual designer and of course Linq. But it’s not the best option if your app gets bigger and you need some more advanced ORM features, like different mapping capabilities or different databases support. It’s not a bad tool, but it has some limitations that need to be addressed and, unfortunately, the fact that L2S is being killed means you are better not investing hard into it.

So I am planning to replace it with NHibernate, a mature and tested product  that fits my needs. But just not yet. Right now, I will simply remove the L2S stuff and work with POCOs and an InMemoryRepository implementation (which is basically the FakeDinnerRepository present in the Tests project).

The model

As we can see on the picture of the original model, the domain is quite simple.image

I have simply created POCO classes replacing the L2S generated ones.

After all the changes, we run all the tests and…

tests-green

We’re done!

The road to Continuous Integration. Part 3: Script it, build it, test it, break it, fix it. Commit it.

Ideally, any new developer in your team should be able to build your project with a single command or double-click. To accomplish that, we are going to use a build script.
You can also pick your poison here, too. I am going to stick with nant for the moment, because it’s the most mature and broadly used, and the one I know better, despite of the XMHell that is the angle-bracket orgy it imposes. Rake seems nice, and has less noise than the others, but I don’t like the fact that I have to install ruby and rake separately. As I said, I like all of my dependencies being included in source control, so that my projects are self-contained (there are some efforts to get ruby and rake as a single executable, though). If you are hesitating between msbuild and nant, you can check out a comparison between nant and msbuild I did a while ago.
project-structure
As you can see on the picture, I have added two build scripts to the root of AltNerdDinner. common-targets.build has, you know, common nant targets. It’s a script I reuse between projects and it has all the tasks I usually execute (compile, recompile, publish or package the project, run the tests, analyze the code or binaries, etc). AltNerdDinner.build is the specific script for this project. By virtue of Convention over Configuration on the project structure and directory and file names, we can remove a lot of unnecessary noise. By adhering to conventions, we just have to set up a couple of properties and simply delegate on common-targets.build for most (if not all) of the tasks, just defining the dependencies between tasks and passing parameters to configure the task where needed.

You can see below how simple it gets, with only 16 lines of code:




<?xml version="1.0" ?>
<
project name="AltNerdDinner" default="compile">
<
property name="dir.root" value="${path::get-full-path('.')}" />
<
include buildfile="${dir.root}/common-targets.build" />
<
property name="file.solution" value="${dir.root}/NerdDinner.sln" />
<
property name="file.project" value="${dir.root}/src/NerdDinner/NerdDinner.csproj" />
<
property name="assembly.tests" value="NerdDinner.Tests.dll" />

<
target name="compile" depends="common.clean, common.init, common.compile" />
<
target name="test" depends="compile, common.test" />
<
target name="publish" depends="test, common.publish" />
<
target name="zip" depends="publish, common.zip" />
<
target name="analyze" depends="publish, common.stylecop, common.ndepend" />
<
target name="build" depends="publish, analyze" />
<
target name="build-full" depends="publish, analyze, zip" />
</
project>



There is also a go.bat script, which just calls nant, passing AltNerdDinner.build as the build file. As a side note, notice that my solution file is in the root of the project instead of in src. I like to keep it there so that I can easily refer to the root of the project from it (useful if you want to dome some pre/post build stuff on Visual Studio or for other tools than reference your solution).

What do you see on the picture?

Monotouch 1.0 was released today. I was quite shocked when I saw the logo. Look at it for a second. What do you see there?
It might be my perturbated mind, but I was quite shocked when I felt it was “showing me the finger”. It actually took me a minute (I said I was shocked) to realize it was not that finger. Still, maybe that logo deserves a revamp. Just making clear the first finger is a thumb will suffice.

The road to Continuous Integration. Part 2: Shake your tree

As I stated in the first part of this Continuous Integration series, one of the aims of storing your stuff under source control is being able to build your project from a fresh checkout, without needing to manually install or configure anything.

To accomplish this, it is always useful to use a standardized tree structure. You can have a look at some of the popular open source projects you use and love to get ideas on how to organize things. Now that your have everything under source control (don’t you?), we can start moving a few things around.

On the picture you can see a very typical structure for a project.

The src folder contains the different projects in their respective folders.
The lib folder will contain any third-party library needed to run our project. This is, any dependency that has to be deployed with our project (e.g. NHibernate, Windsor, etc).

The tools folders will contain any tools needed to build our project. It will contain tools like nant, nunit or fxcop, which we will use but won’t distribute with our application.

The build folder will hold the artifacts of the build.


Again, the purpose of putting all these libraries and frameworks under source control is to make EVERITHING needed to build and run your project available. Any new developer getting into your team should then be able to checkout your code and build it successfully, without needing to download and/or install anything from the Internet or hunt down any other dependencies your project builds upon.

If you need further info, I would recommend you to watch this screencast by Kyle "Dissociative identity disorder" Baley.