I’ll let a few queries from my current project say all that needs to be said.

public IEnumerable GetRolledUpEventsFor(DateTime tradeDate, IEnumerable tickers)
        {
            return worker.On(connection, session =>
                                             {
                                                 OrderEventRollup rollup = null;
                                                 return session.QueryOver()
                                                     .Where(x => x.TradeDate == tradeDate)
                                                     .WhereRestrictionOn(x => x.Ticker).IsIn(tickers.ToArray())
                                                     .Select(
                                                         list =>
                                                         list.SelectGroup(x => x.Ticker).WithAlias(() => rollup.Ticker)
                                                             .SelectSum(x => x.Shares).WithAlias(() => rollup.SharesTotal))
                                                     .TransformUsing(Transformers.AliasToBean())
                                                     .List();
                                             });
        }
 public IEnumerable GetBrokersByCode(IEnumerable brokerCodes)
        {
            if (brokerCodes.Count() == 0) return Enumerable.Empty();
            return worker.On(connection, session =>
                                         session.Query()
                                             .Where(x => brokerCodes.Contains(x.Code))
                                             .ToList()
                );
        }
public IEnumerable GetByTradeDateAndTicker(DateTime tradeDate, string ticker)
        {
            return worker.On(connection, session =>
                                             {
                                                 CSMSecurity security = null;
                                                 return session.QueryOver()
                                                     .Fetch(x => x.CSMSecurity).Eager
                                                     .Fetch(x => x.TSOrderSecuritySpec).Eager
                                                     .Fetch(x => x.CSMSecurity.CSMSecurityType).Eager
                                                     .JoinAlias(x => x.CSMSecurity,() => security)
                                                     .Where(x => x.TradeDate == tradeDate)
                                                     .Where(() => security.Ticker == ticker)
                                                     .List();
                                             });
        }
So hawt indeed.
 
Categories: NHibernate

Well here we are on Thursday and I am finally posting Tuesday’s video. When I started doing this I had no idea how long it would take to produce one of these videos. I have a pretty good idea now. ;)

In this installment I cover conventions, both ClassMap conventions and AutoMap conventions. I slowly convert the ClassMap implementation over to AutoMap by leaning on default convention and then adding my own as needed. This demonstration should give you a firm understanding of how conventions work in Fluent NHibernate.


 
Categories: Development | Fluent Interface | NHibernate | Tools

Hello Tuesday! Wait a minute this is Monday’s video. That’s right I spent so much time on Monday producing the Introduction video and planning the ClassMaps video, I didn’t get around to making Monday’s until Tuesday. But hey I am on vacation what are you expecting from me really?

So, today I am covering the topic of ClassMaps in Fluent NHibernate. I used Steve Bohlen’s Summer of NHibernate code from session 9 as a starting place. In this video you will see me get the code running on my machine, upgrade it to NHibernate 2.1.0 GA and then convert it over to using ClassMaps. The video clocks in at just over 30 minutes. Enjoy.


 
Categories: Development | Fluent Interface | NHibernate | Tools

Inspired by Steve Bohlen’s Summer of NHibernate screencast series, I thought I would spend some of my vacation creating an addendum to it called Vacation of Fluent NHibernate.

Links from the Screencast:


 
Categories: Development | Fluent Interface | NHibernate | Tools

I love me some S#arp Architecture! I subscribe to the mailing list where users ask questions about it’s usage and I try to help when I can. Recently, Paul Hinett of UK Creative Designs asked the following question:

Hi Everyone.

I’m very new to NHibernate, Fluent & S#arp but I’m very keen to learn and have an idea of how OOP and DDD works.

One question I have though is if it’s possible to some way extend the IRepository class, at the moment it provides some basic CRUD functions such as Get, GetAll etc...

However, for this project I am creating for virtually every call to the database i need to pass  a SiteId to filter the data, i thought it would be easier to extend the IRepositroy class itself rather than creating 15-20 interfaces which inherit the IRepository class (like the Northwind example project has done for a couple of classes) and add my own functions.

