Ryan LanciauxNew Media Mercenary

RhinoCommons, NHibernate and ASP.NET MVC Part 2 - Configuration

May 20, 2008 by ryan

Following up on my last post, we're going to setup a project and get everything ready for the code (we'll be doing the coding very soon -- I promise).  First off, create a new MVC application (make sure you're using the latest preview from codeplex) and a new Class library. From here, you'd normally want to want to do some TDD to create your model but that's a little outside the scope of this example.

Add the references to Boo, Castle, NHibernate, RhinoCommons and Log4Net to the MVC application. In the class library, add Castle.ActiveRecord, Iesi.Collections, NHibernate, Rhino.Commons and Rhino.Commons.NHibernate. Switch over to your web.config file and Underneath the ConfigSections node add the following custom tags:

        <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />

        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

            <section name="Rhino.Commons.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

        </sectionGroup>   

Next add the specific custom tag properties somewhere after the </ConfigSections> : 

    <activerecord isWeb="true">

        <config>

            <add key="hibernate.connection.driver_class"

                value="NHibernate.Driver.SqlClientDriver" />

            <add key="dialect"

                value="NHibernate.Dialect.MsSql2005Dialect" />

            <add key="hibernate.connection.provider"

                value="NHibernate.Connection.DriverConnectionProvider" />

            <add key="hibernate.show_sql"

                value="false" />

            <add key="connection.connection_string" value="Data Source=___________;Initial Catalog=NHibernateTest;Integrated Security=True" />

        </config>

    </activerecord>

These active record settings should be pretty straight-forward but for more information on specific dialects or other properties check out the Castle's Configuration Reference. Be sure to swap out my Data Source and Initial Catalog settings with yours.

    <applicationSettings>

        <Rhino.Commons.Properties.Settings>

            <setting name="WindsorConfig"

                    serializeAs="String">

                <value>windsor.boo</value>

            </setting>

        </Rhino.Commons.Properties.Settings>

    </applicationSettings>

With this tag, we're telling Castle that we're going to configure Windsor with a boo file instead of an xml document. Ayende Rahien pointed out in the comments that this tag is no longer necessary as long as the file is named windsor.boo

Windsor Configuration With Boo 

Up until this point, we've been dealing with the web.config to configure our application -- now we want to configure Windsor but instead of using another xml file, we're going to use a boo file. What is Boo you might ask? According to wiki...

Boo is an object oriented, statically typed programming language developed starting in 2003, which seeks to make use of the Common Language Infrastructure support for Unicode, internationalization and web style applications, while using a Python-inspired syntax and a special focus on language and compiler extensibility. 

The mere fact that you can use a programming language instead of an XML file to configure Windsor is pretty sweet. I would be lying if I claimed to know boo very well, however, the Exesto and Hibernating-Forums samples (from the Rhino-Tools project) have enough information to get you up and running. I plan on learning boo well enought to create my own config files from scratch but in the mean time, here's what my boo file looks like (heavily influenced by the sample applications mentioned above)...

import Rhino.Commons

import System.Reflection

import Castle.Core

import Castle.Services.Transaction

import Castle.Facilities.AutomaticTransactionManagement

 

activeRecordAssemblies = ( Assembly.Load("ProductModelActiveRecord"), )

 

Component("active_record_repository", IRepository, ARRepository)

Component("active_record_unit_of_work",

    IUnitOfWorkFactory,

    ActiveRecordUnitOfWorkFactory,

    assemblies: activeRecordAssemblies )

Check out Ayende's comment for a more succinct way to register these components. As you might have noticed, I still have to set up the colors for boo files in Visual Studio :) What this file is doing is loading the assemblies and setting up the repository / unit of work (we'll see those in action in the next parts of this series). Your project configuration should be all set. Next time we will actually be writing some code so stick around for that. View Part Three - The Model





RhinoCommons, NHibernate and ASP.NET MVC Part 1 - Setup

May 19, 2008 by ryan

