Fluent Nhibernate and ASP.NET MVC

For those of you who follow our personal tweets (yeah we have to tweet more with our @itsletnl account), you probably noticed how we’re currently involved (or obsessed) by Fluent Nhibernate. Fluent Nhibernate FTW!

Itslet Fluent Nhibernate

Fluent Nhibernate uses poco mappings instead of XML mapping, like its big brother Nhibernate. There is no strong argument to use Fluent Nhibernate instead of Nhibernate, it is just a matter of taste to me. Although, Fluent Nhibernate can automap and autopersist your entities, based on convention, and Nhibernate cannot.

Getting started with Fluent Nhibernate is very simple. Just read their excellent getting started guide. It doesn’t make much sense to repeat that on this website with different entities.

But how do we get started with ASP.NET MVC? How do I connect with the Fluent Nhibernate session gracefully?

Handling sessions

I used the book of Jason Dentler to find out more. The most common pattern in web application is the session-per-request. We open the session when the request begins and close it when it ends.

Nhibernate has a contextual session feature which allows a session to be associated with some application specific scope (unit of work). You need to set the current_session_context_class property in the hibernate-configuration section of web.config. But as we use Fluent Nhibernate, we have to use the ‘ExposeConfiguration’ method.

Here is my Global.asax.cs. Check out line 45: .ExposeConfiguration(c => c.SetProperty(“current_session_context_class”, “thread_static”))’.

Now we can refer to that session in our controller, like this:

In the example the person is fetched from the database. But to make the app more production worthy, we would use dependency injection rather than directly access the current session. Also, we would not have exposed our connectionstring like that.
But that is a completely new blogpost.

(Another) ASP.NET MVC 2.0 app with MongoDb Part 1

I have been fiddling around with Db4o and well.. I did not finish my app. Which probably means that it is time to try out yet another document based database. So. Let’s cover MongoDb this time.

I will now create a webapplication where users can submit bugs for a certain software project. Let’s call it BugBase.

The first step is to create the folders c:\data and c:\data\db. These are the default folders that you can override if you wish. The next step is to download the Mongo binaries and extract them in c:\data\db.

As with many nosql databases they’re obscenely trivial to install. Click on mongod.exe in the bin folder and the Mongo server is running:


Let’s see if this works. Let’s create a bug record for “unable to save” in a database.

MongoDB shell version: 1.4.2
url: test
connecting to: test
type "exit" to exit
type "help" for help
> b = { description : "unable to save" };
{ "description" : "unable to save" }
> b = { bugtext : "unable to save the records"};
{ "bugtext" : "unable to save the records" }
> db.bugbase.find();
{ "_id" : ObjectId("4c03a7fa0e6c000000004226"), "bugtext" : "unable to save the
records" }


Apparently it does work 😉
I inserted a record in a document (ie table) and Mongo created a unique identifier for me. Cool.

Put Mongo in an ASP.NET MVC 2 app

First step is to create an MVC2 app in Visual Studio 2010 and get rid of all the standard stuff from the template.

Did somebody actually write a MongoDb to Linq provider? But yes of course! My hero Rob Conery did. And Andrew Theken took it further and hosts the project on Github.

What a surprise, only yesterday Andrew uploaded a new version. Wherever would I be without the efforts of these brilliant people? Download the latest Norm project (should I use Github) and compile it in Visual Studio. Grab the norm.dll from the bin folder and add a reference to it in the BugBase project.

Next I need an example as of how to use this dll. At Codeplex Shiju Varghese wrote an example application, which I will use as a reference. But you don’t need to check out all these examples. It’s just to give the credits to the people that made all this possible.

For BugBase we need at least 2 classes. Bug and User. Create them in the Models folder.

 public class User
        public ObjectId Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public List Bugs { get; set; }

        public User() {
            Bugs = new List();
public class Bug
        public ObjectId Id { get; set; }
        public string ShortDescription { get; set; }
        public string LongDescription { get; set; }
        public DateTime? Date { get; set; }
        public bool Status { get; set; }
        public User User { get; set; } 

Now, let’s add a folder called Infrastructure to put all the data layer stuff in. Create a new class called MongoSession.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Norm;
using Norm.Collections;
using Norm.Linq;
using Norm.Responses;
using BugBase.Models;

namespace BugBase.Infrastructure
    internal class MongoSession : IDisposable
        private readonly MongoQueryProvider provider;

        public MongoSession()
            var mongo = new Mongo("BugBase", "localhost", "27017", "");
            this.provider = new MongoQueryProvider(mongo);

        public IQueryable Bugs
            get { return new MongoQuery(this.provider); }
        public IQueryable users
            get { return new MongoQuery(this.provider); }
        public MongoQueryProvider Provider
            get { return this.provider; }

        public void Add(T item) where T : class, new()

        public void Dispose()
        public void Delete(T item) where T : class, new()

        public void Drop()

        public void Save(T item) where T : class,new()

We’ve got the models in place and the datalayer, so let’s create a UserController.


Let’s create a view.


Create a strongly typed view with the BugBase.Models.User View Data Class and Create as View Content.

Now let’s add the controllermethods to create a user and list them:

 public ActionResult Index()
            using (var session = new MongoSession())
                var userlist = session.users.AsEnumerable();
                return View(userlist);
        public ActionResult Create(User user)
            using (var session = new MongoSession())
            return new RedirectResult("/User");

Compile the project and behold the result:


And the list: (OK, never mind the poor security of this app)


Next time let’s implement the bugs. You can download the very beta beta beta BugBase App here.

Db4o and ASP.NET MVC 2 part 2

In the last article I explained how to set up an ASP.NET MVC 2 project with a Db4o backend to create a weblog application. In the spirit of Domain Driven Design we created a single entity ‘Story’. We managed to create a separate class for database access. We did not however, implement the Unit of Work or the Repository pattern. We’ll get to that later. Let’s have a working application first and we’ll build in the abstractions later.

So, we created a StoryController in the Controllers folder and we implemented the Create method. After clicking Submit the method takes us to Index:


So we need to go to line 19 and right click on Index and click Add View, just like before:


And then we can scaffold the Index View like this:


Here is the code to list all the Story entries in the database:

public ActionResult Index()
            //instantiate the db4o objectcontainer:
            IObjectContainer db = MySingleInstance.Instance().

                //this is the tricky part.
                //We select all the Story objects from the db:
                var query = from Story s in db select s;
                //And we'll add that to a list:
                List allStories = new List();
                foreach (Story story in query)
                //We'll present the List to the View
                return View(allStories);
                //Close the database.

Why am I copying the query result to a List? The answer is, if I don’t, the database closes before the page is displayed, so the page remains empty and we’ll get a DataBaseClosed Exception.

Now run the application (hit F5) and browse to http://localhost:portnr/Story.


And we see all our entries. If you click Create New, you’ll be directed to the form we made in part 1 and you can add another blog article. So basically the weblog application is ready, right?

The only thing is, it looks like shit. And I am no designer. So let’s grab a nice minimalist CSS template from the web. I googled ‘minimalist elegant css’ and came across Inkcover. The css of this site is a bit cluttered and it’s derived from a templating engine from Coldfusion I believe. But with a little hacking it came out quite nice.

Ik Zeg..

I’ll think I’ll have to notify the designers.

Next time I will cover validation at last. And perhaps upload the code.