Sorry if any of my terminology is incorrect, hope you understand what i mean!

Regards,
Paul Hinett

The entire thread is a good read and I suggest reading the whole thing for context. What Paul is talking about is a Multi-Tenant application. For a great tutorial on what muli-tenancy is check out Ayende’s excellent series on the subject which starts here and ends here. Sadly, Ayende never went back and finished his series on the topic, but he does still talk on the subject at conferences. I was lucky enough to attend his workshop at ALT.NET Seattle this year. He even has a sample application you can look that demonstrates the key concepts.

S#arp Architecture has multiple database support built in at the Repository level. What this means is that I can have a UserRepository that uses the default nhibernate configuration and then a separate ContentRepository using a different configuration. To accomplish this all you need to do is attribute your Repository with a SessionFactory key like this:

  [SessionFactory("content")]
  public class ContentRepository : Repository
  {  }

There is also some other configuration stuff you need to do for this to work, I’ll get to that in a bit.

What Paul wants to be able to do is to have NHibernate talk to different databases based on some bit of the URL. So, if the user accesses the site via http://www.havartirocks.com it talks to the HavartiCheese database, but if they come in using http://www.provaloneowns.com they talk to the ProvaloneCheese database. He ads the extra wrinkle in that he would like a third common database for things like User accounts.

The best way I have found to approach this kind of problem is to start with the domain and let it tell the infrastructure how to react to it. So given the following simple classes, I would like the User class to be persisted to a common core database and the Orders & LineItems classes to be persisted to their respective Tenant databases.

 
namespace CheeseStore.Core
{
  public class User : Entity
  {
    public virtual string Name { get; set; }
  }
  
  public class Order : Entity
  {
    public virtual DateTime OrderDate { get; set; }
    public virtual DateTime ShipDate { get; set; }
    public virtual IList Items { get; set; }
  }

  public class LineItem : Entity
  {
    public virtual string SKU { get; set; }
    public virtual int Quantity { get; set; }
  }
}

All of my domain classes inherit from the S#arp Architecture base class Entity. This gives me a lot of preconfigured persistence support via NHibernate for my domain classes. Next, I need some way in my domain to identify entities that are tenant specific. The simplest way to do this is with a marker interface. A marker interface has no implementation and as it’s name suggests it simply marks a class so that it is easy to detect via reflection. The above domain now looks like this:

 
namespace CheeseStore.Core
{
  public interface IAmTenantSpecific
  {  }

  public class User : Entity
  {
    public virtual string Name { get; set; }
  }
  
  public class Order : Entity, IAmTenantSpecific
  {
    public virtual DateTime OrderDate { get; set; }
    public virtual DateTime ShipDate { get; set; }
    public virtual IList Items { get; set; }
  }

  public class LineItem : Entity, IAmTenantSpecific
  {
    public virtual string SKU { get; set; }
    public virtual int Quantity { get; set; }
  }
}

We can now clearly see that Orders and LineItems are meant to be considered as multitenant objects. Since S#arp’s Repository<T> class doesn’t support switching databases on the fly, I need to create my own implementation class that will do this for me. I can inherit directly from Repository<T> and just override the bits I need.

 
namespace CheeseStore.Core
{
  public interface ITenantContext
  {
    string GetFactoryKey();
  }
}
namespace CheeseStore.Data
{
  public class MultiTenantRepository : Repository
  {
    private ITenantContext tenantContext;

    public MultiTenantRepository(ITenantContext tenantContext)
    {
      this.tenantContext = tenantContext;
    }

    protected override ISession Session
    {
      get
      {
        string factoryKey = tenantContext.GetFactoryKey();
        return factoryKey == null ? base.Session : NHibernateSession.CurrentFor(factoryKey);
      }
    }
  }
}

