Category Archives: Programming

Decimal, hexadecimal, octal characters and their usage in HTML, CSS and JavaScript

Character encoding is a lot like regular expressions. Every time I need to know how it works, I have to learn it all over again. The real reason for this post is to provide a cheat sheet for those times, but first I’ll give you the skinny on character encoding.

Consider the quotation mark character (“). There are many ways this character can be represented on a computer. Ultimately, like any character, the quotation mark boils down to a series of zeros and ones that can be understood by the various electronic doodads connected to your motherboard. To those doodads, the quotation mark is simply 100010.

How would you like to type that every time you needed a quotation mark? Just think, if you wanted to quote Monty Python and the Holy Grail, you’d have to type:

100010 101001 1101110 1101111 1110100 1101000 1100101 1110010 100000 1110011 1101000 1110010 1110101 1100010 1100010 1100101 1110010 1111001 100001 100010

Every binary number has an equivalent decimal number as well as a hexadecimal number and an octal number. The binary number 100010 is equal to the decimal number 34. It’s also equal to the hexadecimal number 22 and the octal number 42. Don’t think about it too hard, just take my word for it:

100010 = 34 decimal = 22 hexadecimal = 42 octal

This makes it much easier to quote Monty Python, but it’s still kinda cryptic and painful to type it in decimal:

34 41 110 111 116 104 101 114 32 115 104 114 117 98 98 101 114 121 33 34

Fortunately for you (and especially for me, since I quote Monty Python a lot), there are layers and layers of software that run on top of the hardware in your computer that can translate for you. So you almost never have to type anything in binary or decimal anymore. These days, you will almost always be working with a character set, which maps each of those zeros and ones to their respective glyphs to make them easier to use. You can think of a character set like this:

" -> 100010
A -> 101001
n -> 1101110
o -> 1101111
...

A Unicode character set will map those characters to hexadecimal numbers instead of binary numbers:

t -> 74
h -> 68
e -> 65
r -> 72
...

Except instead of hexadecimal numbers they are called Unicode points, and they look like this:

s -> U+0073
h -> U+0068
r -> U+0072
u -> U+0075
...

Then some other layer will take care of mapping those hexadecimal numbers to zeros and ones for the sake of the doodads we mentioned earlier.

Most character sets have a lot more characters than you can see on your keyboard. If you’ve ever needed to use one of them, you either had to punch in a super special secret code (like holding down the alt key and pressing 0 1 6 9 on the number pad for the copyright symbol), or – specifically if you are a web developer – you had to look up a magic string to use in your HTML (like ©). There are actually several ways to use these special characters in your HTML, involving their decimal, hexadecimal and octal representations. Here’s another way you can add the copyright symbol to your pages:

©

In normal fonts like Arial or Times, the decimal number 169 corresponds to the glyph for the copyright symbol. You can also use the hexadecimal number A9 pretty much the same way but with the letter x in front of it:

©

Or you can use the hexadecimal number in your stylesheet instead. This is the approach taken by Dave Gandy when he created Font Awesome:

<style>
  .copy:after {
    content: '\00A9';
  }
</style>
<span class="copy"></span>

Finally, you can use the octal number in your JavaScript:

<script>document.write('\251');</script>

The reason I needed to do this (and you might find it useful too) was so I could see all the characters a font contained. I couldn’t use the Character Map utility in Windows because it didn’t allow me to adjust the font size, and I didn’t want to spend all day looking for a replacement. I found it much easier to simply print all the characters to a page using some JavaScript:

<script>
    var i;
    
    for (i = 0; i < 2048; i++) {
        document.write('&#' + i + '<br/>');
    }
</script>
Advertisements

A beginner’s Visual C++ tutorial

A friend of mine who just started learning C++ ran into a build error on his first program, which looks likes this:

#include <iostream>

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    return 0;
}

This is the type of program you’d expect to see in just about any beginner’s C++ tutorial. What they usually don’t tell you is that this program won’t work in Microsoft Visual C++ without some additional configuration.

Visual C++ displays the full error message in the Output pane (bottom)

Visual C++ displays the full error message in the Output pane (bottom)

You can see the full error message in the Output pane, which is normally docked at the bottom of the window. Here is the rest of the message:

1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1>  ConsoleApplication1.cpp
1>e:\code\visual c++ projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(1): warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1>          Add directive to 'StdAfx.h' or rebuild precompiled header
1>e:\code\visual c++ projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(10): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Right away, there’s a problem with line 1. We know this because the line number is shown in parentheses after the filename in the Output pane. This is followed by the warning code, which is C4627, and the rest of the warning message. Visual C++ is pretty clear about what the problem is, but if you’re completely new to programming or to C++ then these words probably don’t mean much to you.

Beginners often get flak in programming circles for not reading or understanding error messages – in this case, a search for warning c4627 would get you pretty far – but I think this is a bit unfair. We don’t normally expect anyone to read, much less understand, something in another language. There’s a lot of vocabulary here for a beginner to learn. So let’s break this error message down, starting with:

'#include <iostream>' skipped when looking for precompiled header use

Basically, the compiler didn’t bother to include the file we asked it to (it skipped it). What’s a “precompiled header?” It’s just another C++ file that has some code that we need in it, plus it’s already been compiled. We don’t need to compile it again because it is not going to change. (i.e., iostream will probably never be updated.)

Add directive to 'StdAfx.h' or rebuild precompiled header

A “directive” is an instruction we can give to the compiler. In our program, #include <iostream> instructs the compiler to look in the iostream header file for things like cout. We could add another directive like this to stdafx.h, another header file which is included in our project under “Header Files” in the Solution Explorer pane.

(By the way, are we having fun yet? Get used to debugging errors if you want to become a programmer. i.e. don’t get discouraged. At least 50% of my time at work is spent debugging errors.)

Visual C++ reports not one but two problems with our code. The second error message comes from line 10, error code C1010:

unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?

Here, the compiler is telling us it kept looking for our precompiled header ’til it hit the end of the file. It never found it, but it thinks it could be in stdafx.h. Unless you’ve been reading ahead, it won’t find it there either. It doesn’t know either way because we never told it to look there. i.e., we didn’t #include "stdafx.h" at the beginning of our file.

Want to know something freaky? Our program compiles without a hitch in Code::Blocks.

This is because new projects in Visual C++ are configured to use precompiled headers, but not in Code::Blocks. That tutorial we got our code from probably assumed we weren’t using Microsoft tools but standard tools like GNU Make. In fact, Code::Blocks normally comes with a version of GNU specifically for Windows called MinGW (Minimalist GNU for Windows). That solves that mystery.

But how do we fix our program? I’ll tell you how to change your project’s configuration to get up and running quickly, but I’ll also tell you how to take advantage of precompiled headers if you want to do things the Visual C++ way.

First, if you want Visual C++ to behave like Code::Blocks, right click on your project in the Solution Explorer pane and go to Properties:

The project's context menu as seen in the Solution Explorer pane.

The project’s context menu as seen in the Solution Explorer pane.

On the left side of the properties window, drill down to Configuration Properties > C/C++ > Precompiled Headers. Change the first option, simply named Precompiled Header, from “Use (/Yu)” to “Not Using Precompiled Headers,” then click OK.