After my last post about the unit of work with NHibernate, Chad Myers mentioned that I should take a look at Ayende's Rhino Commons (because the Unit of Work stuff is already being handled). Since I am not a big fan of reinventing the wheel I decided I would give it a shot. There's going to be another post in the near future about how to get Rhino Commons, Castle ActiveRecord and ASP.NET MVC working together but for now, it would be good to make sure all the necessary components are installed on your machine.

  1. Make sure you have a subversion client -- Tortoise SVN or the command prompt is what I use but any subversion client should be fine.
  2. If you don't already have Nant installed on your machine download and install that
  3. Download and build the following (Ayende mentions, the trick is not opening in Visual Studio):
  4. Next you're going to want to setup the NHibernate Query Generator (we're going to use Linq to NHibernate in a later example but for now get this installed). This should be a part of the Rhino-tools package but if you want you can download the binaries. Then setup the application as an external tool in Visual Studio (my settings are posted below). see James Hollingworth's post for more info
    • Command: C:\program files\nhqg\NHQG.exe
    • Arguments: /Lang:cs /InputFilePattern:$(BinDir)/ProductModelActiveRecord.dll /OutputDirectory:$(ProjectDir)/Queries /BaseNamespace:Queries
    • Initial Directory: $(TargetDir)
  5. Finally make sure you're running the preview 3 drop of the ASP.NET MVC Framework -- you can get that here from CodePlex
You should now have everything setup. It may be good to take a look at the Exesto application in the rhino-tools\SampleApplications directory to get an introduction to the Rhino-tools / binsor / castle settings that we'll be looking at later on. Finally, if you are not familiar with the ASP.NET MVC Framework take a look Fredrik Normen's step by step guide. In the next couple of days, I will be posting how to wire these tools together for quick web application development. Stay Tuned.




Using NHibernate (years after I should have been)

April 30, 2008 by ryan

As mentioned in my last post, I've been starting to use NHibernate in some of my more recent projects. I checked it out years ago and I completely hated it (maybe becuase I was a newer developer -- not totally sure). More recently, however, I've realized some of the benefits of Domain Driven Design and thought its about time to give Hibernate another shot. I'm admittedly pretty new to Hibernate so any feedback would be appreciated!

Classes 

    public class ProductGroup

    {

        public virtual string ProductGroupID { get; set; }

        public virtual string Title{ get; set;}

        public virtual IList<SimpleProduct> Products { get; set; }

    } 

    public class SimpleProduct

    {

        private IList<SimpleProduct> _relatedProducts;

 

        public virtual string ID { get; set; }

        public virtual string Title { get; set; }

        public virtual string ImagePath { get; set; }

        public virtual string Description { get; set; }

        public virtual IList<SimpleProduct> RelatedProducts

        {

            get{ return _relatedProducts; }

            private set { _relatedProducts = value;  }

        }

 

        public virtual void AddRelatedProduct(SimpleProduct product)

        {

            if (_relatedProducts == null)

                _relatedProducts = new List<SimpleProduct>();

            _relatedProducts.Add(product);

        }

 

    }

We're going to start out with some very contrived classes (normally would start with tests but this is just for the hibernate concepts)... These classes should be pretty straight forward; they consist only of some basic properties and list methods.

Data Tables 

Next, we need to create our tables to hold the data coming from the Classes -- I've created a product table / product group table and a lookup table for both (there are many-to-many references in both SimpleProduct and ProductGroup). 

CREATE TABLE [dbo].[SimpleProducts](
    [ProductID] [char](32) NOT NULL,
    [Title] [nvarchar](50) NOT NULL,
    [ImagePath] [nvarchar](300) NULL,
    [Description] [nvarchar](500) NULL
)
   
CREATE TABLE [dbo].[RelatedProductsLookup](
    [ProductID] [char](32) NOT NULL,
    [RelatedProductID] [char](32) NOT NULL
)

CREATE TABLE [dbo].[ProductsProductGroupsLookup](
    [ProductGroupID] [char](32) NULL,
    [ProductID] [char](32) NULL
)

CREATE TABLE [dbo].[ProductGroups](
    [ProductGroupID] [char](32) NOT NULL,
    [Title] [nvarchar](50) NULL
)    

 You will want to set the Primary Key of the SimpleProduct and Product Groups table to be the ID. 

Hibernate Mappings