There are a couple interesting things going on here. First is the interface ITenantContext. You notice that it lives in the CheeseStore.Core namespace in a project of the same name. My application needs some way to determine what the tenant is, at this point I don’t really care how or where. I just want to define the contract that states that something will provide this bit of information for the Repository. Next, we have the MultiTenantRepository<T> it inherits form the S#arp provided Repository<T> implementation and simply overrides its Session property. This property relies on the tenant context to provide the key and then pulls it out of the S#arp provided session factory class. Finally, notice that the tenant context is provided though constructor injection. We will have to wire that up later once we have an implementation.

I can now easily create a Order specific repository like this:

namespace CheeseStore.Core.DataInterfaces
{
  public interface IOrderRepository
  {
    IList GetBySomeCriteria(int count);
  }
}

namespace CheeseStore.Data
{
  public class OrderRepository : MultiTenantRepository, IOrderRepository
  {
    public OrderRepository(ITenantContext tenantContext) : base(tenantContext)
    {
    }

    public IList GetBySomeCriteria(int count)
    {
      ICriteria criteria = Session.CreateCriteria(typeof(Order));
      return criteria.List();
    }
  }
}

This is exactly how the S#arp architecture documents instruct you to create a entity specific repository with a defining interface and implementation that leans on the base Repository class.

Next up we need a way to configure the S#arp NHibernate session factory factory with multiple configurations. This configuration is almost wired up for us already, we simply need to edit the InitalizeNHibernateSession() method in the Global.asax and add a couple tricky tweaks to the AutoPersistenceModelGenerator class to take advantage of our marker interface.

Here is the change to the Global:

    /// 
    /// If you need to communicate to multiple databases, you'd add a line to this method to
    /// initialize the other database as well.
    /// 
    private void InitializeNHibernateSession()
    {
      NHibernateSession.Init(
         new WebSessionStorage(this),
          new string[] { Server.MapPath("~/bin/CheeseStore.Data.dll") },
          new AutoPersistenceModelGenerator().GenerateCore(),
          Server.MapPath("~/Config/CoreNHibernate.config"));

      NHibernateSession.Init(
         new WebSessionStorage(this,"Tenant1"),
          new string[] { Server.MapPath("~/bin/CheeseStore.Data.dll") },
          new AutoPersistenceModelGenerator().Generate(),
          Server.MapPath("~/Config/Tenant1NHibernate.config"));
    }

Notice that I first initialize the default core session factory and then initialize a tenant factory providing an tenant key to identify them by. I could add as many tenants as I want right here. Also note that each factory uses a separate nhibernate.config file so you can tweak all you want. The final thing to notice here is the call to AutoPersistenceModelGenerator.GenerateCore(). This is the additional tweak I mentioned earlier.

We want to be able to configure each session factory with a different set of domain objects. The core needs only core entities and each tenant needs the full set of multi-tenant entities. Here is how I accomplished that:

namespace CheeseStore.Data.NHibernateMaps
{
  public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
  {
    private bool isTenantModel = true;

    public AutoPersistenceModel GenerateCore()
    {
      isTenantModel = false;
      return Generate();
    }

    public AutoPersistenceModel Generate()
    {
      AutoPersistenceModel mappings = AutoPersistenceModel
         .MapEntitiesFromAssemblyOf()
          .Where(GetAutoMappingFilter)
          .ConventionDiscovery.Setup(GetConventions())
          .WithSetup(GetSetup())
          .UseOverridesFromAssemblyOf();

      return mappings;
    }
   ...

    private bool GetAutoMappingFilter(Type t)
    {
      //see if the type is a tenant entity
      var tenantType = t.GetInterfaces().Any(x => x == typeof(IAmTenantSpecific));
      
      return t.GetInterfaces().Any(x =>
           x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>))
           && isTenantModel ? tenantType : !tenantType;
    }
    ...
  }
}

Here I have added a private member to indicate if we are generating a tenant model and a new method GenerateCore() that sets that property and calls the default functionality. I have also modified the GetAutoMappingFilter() method to divide my domain objects by the marker interface. Thus providing two totally different persistence models from one domain.

So far we started at the domain model and worked out way down to the data access layer. Next up we need to create a MVC Controller that uses our OrderRepository. No problem. It looks like every other controller with a dependency on a Repository.