We don't need no stinking precompiled headers... except for when we do.

We don’t need no stinking precompiled headers… except for when we do.

Now you can run your program!

If you want to use precompiled headers instead, simply change the first line of your program:

#include "stdafx.h"

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    return 0;
}

Then add the missing directive to stdafx.h:

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <iostream>

Now, run your program and celebrate. You are a programmer.

Did you see the console window appear for a brief second and then disappear? Typically, console programs do their thing and then close immediately. You can tell your program to pause and wait by adding a call to system("pause") before the line return 0:

#include "stdafx.h"

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    system("pause");
    return 0;
}

That way you’ll have time to admire your beautiful program before closing it.

For extra credit, modify your program to print something awesome to the console.

For extra credit, modify your program to print something awesome to the console.

Updated NHibernate articles

It wouldn’t surprise me if nobody noticed, but I overhauled my NHibernate articles. They are now grouped together in one convenient location.

Maybe when I have time, I will write about all the things I was doing wrong and how I fixed them.

How to set up Console2 to use bash

If you prefer to use bash over cmd, you can set up a bash tab in Console2 by going to Edit > Settings > Tabs, clicking the Add button, and setting the shell option to the location of your bash executable followed by the -l parameter (or –login). You can set the title to whatever you like, change the background color, etc.

Now, if you added the Console2 context menu entries that I described in my previous post, you might also like to change into the current directory when you invoke it from the context menu. Depending on what version of bash you have, you might need to put the following at the end of your .bashrc file in your home directory:

# Change to current directory when invoking from Windows Explorer context menu
cd -

I found that this step was not necessary if I used the version of bash that comes with Git (located at C:\Program Files (x86)\Git\bin\bash.exe on my system). However, it was necessary if I used the version that comes with cygwin (C:\cygwin\bin\bash.exe). Using the latter, the home directory used by bash was actually located at C:\cygwin\home\dave. This will (obviously) be different on your system.

EDIT 4/14/2015: It appears that Console2 is currently dormant. One alternative I’ve found is ConsoleZ, which is a fork of Console2. You can find it here: https://github.com/cbucher/console.

Then, use this script to create context menu entries:

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\directory\shell\ConsoleZ]
@="Open ConsoleZ here"
[HKEY_CURRENT_USER\Software\Classes\directory\shell\ConsoleZ\command]
@="C:\\Users\\Dave\\AppData\\Local\\ConsoleZ\\Console.exe -d \"%V\""
[HKEY_CURRENT_USER\Software\Classes\directory\background\shell\ConsoleZ]
@="Open ConsoleZ here"
[HKEY_CURRENT_USER\Software\Classes\directory\background\shell\ConsoleZ\command]
@="C:\\Users\\Dave\\AppData\\Local\\ConsoleZ\\Console.exe -d \"%V\""

Update the path as appropriate.

Fluent NHibernate, auto mappings, ASP.NET MVC 3, Castle Windsor, and NUnit… and Moq

I’m going for a record: internet’s longest blog post title. FNHAMASPDNMVC3CWNUM is the official acronym of this post.

This is the fourth article in a series on using Fluent NHibernate with auto mappings. This time, I will cover unit testing with NUnit and Moq. If you haven’t already, you might want to catch up:

  1. How to use Fluent NHibernate with auto mappings
  2. Fluent NHibernate, auto mappings and ASP.NET MVC 3
  3. Fluent NHibernate, auto mappings, ASP.NET MVC 3, and Castle Windsor

You may be asking yourself, “What is unit testing and why would I want to do it?” If that’s the case, then you should read my previous article: What is unit testing? Dependency injection?

Here’s what the completed project will look like:

If you don’t see the solution at the top of the Solution Explorer, go to the Tools menu > Options. In the Options window, ensure “Show all settings” is checked, then go to Projects and Solutions on the left and check “Always show solution” on the right:

This time, you don’t need to create a new ASP.NET MVC 3 web application. Instead, open the solution from last time, right click on the solution at the top of the Solution Explorer and choose Add > New Project…:

Choose Visual C# Class Library as the project template and name it CastleFluentNHibernateMvc3.Tests. Once the project has been added to the solution, delete the Class1 class. Next, right click on the Tests project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for NUnit and install it. Also, search for and install Moq.

Once the packages have been downloaded and installed, add a folder to the Tests project named Controllers, then add a class to the Controllers folder named HomeControllerTest. Make this class public and prepend it with the TestFixture attribute, like so:

[TestFixture]
public class HomeControllerTest { }

Finally, we’re ready to write some tests!

Remember, a unit test typically covers a single unit of code. In the case of a MVC application, that means that each action and method deserves its own unit test. Depending on the complexity, some actions and methods deserve several unit tests. Because our application is so simple, however, our unit tests will be relatively simple as well. As you can tell from the previous step, we will be writing unit tests for the actions in our home controller, starting with the Index action. For convenience, here is the code:

public ActionResult Index()
{
    storeRepository.BeginTransaction();

    var stores = storeRepository.GetAll();

    if ( stores == null || !stores.Any() )
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
    
    try
    {
        storeRepository.Commit();

        return View( stores.ToList() );
    }
    catch
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
}

We want to make sure that every time the Index action is called the store repository returns a list of stores and the action returns a view. Testing that the action returns a view is simple enough, so at first we might try something like this:

[Test]
public void Index()
{
    // Arrange
    var controller = new HomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

The first thing you’ll notice is that the Tests project requires a reference to CastleFluentNHibernateMvc3, as well as System.Web.Mvc. Once you’ve added these references, Visual Studio will display this compilation error:

'CastleFluentNHibernateMvc3.Controllers.HomeController' does not contain a constructor that takes 0 arguments

The reason we get this error is because we modified the home controller constructor last time to use dependency injection. We did this because we don’t want to use our real repository in our unit tests. Instead, we want to use a fake (or mock) repository. This is where Moq comes in handy, although it does require a little setup before we can use it. First, we need a field to store our fake repository in the HomeControllerTest class, which we need to reset after each test execution:

[TestFixture]
public class HomeControllerTest
{
    private Mock<IRepository<Store>> storeRepositoryMock;

    [SetUp]
    public void Init()
    {
        storeRepositoryMock = new Mock<IRepository<Store>>();
    }

    // ...
}

Now, we can pass this value to the home controller constructor in our unit test, exposing its mocked instance with Moq’s Object property:

[Test]
public void Index()
{
    // Arrange
    var controller = new HomeController( storeRepositoryMock.Object );

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

Eventually, we may end up with lots of injected dependencies in our home controller constructor, so I like to extract the constructor call to a separate method:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

private HomeController GetHomeController()
{
    return new HomeController( storeRepositoryMock.Object );
}

At this point, if we try running our application, we will get a nasty error. We can’t run a class library directly. There are two options for running NUnit tests:

  1. Download NUnit and run it in the console or run the GUI tool. After compiling the Tests project, load the .dll file (located in the project’s bin/Debug folder) in NUnit and run the test.
  2. Download the Visual NUnit extension for Visual Studio. Go to View > Other Windows > Visual NUnit. After compiling the Tests project, select it in Visual NUnit and run the test.

Whichever option you choose, our test should pass with flying colors! Unfortunately, there’s a problem. We’ve made sure our action returns a view, but the view it’s returning is actually the Error view. We can verify this by debugging our test. In Visual Studio, go to Debug > Attach to process… find nunit-agent.exe (if you chose option one above) or VisualNUnitRunner.exe (if you chose option two) in the list of processes and click the Attach button.

Now, we can put a breakpoint in our test and take a closer look at our result. Sure enough, the ViewName is “Error”:

We could have caught this sooner by testing that the view is getting the right model. In this case, our view should be getting a list of stores as its model. We would test for that as follows:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );

    var view = (ViewResult)result;

    Assert.IsInstanceOf<List<Store>>( view.Model );
}

