MongoDB and ASP.NET MVC – A basic web app

January 16th, 2011 by Gareth / Comments

I first heard about document databases (NoSql) last year thanks to Rob Conery’s blog post. At the time I couldn’t imagine a database without SQL but there really is such a thing and MongoDB is a leading example. Today I’ve spent some time working with MondoDB putting together a basic ASP.NET MVC web application to CRUD a bugs database.

A document database differs from a relational database in that, when you can get away with it, a record (known as a document here) can contain all it’s own data. It is not necessary to have normalised tables with joins pulling data together into a result set. Instead of having an order table, a product table, a customer table, an address table etc… you can have a single record containing all this information.

Here is an example of a single record for a user :

	{
    "name": "Mr Card Holder",
    "email": "blowJoggs@myemail.com",
    "bankAccounts":
    [
        {
            "number": "12332424324",
            "sortCode": "12-34-56"
        },
        {
            "number": "8484949533",
            "sortCode": "11-33-12"
        },
    ],
    "address":
    {
        "address1": "100 The Big Road",
        "address2": "Islington",
        "address3": "London",
        "postCode": "LI95RF"
    }
}
	

And that’s how the record is stored in the database; the exact opposite of a normalised database. The user’s bank accounts are stored in the user document. In this example a user’s bank accounts are unique to that user so it’s ok to store them right there. But what about when the associated information needs to be more centralised such as an author’s list of published books? What happens when there are multiple authors on a book? In this case you would have a separate collection for the books and put the list of book ObjectIds in the author document. Like this :

	{
    "name": "Mr Author",
    "email": "I_write_books@myemail.com",
    "publishedBooks":
    [
        {"id": "12332424324"},
        {"id": "5r4654635654"},
        {"id": "5654743"}
    ],
    "address":
    {
        "address1": "142 The Other Road",
        "address2": "Kensington",
        "address3": "London",
        "postCode": "L92RF"
    }
}
	

After loading the author from MongoDB you would then perform a second query to load the associated books.

The data is stored in BSON format (a binary format of JSON). You still get indexes and the equivalent of where clauses, the simplicity is not at the cost of functionality. Pretty much the only thing you don’t get are complex transactions.

I wanted to try this out for myself so I installed MongoDB and saw it working from the command line and then started looking into a C# driver. After a quick look around the internet it seems that there are two main options for C# drivers :

I chose the official driver because, although it isn’t as mature as Sam Corder’s driver, I’d already started reading the docs for it.

A day in Visual Studio and a JSON Viewer

First I wrote a very rudimentary membership provider that uses the Mongo database. This lets you register on the site and then login which is enough for my test. Hopefully the MongoDB guys will release a complete ASP.NET membership provider soon.

Secondly I wrote an ASP.NET MVC controller, domain class and MongoDB bug repository to help me figure out how to work with a Mongo database using C#. The BugRepository class contains database code like this :

	public Bug Read( string sId)
{
    MongoServer oServer = MongoServer.Create();
    MongoDatabase oDatabase = oServer.GetDatabase( "TestDB");
    MongoCollection aBugs = oDatabase.GetCollection( "bugs");
 
    Bug oResult = aBugs.FindOneById( ObjectId.Parse( sId));
 
    return oResult;
}
 
public Bug Update( Bug oBug)
{
    MongoServer oServer = MongoServer.Create();
    MongoDatabase oDatabase = oServer.GetDatabase( "TestDB");
    MongoCollection aBugs = oDatabase.GetCollection( "bugs");
 
    aBugs.Save( oBug);
 
    return oBug;
}
	

If, like me, you are just getting started using MongoDB with C# you may find it useful to see the code so here is the source code for the test app. You’ll need Visual Studio 2010 and MVC 3. This is what you’ll get :

My main resources while figuring this out were :