namespace CheeseStore.Web.Controllers
{
  [HandleError]
  public class HomeController : Controller
  {
    private IOrderRepository orderRepository;

    public HomeController(IOrderRepository orderRepository)
    {
      this.orderRepository = orderRepository;
    }

    public ActionResult Index()
    {
      return View();
    }
  }
}

Notice that our controller knows nothing about the multi-tenancy work we have been doing. It requests a IOrderRepository and does what ever it needs to do with it completely ignorant of where the objects are being persisted or even how.

There is one thing left to do here. We still haven’t specified where the tenant context comes from. For this example, I will keep it simple and base the tenant id off of a query string parameter. It could just as easily be based on the domain or a sub-domain. Here is what that looks like:

namespace CheeseStore.Web
{
  public class TenantContext : ITenantContext
  {
    
    public string GetFactoryKey()
    {
      return HttpContext.Current.Request.QueryString.Get("tenantId");
    }
  }
}

It is that simple. This class actually lives in the ASP.NET MVC project. This allows the website to define how the tenant context is created.

If you are interested in taking a look at the complete solution you can download it here. A majority of what you see in the solution is auto generated by S#arp Architecture when you create a new project. So all credit goes to Billy and the other devs on S#arp for that. I have outlined my modifications above.


 
Categories: Development | NHibernate

January 9, 2009
@ 08:15 AM

I was reading Oren's excellent series of posts on Multi Tenancy located here. It seems like he is just building up a good head of steam when the posts stop. Was Multi Tenancy - Approaches and Applicability the last one in the series?

Before you jump on me for not utilizing my google skills, a query of "site:ayende.com Multi Tenancy" does not return anything I have not already read. Did he stop cold turkey in the middle of the series? Or did he switch his post title scheme?


Does anyone have suggestions on other sources for this kind of information? I am specifically interested in multi tenant applications with separate databases with nhibernate as well as DDD approaches to extensible schemas.


A pointer in the right direction would be greatly appreciated.


 
Categories: Development | NHibernate

I have the following solution project structure:

  • Application.Core.Entities
  • Application.Xtend.CustomerName.Entities

In the Core project I have an entity Customer defiend. In the XTend project, I have an entity defined that subclasses Customer named xCustomer (for lack of a better name at this time...).

The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart IRepository class will return a subclass of the core class instead.

I am attempting to map this relationship in NHibernate. Using Fluent NHibernate I was able to generate this mapping:

 

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   default-lazy="false"
                   assembly="NHibernate.Core.Entites"
                   namespace="NHibernate.Entites"
                   default-access="field.camelcase-underscore">
  <!-- Customer is located in assembly Application.Core.Entities -->
  <class name="Customer" table="Customers" 
        xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" column="Id" type="Int64">
      <generator class="native" />
    </id>
    <component name="Name" insert="true" update="true">
      <property name="LastName" column="LastName" length="255"
                type="String" not-null="true">
        <column name="LastName" />
      </property>
      <property name="FirstName" column="FirstName" length="255"
                type="String" not-null="true">
        <column name="FirstName" />
      </property>
    </component>
    <!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities -->
    <joined-subclass name="xCustomer" table="xCustomer">
      <key column="CustomerId" />
      <property name="CustomerType" column="CustomerType"
                length="255" type="String" not-null="true">
        <column name="CustomerType" />
      </property>
    </joined-subclass>
  </class>
</hibernate-mapping>

But NHib throws the following error:

NHibernate.MappingException: persistent class Application.Entites.xCustomer, Application.Core.Entites not found ---> System.TypeLoadException: Could not load type 'Application.Entites.xCustomer' from assembly 'Application.Core.Entites, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'..

Which makes sense xCustomer is not defined in the Core library. I took my quandary to the NHibernate Users mailing list and StackOverflow. After some helpful suggestions and pointers, I discovered that the solution was so obvious that I am somewhat embarrassed that I couldn't see it.

The hibernate-mapping attributes assembly and namespace are convenient short cuts that allow you to not have to fully qualify your class names. This lets you have the nice mark up , but the name attribute of both class and joined-subclass elements can take a fully qualified assembly name as well.