If we run our test again, it should fail. NUnit will display the following error:

CastleFluentNHibernateMvc3.Tests.Controllers.HomeControllerTest.Index:
  Expected: instance of <System.Collections.Generic.List`1[CastleFluentNHibernateMvc3.Models.Store]>
  But was:  null

Let’s put a breakpoint in our home controller this time and find out what’s going on. Doing this, we can see that our store repository is not returning any stores. And why should it? Remember, it’s a fake repository! We have to tell our fake repository what to do when it’s queried for a list of stores. But before we do that, make a copy of the Index test and rename it to Index_NoStoresFound. With a little modification, this test can still be useful:

[Test]
public void Index_NoStoresFound()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
    
    var view = (ViewResult)result;

    Assert.AreEqual( "Error", view.ViewName );
}

Keeping this test will ensure that the Index action always returns the Error view when our store repository doesn’t return any stores. If this test ever fails (for instance, because the Index action returns the Index view), then something is wrong with our error handling.

Now, let’s fix our Index test. We can use Moq’s Setup method to tell Moq what to return when we ask it for a list of stores:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    var stores = new List<Store>
        {
            new Store()
        };

    storeRepositoryMock.Setup( s => s.GetAll() )
        .Returns( stores.AsQueryable() )
        .Verifiable();

    // Act
    var result = controller.Index();

    // Assert
    storeRepositoryMock.Verify();

    Assert.IsInstanceOf<ViewResult>( result );

    var view = (ViewResult)result;

    Assert.IsInstanceOf<List<Store>>( view.Model );
}

Notice that we can return any list of stores we want, so long as we convert it to an IQueryable because that’s what Moq expects to get back from the GetAll method of our store repository.

That concludes my series on using Fluent NHibernate with auto mappings. As always, let me know if you have any questions or comments. Good luck!

What is unit testing? Dependency injection?

Previously, I mentioned that dependency injection is important for unit testing. If you are unfamiliar with either of these concepts, then your eyes probably glossed over when you read that sentence. I’m sure you could find many articles that cover unit testing and dependency injection on the interwebs. However, since I try to be newbie friendly (i.e. I am a newbie), I’m going to try to explain – in layman’s terms – the basic ideas behind these concepts. This will also give me a chance to learn more by teaching, which is how I learn best.

NOTE: I won’t be discussing test-driven development here. Some beginners get unit testing and TDD confused, but TDD is a separate topic that deserves its own article at some point in the future.

Unit testing

If you’ve ever done any programming in any language, then you are already familiar with manual testing. You might call it “looking for bugs” or “checking your work,” but it all boils down to launching your software and using it. At first, manual testing is quick and easy. After creating an HTML page, for instance, you would open it in a browser to verify that it looks okay. If it doesn’t, you would have to adjust the HTML until it passes the test. If it does, you might create another page and repeat the process. After that, you would need to add links from each page to the other. Then, you would have to open each page in a browser to verify that the links on each page work.

Here’s what usually happens pretty quickly: you have several pages, each with links to several other pages. Then, without thinking through the ramifications, you change a file name. This tends to happen at the worst possible moments, like right after your pages go live. Of course, it’s possible to test every link on every page every time you make a change like that. But if you are working on a large project, it can become extremely time consuming. Wouldn’t it be nice if there was a way to test every link on every page automatically every time you make a change?

There is a way. It’s called unit testing, and – if implemented correctly – it will save you from breaking changes. The reason it’s called unit testing instead of automatic testing is because it normally involves testing a single unit of code (a method or an action) at a time. To be honest, I don’t have a clue how you would write a unit test for the above scenario – at least not if all we’re dealing with is simple HTML pages. Frameworks such as Zend for PHP and ASP.NET MVC for C# lend themselves to such cases, which is one reason why they’re so popular. Here’s how we might do it in C#:

public class MyTests
{
    public void TestLinks()
    {
        // Arrange
        var links = GetAllLinks();
        var numErrors = 0;

        // Act
        foreach (var link in links)
        {
            if (!TryLink( link ))
            {
                numErrors ++;
            }
        }

        // Assert
        Assert.AreEqual( 0, numErrors );
    }
}

Of course, the implementation of such a test will vary greatly depending on the framework. Arrange-Act-Assert is a common pattern for unit testing:

  1. Arrange: Set up any variables that will be used in the test
  2. Act: Call the method or execute the action to be tested
  3. Assert: Check that the conditions of the test were met

At the end of the TestLinks method above, we assert that the number of errors is equal to zero. If it’s not, then the test will fail, letting us know that a link is broken. Ideally, you would run this test after making any changes that could affect it. Most importantly, you would run it before committing those changes to source control.

Dependency injection

Dependency injection is often associated with unit testing because it allows you to test a unit of code by passing in a fake implementation rather than a concrete object. The most obvious case where you would want use this is to test a unit of code that needs to save data to a database.

Imagine that, on your website, a user can sign up for an account. To do this, the user must fill out and submit a form, which inserts a record into the database. This is something that needs to be tested – extensively, in fact, if you are a good developer.

If you’re using a data layer such as NHibernate or Entity Framework, you don’t need to test that the data is inserted into the database correctly. Also, you don’t want to insert a bunch of dummy data into the database. Instead, you need to test that the form is submitted, that an account is created, and that the page is redirected. If the user forgets to fill out a required field on the form, the page should be redirected to an error page, or back to the same page so the user can try again.

Now, assume your user controller has an action called NewUser that handles the form submission. In ASP.NET MVC, it might look something like this:

public class UserController : Controller
{
    [HttpPost]
    public ActionResult NewUser( User user )
    {
        // Data validation goes here
        // ...

        // Create a new instance of the repository
        var db = new Database();

        // Insert the record into the database
        db.Save( user );

        // Redirect the user to the success page
        return Redirect( Success );
    }
}

Then, our unit test might look something like this:

public void TestNewUser()
{
    // Arrange
    var controller = new UserController();
    var user = new User
    {
        FirstName = "Dave",
        LastName = "Ryder",
        UserName = "BigMcLargeHuge1",
        Password = "12345"
    };

    // Act
    var result = controller.NewUser( user );

    // Assert
    Assert.AreEqual( "Success", result.RouteData["Action"] );
}

Running that test would insert the dummy data into the database, but we’re not interested in that part. What we’d rather do is skip that part and just test that the page is redirected to the right action. To do that, we need to pass a fake database to the home controller:

public void TestNewUser()
{
    // Arrange
    var controller = new UserController( new Fake<Database>() );
    var user = new User
    {
        FirstName = "Dave",
        LastName = "Ryder",
        UserName = "BigMcLargeHuge1",
        Password = "12345"
    };

    // Act
    var result = controller.NewUser( user );

    // Assert
    Assert.AreEqual( "Success", result.RouteData["Action"] );
}

Then, we would need to modify the constructor of our user controller to accept a parameter for the repository. In other words, we need to inject our dependency into the constructor. We also remove the instantiation of the database class from the NewUser action:

public class UserController : Controller
{
    private readonly Database db;

    public UserController( Database db )
    {
        this.db = db;
    }

    [HttpPost]
    public ActionResult NewUser( User user )
    {
        // Data validation goes here
        // ...

        // Insert the record into the database
        db.Save( user );

        // Redirect the user to the success page
        return Redirect( Success );
    }
}

Instead of saving the data, our fake implementation of the database class just pretends to save the data so we can go on testing the parts we care about.

Conclusion

Hopefully, now you get the basic ideas behind unit testing and dependency injection. As I mentioned before, my next article will cover using NUnit and Moq for unit testing an ASP.NET MVC 3 application with NHibernate and Castle Windsor already implemented.

Fluent NHibernate, auto mappings, ASP.NET MVC 3, and Castle Windsor

The title of this article is so long, I briefly considered using an acronym. Unfortunately, FNHAMASPDNMVC3CW doesn’t communicate much except to the nerdiest of nerds.

This is the third article in a series on using Fluent NHibernate with auto mappings. The first one demonstrated its basic functionality in a console application, and the second one showed how to convert the first one into an ASP.NET MVC 3 application. This article will cover how to use Castle Windsor for dependency injection, which is important for unit testing. I won’t include any unit tests in this article, but will lay the foundation that will make unit testing possible for my next article.

Much of the code below is directly from the Castle Windsor documentation, which really is exceptional.

Here’s what the completed project will look like:

Once again, create a new ASP.NET MVC 3 web application in Microsoft Visual Studio 2010 and use the empty project template. This time, call your project CastleFluentNHibernateMvc3. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it. We also need Castle Windsor, so search for that and install it too.

EDIT 12/18/2012: You can get the source code on GitHub.

Once you’ve installed the packages, copy the Controllers, Models and Repositories folders from our previous project to our new project. Also, copy the Views/Home folder to our new project. Make sure you change the namespace in each file accordingly.

The first thing we need is a Windsor controller factory. The Windsor controller factory overrides two methods of the default MVC controller factory and is central to how Castle Windsor resolves controller dependencies. Create this class in a new Windsor directory at the root level of the project:

namespace CastleFluentNHibernateMvc3.Windsor
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory( IKernel kernel )
        {
            this.kernel = kernel;
        }

        public override void ReleaseController( IController controller )
        {
            kernel.ReleaseComponent( controller );
        }

        protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType )
        {
            if (controllerType == null)
            {
                throw new HttpException( 404, string.Format( "The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path ) );
            }

            return (IController)kernel.Resolve( controllerType );
        }
    }
}

Next, we need to tell MVC to use the Windsor controller factory instead of the default one. To do that, we’ll add a couple of methods to the MvcApplication class, which resides in the Global.asax.cs file at the root of the project:

namespace CastleFluentNHibernateMvc3
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static IWindsorContainer container;

        private static void BootstrapContainer()
        {
            container = new WindsorContainer()
                .Install( FromAssembly.This() );

            var controllerFactory = new WindsorControllerFactory( container.Kernel );

            ControllerBuilder.Current.SetControllerFactory( controllerFactory );
        }

        // RegisterGlobalFilters and RegisterRoutes methods go here...

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters( GlobalFilters.Filters );
            RegisterRoutes( RouteTable.Routes );

            BootstrapContainer();
        }

        protected void Application_End()
        {
            container.Dispose();
        }
    }
}

Now, we need to tell Windsor about our controllers, including where they reside and how to configure them. In other words, we’ll “register” our controllers with the Windsor “container.” We do this using an “installer.” Create this class in your Windsor directory:

namespace CastleFluentNHibernateMvc3.Windsor
{
    public class ControllersInstaller : IWindsorInstaller
    {
        public void Install( IWindsorContainer container, IConfigurationStore store )
        {
            container.Register( Classes.FromThisAssembly()
                                .BasedOn<IController>()
                                .LifestyleTransient() );
        }
    }
}

Next, create a new class named PersistenceFacility in your Windsor directory, and move the CreateSessionFactory, CreateDbConfig, CreateMappings and UpdateSchema methods of our NHibernateSessionPerRequest class there:

namespace CastleFluentNHibernateMvc3.Windsor
{
    public class PersistenceFacility : AbstractFacility
    {
        protected override void Init()
        {
            Kernel.Register(
                Component.For<ISessionFactory>()
                    .UsingFactoryMethod( CreateSessionFactory ),
                Component.For<ISession>()
                    .UsingFactoryMethod( OpenSession )
                    .LifestylePerWebRequest() );
        }

        private static ISession OpenSession( IKernel kernel )
        {
            return kernel.Resolve<ISessionFactory>().OpenSession();
        }

        // CreateSessionFactory, CreateDbConfig, CreateMappings and UpdateSchema methods go here...
    }
}

In the Init method, we’re telling Castle Windsor what to do when it encounters a dependency on ISessionFactory or ISession. If we ask for an ISession, it will resolve the dependency using the OpenSession method. Notice that this method needs an ISessionFactory, which Castle Windsor will resolve by calling CreateSessionFactory.

We’re also telling Castle Windsor that an ISession instance should be bound to a web request. Since we aren’t specifying a lifestyle for ISessionFactory, the default value of singleton will be used. In other words, only one session factory will be instantiated during the lifetime of our app, and it will hang around in memory until our app dies. This is basically the same thing we did before with our custom HTTP module, except the dependencies will only be resolved when needed. We can verify this by placing breakpoints in the OpenSession and CreateSessionFactory methods and running the app.

Now, we need to register our persistence facility with the Windsor container. Again, we do this using an installer. Create this class in your Windsor directory:

namespace CastleFluentNHibernateMvc3.Windsor
{
    public class PersistenceInstaller : IWindsorInstaller
    {
        public void Install( IWindsorContainer container, IConfigurationStore store )
        {
            container.AddFacility<PersistenceFacility>();
        }
    }
}

Next, we need to add a few more methods to our repository in order to manage NHibernate transactions: BeginTransaction, Commit and Rollback. Previously, we created a custom HTTP module to take care of these operations at the beginning and end of each web request. This time, we’ll manage each transaction ourselves, gaining more control and performance in the process. The GetAll, Get, SaveOrUpdateAll and SaveOrUpdate methods will stay the same:

namespace CastleFluentNHibernateMvc3.Repositories
{
    public interface IRepository<T>
    {
        void BeginTransaction();
        void Commit();
        void Rollback();
        // GetAll, Get, SaveOrUpdateAll and SaveOrUpdate signatures go here...
    }
}
namespace CastleFluentNHibernateMvc3.Repositories
{
    public class Repository<T> : IRepository<T>
    {
        private readonly ISession session;

        public Repository( ISession session )
        {
            this.session = session;
        }

        public void BeginTransaction()
        {
            session.BeginTransaction();
        }

        public void Commit()
        {
            session.Transaction.Commit();
        }

        public void Rollback()
        {
            session.Transaction.Rollback();
        }

        // GetAll, Get, SaveOrUpdateAll and SaveOrUpdate implementations go here...
    }
}

Notice that the repository constructor has been modified to accept an argument of type ISession. This is called dependency injection, and its benefits will become more clear when we use it in our home controller.

But first, we need to register our repositories with the Windsor container. How do we do that? Right! (You did say “use an installer,” right? Good.) Create this class in your Windsor directory:

namespace CastleFluentNHibernateMvc3.Windsor
{
    public class RepositoriesInstaller : IWindsorInstaller
    {
        public void Install( IWindsorContainer container, IConfigurationStore store )
        {
            container.Register( Classes.FromThisAssembly()
                                .Where( Component.IsInSameNamespaceAs<Repository<Store>>() )
                                .WithService.DefaultInterfaces()
                                .LifestyleTransient() );
        }
    }
}

Now, modify the home controller constructor as follows:

// Constructs our home controller
public HomeController( IRepository<Store> storeRepository )
{
    this.storeRepository = storeRepository;
}

The benefit of using dependency injection here is that we no longer have a dependency on a concrete repository. The home controller doesn’t care what the repository does with our data, as long as it implements IRepository. This way, we can change our repository methods without changing our controller actions. Later, when we write unit tests for our controller actions, we’ll be able to create an instance of the home controller using a fake repository so that our tests don’t touch our data.

Because we are no longer using a custom HTTP module to manage NHibernate transactions, we need to call the BeginTransaction method of our repository whenever we get data from or save data to the database. We also need to call the Commit method to flush the NHibernate session, and call the Rollback method if any errors occur:

// Gets all the stores from our database and returns a view that displays them
public ActionResult Index()
{
    storeRepository.BeginTransaction();

    var stores = storeRepository.GetAll();

    if ( stores == null || !stores.Any() )
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
    
    try
    {
        storeRepository.Commit();

        return View( stores.ToList() );
    }
    catch
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
}

// Gets and modifies a single store from our database
public ActionResult Test()
{
    storeRepository.BeginTransaction();

    var barginBasin = storeRepository.Get( s => s.Name == "Bargin Basin" ).SingleOrDefault();

    if (barginBasin == null)
    {
        storeRepository.Rollback();

        return View( "Error" );
    }

    try
    {
        barginBasin.Name = "Bargain Basin";
    
        storeRepository.Commit();

        return RedirectToAction( "Index" );
    }
    catch
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
}

// Adds sample data to our database
public ActionResult Seed()
{
    // Create a couple of Stores each with some Products and Employees
    var barginBasin = new Store { Name = "Bargin Basin" };
    var superMart = new Store { Name = "SuperMart" };

    var potatoes = new Product { Name = "Potatoes", Price = 3.60 };
    var fish = new Product { Name = "Fish", Price = 4.49 };
    var milk = new Product { Name = "Milk", Price = 0.79 };
    var bread = new Product { Name = "Bread", Price = 1.29 };
    var cheese = new Product { Name = "Cheese", Price = 2.10 };
    var waffles = new Product { Name = "Waffles", Price = 2.41 };

    var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" };
    var jack = new Employee { FirstName = "Jack", LastName = "Torrance" };
    var sue = new Employee { FirstName = "Sue", LastName = "Walkters" };
    var bill = new Employee { FirstName = "Bill", LastName = "Taft" };
    var joan = new Employee { FirstName = "Joan", LastName = "Pope" };

    // Add Products to the Stores
    // The Store-Product relationship is many-to-many
    AddProductsToStore( barginBasin, potatoes, fish, milk, bread, cheese );
    AddProductsToStore( superMart, bread, cheese, waffles );

    // Add Employees to the Stores
    // The Store-Employee relationship is one-to-many
    AddEmployeesToStore( barginBasin, daisy, jack, sue );
    AddEmployeesToStore( superMart, bill, joan );
    
    storeRepository.BeginTransaction();

    try
    {
        storeRepository.SaveOrUpdateAll( barginBasin, superMart );
    
        storeRepository.Commit();

        return RedirectToAction( "Index" );
    }
    catch
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
}

You can now run your application. If you get any errors, make sure you have an empty database and a valid connection string. In that case, see my previous article for instructions on setting that up. If all you see is the word “Index,” it’s because you don’t have any data in your database yet. In your browser, navigate to the Seed action of the home controller. You should then see “Index” at the top followed by a list of stores, products and employees.

Next time, we’ll look as using NUnit and Moq for unit testing. Surprisingly, it’s relatively easy! As always, let me know if you have any difficulties. Good luck!

How to add “Open with Git Bash” and “Open with Git GUI” context menu entries in Windows

This is a just a small distraction. I’m sort of a clean freak when it comes to Windows, so I usually opt not to install things like context menu entries when I’m trying a new program. Unfortunately, I opted not to install them for Git and realized later that I really wanted them. There doesn’t seem to be a way to correct this post-installation, so I did some research and figured out a little registry hack to accomplish the same thing:

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\OpenWithGitBash]
@="Open with Git Bash"
[HKEY_CLASSES_ROOT\Directory\shell\OpenWithGitBash\command]
@="\"wscript\" \"C:\\Program Files (x86)\\Git\\Git Bash.vbs\" \"%1\""
[HKEY_CLASSES_ROOT\Directory\shell\OpenWithGitGUI]
@="Open with Git GUI"
[HKEY_CLASSES_ROOT\Directory\shell\OpenWithGitGUI\command]
@="\"C:\\Program Files (x86)\\Git\\bin\\wish.exe\" \"C:\\Program Files (x86)\\Git\\libexec\\git-core\\git-gui\" \"--working-dir\" \"%1\""

Now, I can right click on a folder with a Git repository in it and open it instantly in Git Bash or Git GUI. Joy!

If you want to copy and paste the text above into a .reg file, make sure the encoding is set to UCS-2 Little Endian before you try to import it into the registry.

Fluent NHibernate, auto mappings and ASP.NET MVC 3

In my previous article, I demonstrated how to use Fluent NHibernate with auto mappings. After that, my plan was to move the code into an ASP.NET MVC 3 application. I assumed it would be relatively simple, which goes to show just how little I know about these things. Anyways, hopefully someone else out there will be able to learn from my experience.

Here’s what the completed project will look like:

Create a new ASP.NET MVC 3 web application called FluentNHibernateMvc3 in Microsoft Visual Studio 2010 and use the empty project template. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it.

EDIT 12/18/2012: You can get the source code on GitHub.

Once you’ve installed Fluent NHibernate, copy the Employee, Product and Store classes from the Entities folder of our previous project to the Models folder of our current project. Make sure you change the namespace in each file accordingly.

Next, create a new controller called HomeController in the Controllers folder. Since my goal is to move the code from our previous project to our new project with as little changes as possible, the HomeController class will look very similar to the Program class with the following exceptions:

  1. We’ll move the NHibernate specific methods to a new custom HTTP module.
  2. We’ll use a repository to create a layer of abstraction between our main application and our persistence layer.
  3. We’ll split the Main method into two actions: the Index action, which will display the data, and the Seed action, which will add sample data to our database. This is because we don’t want to add sample data every time our application runs.

Here’s a rough skeleton of the home controller:

namespace FluentNHibernateMvc3.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRepository<Store> storeRepository;
        
        // Constructs our home controller
        public HomeController() { }
        
        // Gets all the stores from our database and returns a view that displays them
        public ActionResult Index() { }
        
        // Adds sample data to our database
        public ActionResult Seed() { }
        
        // AddProductsToStore and AddEmployeesToStore methods go here...
    }
}

The first thing you should notice is that the home controller has a field called storeRepository, which implements an IRepository of type Store. This needs to be set in the constructor method:

// Constructs our home controller
public HomeController()
{
    storeRepository = new Repository<Store>();
}

We’ll create the Repository class and IRepository interface later.

Next, we’ll move the bulk of the Main method from our previous project to the Seed action here:

// Adds sample data to our database
public ActionResult Seed()
{
    // Create a couple of Stores each with some Products and Employees
    var barginBasin = new Store { Name = "Bargin Basin" };
    var superMart = new Store { Name = "SuperMart" };

    var potatoes = new Product { Name = "Potatoes", Price = 3.60 };
    var fish = new Product { Name = "Fish", Price = 4.49 };
    var milk = new Product { Name = "Milk", Price = 0.79 };
    var bread = new Product { Name = "Bread", Price = 1.29 };
    var cheese = new Product { Name = "Cheese", Price = 2.10 };
    var waffles = new Product { Name = "Waffles", Price = 2.41 };

    var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" };
    var jack = new Employee { FirstName = "Jack", LastName = "Torrance" };
    var sue = new Employee { FirstName = "Sue", LastName = "Walkters" };
    var bill = new Employee { FirstName = "Bill", LastName = "Taft" };
    var joan = new Employee { FirstName = "Joan", LastName = "Pope" };

    // Add Products to the Stores
    // The Store-Product relationship is many-to-many
    AddProductsToStore( barginBasin, potatoes, fish, milk, bread, cheese );
    AddProductsToStore( superMart, bread, cheese, waffles );

    // Add Employees to the Stores
    // The Store-Employee relationship is one-to-many
    AddEmployeesToStore( barginBasin, daisy, jack, sue );
    AddEmployeesToStore( superMart, bill, joan );

    storeRepository.SaveOrUpdateAll( barginBasin, superMart );

    return RedirectToAction( "Index" );
}

There are a few important changes you should notice:

  1. We don’t create a new session factory in the Seed action, or anywhere else in the home controller for that matter.
  2. We don’t open a session here.
  3. We don’t create or commit a transaction.

These tasks will be handled by our custom HTTP module at the beginning and end of each web request. Separating these tasks allows us to minimize the dependencies in our home controller, which is often referred to as loose coupling. Our controller doesn’t know anything about sessions or transactions – it isn’t even aware of NHibernate!

The Index action is very simple:

// Gets all the stores from our database and returns a view that displays them
public ActionResult Index()
{
    var stores = storeRepository.GetAll();

    return View( stores.ToList() );
}

Here, we call the GetAll method of our repository, cast the result to a list and send the list to the view. The Index view should go in your Views/Home folder and should look like this:

@model List<FluentNHibernateMvc3.Models.Store>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<ul>
    @foreach ( var store in Model ) {
        <li>@store.Name</li>
        <ul>
            <li>Products:</li>
            <ul>
                @foreach ( var product in store.Products ) {
                    <li>@product.Name</li>
                }
            </ul>
            <li>Staff:</li>
            <ul>
                @foreach ( var employee in store.Staff ) {
                    <li>@employee.FirstName @employee.LastName</li>
                }
            </ul>
        </ul>
    }
</ul>

Now, let’s tackle that repository. Place these files in a new folder called Repositories at the root level of the project. This is where we’ll define what exactly the GetAll and SaveOrUpdateAll methods do that we’re using in our controller actions. First, create the interface:

namespace FluentNHibernateMvc3.Repositories
{
    public interface IRepository<T>
    {
        IQueryable<T> GetAll();
        IQueryable<T> Get( Expression<Func<T, bool>> predicate );
        IEnumerable<T> SaveOrUpdateAll( params T[] entities );
        T SaveOrUpdate( T entity );
    }
}

Then create the implementation:

namespace FluentNHibernateMvc3.Repositories
{
    public class Repository<T> : IRepository<T>
    {
        private readonly ISession session;

        public Repository()
        {
            session = NHibernateSessionPerRequest.GetCurrentSession();
        }

        public IQueryable<T> GetAll()
        {
            return session.Query<T>();
        }

        public IQueryable<T> Get( Expression<Func<T, bool>> predicate )
        {
            return GetAll().Where( predicate );
        }

        public IEnumerable<T> SaveOrUpdateAll( params T[] entities )
        {
            foreach ( var entity in entities )
            {
                session.SaveOrUpdate( entity );
            }

            return entities;
        }

        public T SaveOrUpdate( T entity )
        {
            session.SaveOrUpdate( entity );

            return entity;
        }
    }
}

Speaking of loose coupling, our repository doesn’t know anything about session factories or transactions, but it does have a session field that implements ISession. This field is set by calling the GetCurrentSession method of our custom HTTP module, which we’ll name NHibernateSessionPerRequest.

Here’s an outline of the NHibernateSessionPerRequest class, which you can put in a new Modules folder at the root level of the project:

namespace FluentNHibernateMvc3.Modules
{
    /// 
    /// http://www.bengtbe.com/blog/2009/10/08/nerddinner-with-fluent-nhibernate-part-3-the-infrastructure
    /// 
    public class NHibernateSessionPerRequest : IHttpModule
    {
        private static readonly ISessionFactory sessionFactory;

        // Constructs our HTTP module
        static NHibernateSessionPerRequest() { }
        
        // Initializes the HTTP module
        public void Init( HttpApplication context ) { }

        // Disposes the HTTP module
        public void Dispose() { }

        // Returns the current session
        public static ISession GetCurrentSession() { }

        // Opens the session, begins the transaction, and binds the session
        private static void BeginRequest( object sender, EventArgs e ) { }

        // Unbinds the session, commits the transaction, and closes the session
        private static void EndRequest( object sender, EventArgs e ) { }

        // Returns our session factory
        private static ISessionFactory CreateSessionFactory() { }

        // Returns our database configuration
        private static MsSqlConfiguration CreateDbConfig()

        // Returns our mappings
        private static AutoPersistenceModel CreateMappings()

        // Updates the database schema if there are any changes to the model,
        // or drops and creates it if it doesn't exist
        private static void UpdateSchema( Configuration cfg ) { }
    }
}

Notice that the sessionFactory field, which implements ISessionFactory, is static. Session factories can be expensive to create, especially with a large domain model. So we only want to instantiate one of these during the lifetime of our app, which will hang around in memory until our app dies:

// Constructs our HTTP module
static NHibernateSessionPerRequest()
{
    sessionFactory = CreateSessionFactory();
}

// Returns our session factory
private static ISessionFactory CreateSessionFactory()
{
    return Fluently.Configure()
        .Database( CreateDbConfig )
        .Mappings( m => m.AutoMappings.Add( CreateMappings() ) )
        .ExposeConfiguration( UpdateSchema )
        .CurrentSessionContext<WebSessionContext>()
        .BuildSessionFactory();
}

// Returns our database configuration
private static MsSqlConfiguration CreateDbConfig()
{
    return MsSqlConfiguration
        .MsSql2008
        .ConnectionString( c => c.FromConnectionStringWithKey( "testConn" ) );
}

// Returns our mappings
private static AutoPersistenceModel CreateMappings()
{
    return AutoMap
        .Assembly( System.Reflection.Assembly.GetCallingAssembly() )
        .Where( t => t.Namespace != null && t.Namespace.EndsWith( "Models" ) )
        .Conventions.Setup( c => c.Add( DefaultCascade.SaveUpdate() ) );
}

// Updates the database schema if there are any changes to the model,
// or drops and creates it if it doesn't exist
private static void UpdateSchema( Configuration cfg )
{
    new SchemaUpdate( cfg )
        .Execute( false, true );
}

Most of these methods can be copied to this class from our previous project. There are only a few changes:

  1. We’ve replaced the DropCreateSchema method with a new method called UpdateSchema. As the name suggests, this method will only create the database schema if it doesn’t already exist. Otherwise, it will update it from the model.
  2. NHibernate needs to be told what type of context it’s running in. We do that by calling the CurrentSessionContext extension method in our fluent configuration. It’s strongly typed, so we give it a type of WebSessionContext.
  3. Instead of building a connection string in the CreateDbConfig method, I’m using a connection string from the Web.config file. You can do it either way.
  4. The CreateMappings method will create auto mappings for all types in our assembly that have a namespace ending in “Models”. This is preferable over matching the entire namespace, since it will require less changes moving forward.

Here are the remaining methods:

// Initializes the HTTP module
public void Init( HttpApplication context )
{
    context.BeginRequest += BeginRequest;
    context.EndRequest += EndRequest;
}

// Disposes the HTTP module
public void Dispose() { }

// Returns the current session
public static ISession GetCurrentSession()
{
    return sessionFactory.GetCurrentSession();
}

// Opens the session, begins the transaction, and binds the session
private static void BeginRequest( object sender, EventArgs e )
{
    ISession session = sessionFactory.OpenSession();

    session.BeginTransaction();

    CurrentSessionContext.Bind( session );
}

// Unbinds the session, commits the transaction, and closes the session
private static void EndRequest( object sender, EventArgs e )
{
    ISession session = CurrentSessionContext.Unbind( sessionFactory );

    if ( session == null ) return;

    try
    {
        session.Transaction.Commit();
    }
    catch ( Exception )
    {
        session.Transaction.Rollback();
    }
    finally
    {
        session.Close();
        session.Dispose();
    }
}

Previously, we weren’t catching any exceptions when we tried to commit our transaction. Wrapping our call to commit in a try-catch statement gives us a chance to rollback if something goes wrong.

We’re almost done! We still need to register our custom HTTP module in IIS, so that it can receive and process HTTP requests. If you are using IIS 6.0 or IIS 7.0 in classic mode, add this to your Web.config file:

<configuration>
  <system.web>
    <httpModules>
      <add name="NHibernateSessionPerRequest" type="FluentNHibernateMvc3.Modules.NHibernateSessionPerRequest" />
     </httpModules>
  </system.web>
</configuration>

If you are using IIS 7.0 in integrated mode, add this to your Web.config file:

<configuration>
  <system.webServer>
    <modules>
      <add name="NHibernateSessionPerRequest" type="FluentNHibernateMvc3.Modules.NHibernateSessionPerRequest" />
    </modules>
  </system.webServer>
</configuration>

Finally, if you decided not to build a connection string in the CreateDbConfig method, you’ll need to add one under the configuration section of your Web.config file. Here’s mine, which is using SQL Server 2008:

<connectionStrings>
  <add name="testConn" connectionString="Server=testServer;Database=testDB;User ID=testUser;Password=testPass" providerName="System.Data.SqlClient" />
</connectionStrings>

Before running the application, make sure you create an empty database, and replace “testServer”, “testDB”, “testUser” and “testPass” with your actual server, database, username, and password.

When you run the application, you should see this:

Index

Not very exciting, it is? That’s because we haven’t added any data to the database yet! In your browser, navigate to the Seed action of the home controller, i.e. append /Home/Seed to the URL in your browser’s address bar. You should see this:

Index

  • Bargin Basin
    • Products:
      • Potatoes
      • Fish
      • Milk
      • Bread
      • Cheese
    • Staff:
      • Daisy Harrison
      • Jack Torrance
      • Sue Walkters
  • SuperMart
    • Products:
      • Bread
      • Cheese
      • Waffles
    • Staff:
      • Bill Taft
      • Joan Pope

Look familiar? It should if you read my previous article.

I’d like to demonstrate one more thing before I sign off. Add the following action to the home controller:

// Gets and modifies a single store from our database
public ActionResult Test()
{
    var barginBasin = storeRepository.Get( s => s.Name == "Bargin Basin" ).SingleOrDefault();

    if ( barginBasin == null )
    {
        return RedirectToAction( "Index" );
    }

    barginBasin.Name = "Bargain Basin";

    return RedirectToAction( "Index" );
}

This action is fairly self-explanatory: It will find the Store record named “Bargin Basin” and rename it to “Bargain Basin.” The cool part is that we don’t have to manually save anything because it’s all taken care of by our repository and HTTP module! Navigate to the Test action of the home controller in your browser and you’ll see what I mean.

That does it for this article. Next time, I’ll cover unit testing and dependency injecting using Castle Windsor.

How to use Fluent NHibernate with auto mappings

For this article, I’ll be modifying “Your First Project” found on the Fluent NHibernate Wiki: Getting Started page. I’ll also borrow a couple of ideas from FlashM’s article on Dream.In.Code. The idea is to take advantage of the auto mappings feature of Fluent NHibernate, which is not documented very well, even though it’s arguably its strongest selling point.

Here’s what the completed project will look like:

To begin, create a new console application called FluentNHibernateConsole in Microsoft Visual Studio 2010. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it.

EDIT 12/18/2012: I finally managed to get the source code on GitHub!

Next, create a new folder in your project and name it Entities. Place the following classes in your Entities folder:

namespace FluentNHibernateConsole.Entities
{
    public class Employee
    {
        public virtual int Id { get; protected set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual Store Store { get; set; }
    }
}

Before Fluent NHibernate version 1.3.0.717, we could make the setter function of the Id property private instead of protected. The reason it needs to be one or the other is because it should never be changed by the code. Instead, it should only ever be touched by NHibernate.

namespace FluentNHibernateConsole.Entities
{
    public class Product
    {
        public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
        public virtual double Price { get; set; }
        public virtual IList<Store> StoresStockedIn { get; protected set; }

        public Product()
        {
            StoresStockedIn = new List<Store>();
        }
    }
}

Not only should the Id property of the Product class be protected, but the StoresStockedIn property should be as well. Once this list is populated, we should never be able to set it since that would create orphaned Store records.

namespace FluentNHibernateConsole.Entities
{
    public class Store
    {
        public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
        public virtual IList<Product> Products { get; protected set; }
        public virtual IList<Employee> Staff { get; protected set; }

        public Store()
        {
            Products = new List<Product>();
            Staff = new List<Employee>();
        }

        public virtual void AddProduct( Product product )
        {
            product.StoresStockedIn.Add( this );
            Products.Add( product );
        }

        public virtual void AddEmployee( Employee employee )
        {
            employee.Store = this;
            Staff.Add( employee );
        }
    }
}

Here’s an outline of the Program class:

namespace FluentNHibernateConsole
{
    public class Program
    {
        // Adds sample data to our database and writes the data to the console
        static void Main() { }

        // Returns our session factory
        private static ISessionFactory CreateSessionFactory() { }

        // Returns our database configuration
        private static MsSqlConfiguration CreateDbConfig()

        // Returns our mappings
        private static AutoPersistenceModel CreateMappings() { }

        // Drops and creates the database schema
        private static void DropCreateSchema( Configuration cfg) { }

        // Writes the store data, along with its associated products and employees, to the console
        private static void WriteStorePretty( Store store ) { }

        // Adds any products that we pass in to the store that we pass in
        public static void AddProductsToStore( Store store, params Product[] products ) { }

        // Adds any employees that we pass in to the store that we pass in
        public static void AddEmployeesToStore( Store store, params Employee[] employees ) { }
    }
}

WriteStorePretty, AddProductsToStore and AddEmployeesToStore methods are all fairly self-explanatory:

// Writes the store data, along with its associated products and employees, to the console
private static void WriteStorePretty( Store store )
{
    Console.WriteLine( store.Name );
    Console.WriteLine( " Products:" );

    foreach ( var product in store.Products )
    {
        Console.WriteLine( " " + product.Name );
    }

    Console.WriteLine( " Staff:" );

    foreach ( var employee in store.Staff )
    {
        Console.WriteLine( " " + employee.FirstName + " " + employee.LastName );
    }

    Console.WriteLine();
}

// Adds any products that we pass in to the store that we pass in
public static void AddProductsToStore( Store store, params Product[] products )
{
    foreach ( var product in products )
    {
        store.AddProduct( product );
    }
}

// Adds any employees that we pass in to the store that we pass in
public static void AddEmployeesToStore( Store store, params Employee[] employees )
{
    foreach ( var employee in employees )
    {
        store.AddEmployee( employee );
    }
}

In the Main method, we open a session factory, then begin a transaction. At the end of the transaction, we save the session and commit the transaction:

// Adds sample data to our database and writes the data to the console
static void Main()
{
    // Create a session factory
    var sessionFactory = CreateSessionFactory();

    // Open a session
    using ( var session = sessionFactory.OpenSession() )
    {
        // Begin a transaction
        using ( var transaction = session.BeginTransaction() )
        {
            // Create a couple of Stores each with some Products and Employees
            var barginBasin = new Store { Name = "Bargin Basin" };
            var superMart = new Store { Name = "SuperMart" };

            var potatoes = new Product { Name = "Potatoes", Price = 3.60 };
            var fish = new Product { Name = "Fish", Price = 4.49 };
            var milk = new Product { Name = "Milk", Price = 0.79 };
            var bread = new Product { Name = "Bread", Price = 1.29 };
            var cheese = new Product { Name = "Cheese", Price = 2.10 };
            var waffles = new Product { Name = "Waffles", Price = 2.41 };

            var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" };
            var jack = new Employee { FirstName = "Jack", LastName = "Torrance" };
            var sue = new Employee { FirstName = "Sue", LastName = "Walkters" };
            var bill = new Employee { FirstName = "Bill", LastName = "Taft" };
            var joan = new Employee { FirstName = "Joan", LastName = "Pope" };

            // Add Products to the Stores
            // The Store-Product relationship is many-to-many
            AddProductsToStore( barginBasin, potatoes, fish, milk, bread, cheese );
            AddProductsToStore( superMart, bread, cheese, waffles );

            // Add Employees to the Stores
            // The Store-Employee relationship is one-to-many
            AddEmployeesToStore( barginBasin, daisy, jack, sue );
            AddEmployeesToStore( superMart, bill, joan );

            // Save the session
            session.SaveOrUpdate( barginBasin );
            session.SaveOrUpdate( superMart );

            // Commit the transaction
            transaction.Commit();
        }

        // Begin a transaction
        using ( var transaction = session.BeginTransaction() )
        {
            var stores = session.CreateCriteria( typeof( Store ) )
                .List();

            foreach ( var store in stores )
            {
                WriteStorePretty( store );
            }

            // Commit the transaction
            transaction.Commit();
        }
    }

    Console.ReadKey();
}

This hard dependency on NHibernate isn’t a best practice, but it will do for now.

The CreateSessionFactory method is where we get into the configuration of Fluent NHibernate:

// Returns our session factory
private static ISessionFactory CreateSessionFactory()
{
    return Fluently.Configure()
        .Database( CreateDbConfig )
        .Mappings( m => m.AutoMappings.Add( CreateMappings() ) )
        .ExposeConfiguration( DropCreateSchema )
        .BuildSessionFactory();
}

There are four steps to our fluent configuration. First, we configure our database connection with a call to the CreateDbConfig method:

// Returns our database configuration
private static MsSqlConfiguration CreateDbConfig()
{
    return MsSqlConfiguration
        .MsSql2008
        .ConnectionString( c => c
            .Server( "testServer" )
            .Database( "testDB" )
            .Username( "testUser" )
            .Password( "testPass" );
}

Before running the application, make sure you create an empty database, and replace “testServer”, “testDB”, “testUser” and “testPass” with your actual server, database, username, and password. Note that I’m using SQL Server 2008, but you can use SQLite, MySQL, or any other supported database. You can also read the connection string from a settings file, which you can read more about on the Fluent NHibernate Wiki.

Next, we configure our mappings with a call to the CreateMappings method:

// Returns our mappings
private static AutoPersistenceModel CreateMappings()
{
    return AutoMap
        .Assembly( System.Reflection.Assembly.GetCallingAssembly() )
        .Where( t => t.Namespace == "FluentNHibernateConsole.Entities" )
        .Conventions.Setup( c => c.Add( DefaultCascade.SaveUpdate() ) );
}

Normally, NHibernate uses XML files to determine how each entity in the domain model relates to each table in the database. Fluent NHibernate allows us to bypass this laborious step with auto mappings. We can add other conventions here, but all we need to get our application running is to turn cascading on. This way, when we save a Store, all the associated Products and Employees are saved too.

Next, we tell NHibernate to drop and create our database schema each time the application runs:

// Drops and creates the database schema
private static void DropCreateSchema( Configuration cfg )
{
    new SchemaExport( cfg )
        .Create( false, true );
}

This step is optional. If you prefer, you can the database schema manually. You can also tell NHibernate to update the schema only when the model changes:

// Updates the database schema if there are any changes to the model
private static void UpdateSchema( Configuration cfg )
{
    new SchemaUpdate( cfg );
}

Finally, we build the session factory. This is the last step in our fluent configuration.

We can now run the application. When you do so, you should see this:

If this is what you see, then congratulations on completing your first Fluent NHibernate project with auto mappings! If not, drop me a comment and we’ll try to get it figured out. I’m pretty new to this too, so don’t be afraid to ask!