Next we're on to the Hibernate mapping files. These files link the columns in the database to the fields/properties in the domain classes. Please check the project documentation for more detailed information on the Hibernate Schemas.

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

                  namespace="ProductModel" assembly="ProductModel" default-lazy="false">

  <class name="ProductGroup" table="ProductGroups">

    <id name="ProductGroupID">

      <column name="ProductGroupID" sql-type="char(32)" not-null="true" />

      <generator class="uuid.hex" />

    </id>   

    <property name="Title">

      <column name="Title" length="50" not-null="true" />

    </property>   

    <bag name="Products"  table="ProductsProductGroupsLookup" lazy="false">

      <key column="ProductGroupID" />

      <many-to-many class="SimpleProduct" column="ProductID" />     

    </bag>       

  </class

</hibernate-mapping>

Inside the hibernate mapping tag, we have an element called class where we're defining the relationship between the class and the table in the database. From there we're defining the properties -- Most of this should be pretty straight forward but there are a couple things I would like to focus on. 

    <id name="ProductGroupID">

      <column name="ProductGroupID" sql-type="char(32)" not-null="true" />

      <generator class="uuid.hex" />

    </id>   

 This node is defining the unique ID for the class -- the ID is being created for each item and looks a little something like this: 46abbefc08d14b49a5d15c8a4dd69ff2

    <bag name="Products"  table="ProductsProductGroupsLookup" lazy="false">

      <key column="ProductGroupID" />

      <many-to-many class="SimpleProduct" column="ProductID" />     

    </bag>       

  </class

Here we're defining a many-to-many relationship with Products -- this is bumping up against the lookup table we defined earlier to get all SimpleProducts associated with this class. currently the bag is defining a many-to-many relationship. We're going to assume that a product can exist under any number of product groups -- for instance if we have a video game system it could be under both the Home Entertainment and Electronics product group. See the project documentation for other types of relationships (one-to-many, etc).

SimpleProduct Mapping:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

                  namespace="ProductModel" assembly="ProductModel" default-lazy="false">

  <class name="SimpleProduct" table="SimpleProducts">

    <id name="ID">

      <column name="ProductID" sql-type="char(32)" not-null="true" />

      <generator class="uuid.hex" />

    </id>   

    <property name="Title">

      <column name="Title" length="50" not-null="true" />

    </property>   

    <property name="ImagePath">

      <column name="ImagePath" length="300" not-null="false" />

    </property>   

    <property name="Description">

      <column name="Description" length="500" not-null="false" />

    </property>       

    <bag name="RelatedProducts"  table="RelatedProductsLookup" lazy="false">

      <key column="ProductID" />

      <many-to-many class="SimpleProduct" column="RelatedProductID" />     

    </bag>       

  </class

</hibernate-mapping>
 

 

Accessing The Data

Now that we've defined all of our mappings its time to create some methods to access our data.

    public class ProductGroupRepository

    {

        private ISession _session;

 

        public ProductGroupRepository(ISession session)

        {

            _session = session;

        }

 

        public ProductGroup GetByTitle(string Title)

        {

                return _session.CreateCriteria(typeof(ProductGroup))

                    .Add(Expression.Eq("Title", Title))

                    .UniqueResult<ProductGroup>();

        }

 

        public IList<ProductGroup> List()

        {

                return _session.CreateCriteria(typeof(ProductGroup))

                    .List<ProductGroup>();

 

        }

    }

 

The ISession is the Hibernate object to use when accessing the data -- from what it looks like, these should pretty much line up with a unit of work (More on that here).

In the other methods of the class, we first need to define what type of object we're looking for. In case it's not obvious, we're specifying that in the CreateCriteria section. In the List() method, we're returning a list (of ProductGroups) -- there are no filters or other criteria defined for this operation. In the GetByTitle() method, however,  we're stating that the Title for the product must match the Parameter 'Title'.

Demo Application

I've created a quick demo application using MVC and NHibernate. As I said, I'm still very new to hibernate so there's a lot I'm trying to learn (for instance where the ISession should initially be created and closed in an MVC application). Please let me know of any way that this could be better -- generally I'm writing this to help solidfy my thoughts on the technology, help others (hopefully) and also improve from others feedback. 

If you have tortoise or some other svn client, you can grab the code from http://svn2.assembla.com/svn/NHibernateTest/ -- You will need to change the database connection to whatever your db is. Again I would like to reiterate, it's demo code -- not even close to anything that I would ever use in production but worked out okay for testing. 

kick it on DotNetKicks.com

 

Disclaimer: Use this code at your own risk. 








© 2008 Ryan Lanciaux :: powered by BlogEngine.NET