One more thing. Document databases are absolutely perfect for content management systems. One of the challenges for a CMS is handling dynamic schemas and in relational databases this usually involves at least two generic looking tables. To a document database the collection schema is a trivial concept, it just doesn’t care! You can add new properties to a collection whenever you feel like it, even when there is huge amount of data already there. Drupal has already integrated MongoDB I expect more to follow.

ASP.NET MVC, MongoDB

Comments

My desk

January 9th, 2011 by Gareth / Comments

I am always fascinated when I see photos of other developers’ desks so I thought I’d share mine with the world. For years my desk has been an undervalued dump and, in an act of shameful correlation, I have been an under performing stig for years too.

You’ll see plenty of web design books there which I should put away, I don’t read them any more. There are some iPhone developer books and a few .NET books as well as some productivity and business books. I do have 4 Android books (of the brilliant Mark Murphy Commonsware series) but they’re all pdfs so I can’t put them on my shelf except as represented on a usb drive. I’m waiting for the perfect tablet to come out so I can read them comfortably away from my desk. At the moment I make do with the iPod Touch (brilliant device!).

I also have a few books that provide inspiration but for me the best inspiration is this :

  1. Browse to Google maps
  2. Go to an area where I would love to live
  3. Search for “house for sale”
  4. Look at the photos of my dream house, and dream

Try this example of Bridgnorth. Makes me work harder and visualize my goal. I can see us being very happy in a new bigger house away from this poky end terrace with zero parking although Bridgnorth might be a bit too remote for my other half

I’m in the process of rearranging this the tiniest room in the house (otherwise known as my office). so I’ll blog again when that happens.

Inspiration, Productivity

Comments

My take on .NET CMS’s – Orchard

January 8th, 2011 by Gareth1 / Comments

I threw myself at Orchard for 3 months from August 2010 to November just when version 0.5 had been released. Orchard is based on ASP.NET MVC and at the moment is an open source project financially backed by Microsoft. There are some very clever chaps working on Orchard.

I really tried to use the early 0.5 version of Orchard. The module development infrastructure was baked in so I started creating simple modules by going through the docs. If I had had this blog at the time I would have blogged with lots of detail about how to start working on Orchard modules, as well as a FAQ of all the error messages I’d received and how I fixed them which would have been useful for developers to see

Wow look at this code!

At first I was impressed by the quality of the code and the high level of experience and expertise that has clearly gone into Orchard. They’ve also used lots of open source libraries which introduced me to lots of new concepts and .NET code I would otherwise have never realised was possible. But in the end I just gave up!

Wow. I suck!

In a nutshell it was too hard to get results with the 0.5 version. They’re at version 0.8 now with a 1.0 release coming soon. I gave up at version 0.5 so I can’t say anything about 0.8 or 1.0. My head-against-wall moments could easily have been due to a lack of documentation, which is fair enough as Orchard isn’t even at version 1 yet! The available docs really helped but after I’d read them 20 times I came to the conclusion that I was stuck.

My personal opinion is that in order to produce a flexible CMS in a pre .NET 4 language the code has to be engineered to the point that there is too steep an entry level for a typical enthusiastic module developer. I base this on having worked with Kooboo and Orchard as well as Drupal and WordPress.

I also have the opinion that new CMS’s (not just Orchard) think they can push things off to the community too early.

We can’t do that module the community must do that. Yes that ungrateful lot over there. Look at them, expecting us to do everything. Idiots

Do they think they can just follow the “WordPress model” and watch the magic unfold? A community like WordPress’ cannot be prescribed, it is simply down to how easy and flexible it is for a module developer to use combined with good support

I have now officially dropped the idea of “creating websites for people“. It was just something to fill the time and soak up my flailing eagerness while I found a better idea.

The idea of creating websites for people now makes me sick. Now I should stop writing blog posts about technology I am no longer using and focus on my real passions

ASP.NET MVC, CMS

Comments

My Micro-SAAS Journey

Get the inside story as I work out how to create a micro-SAAS