Castle Project ActiveRecord for ASP.Net Tutorial: Part 1 Introduction and a Single Table
I recently began working with Castle ActiveRecord. It is an Object Relational Mapping (ORM) tool for .Net applications. If you’re reading this I probably don’t have to explain what an ORM is, but essentially, instead of using ADO.Net/SQL to interact with your data, you get to manipulate each database record as if it were a .Net object, with CRUD operations available directly as object methods. While the getting started guide on the Castle Project website is generally adequate, it’s for WinForms instead of ASP.Net, there’s a few typos/inconsistencies in code examples, and it’s getting a little dated. I wanted to document my experience here so that others don’t run into the same problems I did while learning. I’ll be making a very simple blog application that generally follows the getting started guide on the ActiveRecord website, but I’m going to break up my tutorial slightly differently. In part one we’ll setup the environment and write the code for a very simple, single table object. In part two we’ll introduce relationships into the application and pretty up the interface a bit. I assume some level of competency in C#, ASP.Net and Visual Studio, but you can be completely new to ActiveRecord, NHibernate, and ORMs in general. To begin, you’ll need:
- Visual Studio or the free Visual Web Developer Express Edition (I’ll be using Visual Web Developer 2008)
- SQL Express, likely installed with your Visual Studio
- The Castle Project AcriveRecord Binaries. This tutorial is based on ActiveRecord 2.0
Adding References
Begin by creating a new website and calling it ActiveRecordTutorial. Right click on the web site in the solution explorer and click “Add References…” Browse to the place you extracted the ActiveRecord DLLs and add Castle.ActiveRecord.dll. This should automatically add a number of other references including, Castle.Components.Validator.dll, Castle.Core.dll, Iesi.Collections.dll, Lucene.Net.dll, NHibernate.dll, and NHibernate.Search.dll. Not included is NHibernate.ByteCode.Castle.dll, add this as well. The official getting started guide actually misses this resource.
Creating The First Database Table
Right click on the App_Data folder and select “Add New Item…” Select SQL Server, and name it ActiveRecordDB.mdf. Note that this is a SQL Server Express database. You may want to use the full version of SQL Server, or even PostgreSQL or MySQL, but I’ll be using Express as it’s the easiest to integrate with an ASP.Net web site. Then view the database in the Database Explorer, right click on the Tables folder and select “Add New Table”, this will be your Person table. The getting started guide used “User” but I found there was some conflict with the existing .Net User class, which made debugging slightly challenging. Create columns for Id (int), UserName (nvarchar(25)), and Password (nvarchar(25)). Id will be the primary key, and should also be an Identity column. After saving this table as Person, it should look like the following:
Adding the Person Class
For each table that you want to use in your application with ActiveRecord, you will create a corresponding class. Add a new class to your application called User.cs. You will get an alert prompting you to put this code file in the App_Code folder. Accept this option. You should then put the following code into this class.
namespace ActiveRecordTutorial
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class Person : ActiveRecordBase<person>
{
private int id;
private string username;
private string password;
public Person() { }
public Person(string username, string password)
{
this.username = username;
this.password = password;
}
[PrimaryKey]
public int Id
{
get { return this.id; }
set { this.id = value; }
}
[Property]
public string Username
{
get { return this.username; }
set { this.username = value; }
}
[Property]
public string Password
{
get { return this.password; }
set { this.password = value; }
}
}
}
There are at 4 things that separate this from a normal class.
- The ActiveRecord attribute on the class name.
- Inheritance from ActiveRecordBase<Person>.
- The PrimaryKey attribute on the Id property.
- Property attributes on all remaining properties.
All of these attributes are used by ActiveRecord define the relation between the table and the class.
Initializing The Framework
Easily the most frustrating part of trying to adapt the official getting started guide to an ASP.Net application was configuring and initializing the framework. The guide creates an XML file to store settings, but ASP.Net already has an XML file handy, the web.config file. To begin, add the following just inside the configSections element, just before the sectionGroup for system.web.extensions
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord">
Next, immediately following the empty connectionStrings element, add the following
<activerecord isweb="true">
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver">
<add key="dialect" value="NHibernate.Dialect.MsSql2008Dialect">
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider">
<add key="connection.connection_string" value="Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\ActiveRecordDB.mdf; Integrated Security=True;User Instance=True">
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"> </add>
</add>
</add>
</add>
</add>
</config>
</activerecord>
Notice that I am using the MsSql2008Dialect. There is no dialect specific to SQL Expres. MsSql2005Dialect also works against SQL Server 2008, but does not take advantage of some of the new Date data types in SQL Server 2008. See the NHibernate blog post NHibernate and Ms Sql Server 2008 for more details. Finally you will need to add the following inside the httpModules element.
<add name="ar.sessionscope" type="Castle.ActiveRecord.Framework.SessionScopeWebModule, Castle.ActiveRecord">
This module provides default behaviour for SessionScope. You could replace this with custom code in the Global.asax file, but the module will do for now. Next, we need to run some code to initialize the application the first time it’s run. Create a Global.asax file and change it’s Inherits property to ActiveRecordTutorial.MyHttpApplication. We do this so that we can place code in a separate class called MyHttpApplication. It is also possible to write your code directly in the Global.asax file, but this was the approach taken by the getting started guide, so it’s what I follow here. Then create a new class called MyHttpApplication and place the following code in it.
namespace ActiveRecordTutorial
{
using System;
using System.Web;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;
public class MyHttpApplication : HttpApplication
{
protected void Application_Start(Object sender, EventArgs e)
{
//get the settings from web.config
IConfigurationSource source = ActiveRecordSectionHandler.Instance;
//register your objects with ActiveRecord
ActiveRecordStarter.Initialize(source, new Type[] { typeof(Person) });
}
}
}
I have only skimmed the surface of configuration and initialization. For more information see the initialization step of the getting started guide, and the Web Applications guide in the official documentation.
Using the Person Class
Finally, to test the Person class put the following in Default.aspx.cs
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ActiveRecordTutorial;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create your new user and set properties
Person myPerson = new Person();
myPerson.Username = "name"; myPerson.Password = "secret"; try
{
//try to save myPerson to database
myPerson.Create();
}
catch (Exception err) { string errReport = "Failed trying to save user"; errReport += err.Message; System.Diagnostics.Debug.Write(errReport); }
}
}
Run the page with F5 and if you’re page successfully loads, you should have a user in the database.�

Conclusion You have now created your first web site using Castle Project ActiveRecord. This framework not only greatly simplifies data access by abstracting SQL calls to objects, but also encourages OOP patterns, leading to more maintainable code. In part two I will be creating Blog and Post objects to illustrate relationships. Until then.
pete and repete

Posted under: 

Dear Sir,
Thanks a lot for this great article, for a week i have been trying to get hold of stuff to get started with Nhibernate and have feen quite confused being a newbie to the concept. But ur article helped me to get started with the application very smoothly…………..Well documented and well explained!!
Dear Sir,
Thanks a lot for this great article, for a week i have been trying to get hold of stuff to get started with Nhibernate and have feen quite confused being a newbie to the concept. But ur article helped me to get started with the application very smoothly…………..Well documented and well explained!!
I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable detract permissions on the App_Details folder…unfortunately I don’t discern how to assign it.
I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable detract permissions on the App_Details folder…unfortunately I don’t discern how to assign it.
This article was a great help to me. I’m new to this & have been trying to make something like this work all day. This was the only example that I could get to work correctly. Thanks for taking time to share this!
This article was a great help to me. I’m new to this & have been trying to make something like this work all day. This was the only example that I could get to work correctly. Thanks for taking time to share this!
Good job.
Good job.