So the above broken mapping file can be fixed like so:

 

<joined-subclass name="Application.XTend.CustomerName.Entities.xCustomer, 
                 Application.XTend.CustomerName.Entities, Version=1.0.0.0, 
                 Culture=neutral, PublicKeyToken=null" 
                 table="xCustomer">
  <key column="CustomerId" />
  <property name="CustomerType" column="CustomerType" length="255" 
            type="String" not-null="true">
    <column name="CustomerType" />
  </property>
</joined-subclass>

This works as I expected it to. So I then took a look at the Fluent-NHibernate source and created a patch complete with working unit tests to resolve the issue and submitted it to the project.

So at the end of the day, I learned something about NHibernate and the Fluent-NHibernate team got a patch to resolve and obscure bug.


 
Categories: Development | NHibernate

Introduction

As you may have noticed, I have become interested in the concept of Object Relational Mapping and the NHibernate framework. One of the more painful/tedious aspects of using NHibernate is hand writing the xml mapping files. That is why I got excited when I heard that Jeremy Miller was open sourcing his mapping generation libraries.

FHLogo The Fluent NHibernate project is an effort to create a set of APIs that generate NHibernate mapping files using a fluent interface. I downloaded the source code from the Google Code Repository and quickly found myself adding fluent methods. I submitted my changes to the project and was accepted as a contributor.

One of the tasks identified by the project owner, James Gregory, was to create a quick start guide that easily fit into the NHibernate Quick Start section 1.3 Mapping the cat. I assigned the task to myself and start hacking some code.

Creating the Mapping Class

First, create a new class project QuickStart.Domain to hold  domain model objects that need to be mapped. To this assembly,  add the Cat class from the NHibernate quick start.

namespace QuickStart.Domain
{
    public class Cat
    {
        public virtual string Id { get; set; }

        public virtual string Name { get; set; }

        public virtual char Sex { get; set; }

        public virtual float Weight { get; set; }
    }
}

This is what the class looks like after a little ReSharper Code Clean Up loving.

Then add a second class project QuickStart.Domain.Mapping to hold  domain model mapping classes using the Fluent NHibernate library. Add references to both the FluentNHibernate.dll and the domain model library.

Create a new class in the mapping library called CatMap. This class will inherit from ClassMap<T> where T is the type you are creating the map for, in this case Cat. Create a constructor for the CatMap class. The constructor is where the mappings will be defined.

Because CatMap is an instance of ClassMap, you can begin using the fluent interface in the constructor right away.

public CatMap()
        {
            this.TableName = "Cat";
        }

The TableName property of the ClassMap object specifies the name of the table in the data store that stores the Cat class. This explicit setting of the table name is unnecessary. If one is not provided the API will assume the table has the same name as the class being mapped. So, for the rest of this example, it will be dropped.

The API offers several fluent methods for defining an identifier though the Id method of ClassMap. The Cat example uses the UUID generator which looks like this:

 

public CatMap()
        {           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");
        }
 

An identity column in SQL server would be mapped like this:

public CatMap()
        {
            Id(x => x.Id);
        }

These two examples take advantage of the new C# 3.0 syntax sugar lambda expressions. An explanation of lambda expressions is outside the scope of this article, but  tons of information is available on the topic on the web.

The remainder of the CatMap constructor uses the Map method of ClassMap to define the remaining properties of the class.

public CatMap()
        {
            this.TableName = "Cat";
           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            //non-nullable string with a length of 16
           this.Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            this.Map(x => x.Sex);
            this.Map(x => x.Weight);
        }

Both the Sex and Weight properties of the Cat class are mapped quickly with a single call to them Map method. You do not need to explicitly specify the type of your properties, Fluent NHibernate will infer it based on the type being mapped. The Name property has an additional two fluent calls to limit the length of the property to sixteen characters and to disallow null values.

