# Sunday, August 01, 2010

This post is an update to a post I made last September (~10 months ago):

http://www.capprime.com/software_development_weblog/PermaLink,guid,162facaa-a3b9-4dc5-b770-657e27e887ad.aspx

The biggest roadblock I ran into when writing that blog post is that ActiveWriter doesn't work well with the Northwind database which had significant ripple effects throughout the sample.

That inspired me to spend quite a bit of time over the last 10 months to make the Castle ActiveRecord code generation story better.

So here is an updated sample using the free version of the Agility for ORMs Castle ActiveRecord code generator in place of ActiveWriter.

--

This is a quick guide to getting up and running with NHibernate and Linq quickly.

We are going to assume our database already exists.  We are going to assume that database is Northwind, and we are going to assume that we are doing database driven design (as opposed to domain driven design).  Northwind setup is described below.

We are going to use Visual Studio 2008 with Service Pack 1 and SQL Server 2008 Express.  (Note: A web application variant of this should work with Visual Web Developer 2008 Express Edition resulting in a completely free development stack.  This sample should also work fine in Visual Studio 2010, but you'll need to change the project to target the .NET Full Profile instead of the .NET Client Profile.)

Step 1:

Download and install the Northwind database.

Jeff Atwood provides approximate instructions here (ask specific questions in the comments if you get stuck):

http://www.codinghorror.com/blog/archives/000434.html

Follow the path for installing the binary files from the command line.  I have tested that the SQL 2005 instructions work on SQL 2008.


Step 2:

Next Download Castle ActiveRecord.  The download link is available from here:

http://www.castleproject.org/castle/projects.html

At the time of writing, the current version is "2.1.2 (2010-01-31)".

Unzip it and remember where you put it, you'll need that info in step 3.


Step 3:

Start Visual Studio 2008

We will create a new console application project:

File -> New -> Project
 Visual C# -> Windows -> Console Application
  ConsoleApplication1 -> OK

We need to add the appropriate NHibernate & Castle Active Record references:

Solution Explorer
 Right Click ConsoleApplication1 -> References -> Add
  Browse Tab
   Go to your Castle ActiveRecord download location and add:
    Castle.ActiveRecord.dll
    Castle.ActiveRecord.Linq.dll
    Castle.DynamicProxy2.dll
    NHibernate.dll
    NHibernate.Linq.dll
   Click OK

And add a reference to System.Configuration as well:

Solution Explorer
 Right Click ConsoleApplication1 -> References -> Add
  .NET Tab
   System.Configuration
  Click OK


Step 4:

Download the free (aka Convention Only) version of the Agility for ORMs Castle ActiveRecord code generator by registering and then downloading here:

http://www.agilityfororms.com/Apps/Register.aspx

The current version is 1.0.0.4.


Step 5:

Run the AFO Castle ActiveRecord code generator, specifying the correct connection string for the Northwind database you setup in Step 1 above.

Note the output directory where the generated files went, you'll need that info in step 6.


Step 6:

Add the generated files to the console application project.

Solution Explorer
 Right Click ConsoleApplication1 -> Add -> New Folder -> DataLayer
 Right Click DataLayer -> Add -> Existing Item...
  Add all of the .cs files generated in Step 5.


Step 7:

We will now add an Application Configuration File to the project and put the Northwind Connection String into it:

Solution Explorer
 Right Click ConsoleApplication1 -> Add -> New Item...
  Visual C# Items -> General -> Application Configuration File
  Add

Modify the file to look like this and use your specific DB connection info:

--
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=.\SQLExpress;Initial Catalog=Northwind;Trusted_Connection=True;"/>
  </connectionStrings>
</configuration>
--


Step 8:

Open the main "Program.cs" class and add the following new method:

        private static void InitializeNHibernateActiveRecord()
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Northwind"].ToString();
            InPlaceConfigurationSource configuration = InPlaceConfigurationSource.Build(DatabaseType.MsSqlServer2008, connectionString);

            ActiveRecordStarter.Initialize(System.Reflection.Assembly.GetExecutingAssembly(), configuration);
        }

Add the following code to the Main Method:

        static void Main(string[] args)
        {
            try
            {
                InitializeNHibernateActiveRecord();

                using (new SessionScope())
                {
                    var queryToExecute = from oneProduct in ActiveRecordLinq.AsQueryable<Product>()
                                         select oneProduct;

                    foreach (Product oneProduct in queryToExecute.Take(5).ToList())
                    {
                        Console.WriteLine("ProductID=[" + oneProduct.ProductID + "] ProductName=[" + oneProduct.ProductName + "] Supplier CompanyName=[" + oneProduct.Supplier.CompanyName + "]");
                    }
                }
            }
            catch (Exception oneException)
            {
                Console.WriteLine("oneException=[" + oneException + "]");
                throw; // you can remove this if you'd rather the program exit "more normally"
            }
        }

Add the following using statements at the top of Program.cs:

using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord.Linq;

using Model.Northwind;


Step 9:

Copy the NHibernate.ByteCode.Castle.dll file from your Castle Active Record download unzip directory to your projects bin\Debug\ folder.


Step 10:

Run the application:

Ctrl-F5 (Debug -> Start Without Debugging)

And you should see the following output:

--
ProductID=[1] ProductName=[Chai] Supplier CompanyName=[Exotic Liquids]
ProductID=[2] ProductName=[Chang] Supplier CompanyName=[Exotic Liquids]
ProductID=[3] ProductName=[Aniseed Syrup] Supplier CompanyName=[Exotic Liquids]
ProductID=[4] ProductName=[Chef Anton's Cajun Seasoning] Supplier CompanyName=[New Orleans Cajun Delights]
ProductID=[5] ProductName=[Chef Anton's Gumbo Mix] Supplier CompanyName=[New Orleans Cajun Delights]
Press any key to continue . . .
--

We have successfully executed a join query through Linq.


Please note:

You'll notice that the Agility for ORMs Castle ActiveRecord code generator only generated 5 class files in addition to a readme.txt file (there are 13 tables in Northwind which would otherwise result in 11 class files).  Northwind is not a convention based database due to use of assignable keys, surrogate keys, and composite keys.  The free version of the AFO code generator only works with convention oriented database tables and only 5 of the tables in Northwind follow conventions.  The readme.txt file explains why the other tables were not generated.

The commercial version ($30) of the AFO code generator will properly generate code for all 13 tables in Northwind and is intended to support the entire feature set of Castle ActiveRecord including things like Composite Keys, which aren't currently supported by ActiveWriter.


Now that you have the basic NHibernate Linq infrastructure in place, there are plenty of Linq examples and sample code available elsewhere.

Enjoy!