Usage of this mapping generates the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
  default-lazy="false" 
  assembly="QuickStart.Domain" namespace="QuickStart.Domain">
  <class name="Cat" table="Cat" xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" column="Id" type="String" unsaved-value="0">
      <generator class="uuid.hex">
        <param name="format">B</param>
      </generator>
    </id>
    <property name="Weight" column="Weight" type="Single">
      <column name="Weight" />
    </property>
    <property name="Sex" column="Sex" type="Char">
      <column name="Sex" />
    </property>
    <property name="Name" column="Name" length="16" type="String" not-null="true">
      <column name="Name" />
    </property>
  </class>
</hibernate-mapping>

This mapping xml is a bit more verbose than the original example from the NHibernate quick start, but this post is being written using an alpha version of the Fluent NHibernate library. There is a lot of clean up and work left to be done.

Hooking It All Up

So, how exactly did I go from CatMap to generated XML document? There is currently no recommended methodology that I am aware of, but I am happy to share how I accomplished it.

I started by adding an interface to the Mapping library called IMapGenerator that looks like this:

namespace QuickStart.Domain.Mapping
{
    public interface IMapGenerator
    {
        string FileName { get; }
        XmlDocument Generate();
    }
}

 

FileName is defined in the fluent interface on the ClassMap class, I know I added it while writing this code ;). It represents the conventional name for the NHibernate mapping files. For example, We are mapping the class Cat so FirstName would contain the string "Cat.hbm.xml". Generate on the other hand, will be a wrapper around the ClassMap's CreateMapping method.

I then added the interface to the CatMap class. The final CatMap looks like this:

namespace QuickStart.Domain.Mapping
{
    public class CatMap : ClassMap<Cat>, IMapGenerator
    {
        public CatMap()
        {
             Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            Id(x => x.Id);

            //non-nullable string with a length of 16
            Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            Map(x => x.Sex);
            Map(x => x.Weight);
        }
        
        public XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }
    }
}

 

I now have a way to identify all my mapping classes using the interface. I wanted to be able to automatically get a list of all the classes that implement the IMapGenerator interface, so  created a helper class GeneratorHelper with a single static method GetMapGenerators. The class lives in the Mapping library and looks like this:

namespace QuickStart.Domain.Mapping
{
    public class GeneratorHelper
    {
        private const string GENERATOR_INTERFACE = "IMapGenerator";

        public static IList<IMapGenerator> GetMapGenerators()
        {
            IList<IMapGenerator> generators = new List<IMapGenerator>();
            Assembly assembly = Assembly.GetAssembly(typeof(IMapGenerator));
            foreach (Type type in assembly.GetTypes())
            {
                if (null == type.GetInterface(GENERATOR_INTERFACE)) continue;
                var instance = Activator.CreateInstance(type) as IMapGenerator;
                if (instance != null)
                    generators.Add(instance);
            }
            return generators;
        }
    }
}

This method uses reflection to locate and load the assembly that contains the IMapGenerator interface. It then iterates over the types in the loaded assembly and checks to see if the type implements the IMapGenerator interface. If a match is found, an instance of that class is created and added to the generators list.

Finally, I created a console application, QuickStart.Domain.Mapping.Mapper, and added a reference to my Mapping library. The implementation of my console app is fairly straight forward.

 

namespace QuickStart.Domain.Mapping.Mapper
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IList<IMapGenerator> generators =
                GeneratorHelper.GetMapGenerators();
            
            foreach (IMapGenerator generator in generators)
            {
                XmlDocument classMapXML = generator.Generate();
                classMapXML.Save(generator.FileName);
            }
        }
    }
}

 

The app calls the generator helper class to get a list of IMapGenerator objects which it then iterates over calling each objects Generate method and saves the result using the conventional name for mapping files. It works fairly well and I can add as many mapping classes as I need to the Mapping library and spin out xml any time I need.

Now where Fluent NHibernate becomes really interesting is when you decide to do away with xml mapping files all together. For a great example of this check out Zachariah Young's post, "Does the Fluent NHibernate create static XML mapping files?".


 
Categories: Development | Fluent Interface | NHibernate | Tools