Polymorphism and identifiers

Polymorphism makes you use truly unique identifiers. If you don’t agree, consider the following scenario:
Polymorphism diagram Imagine, that client wants you to create a registry (list view, whatever), that will enable him to query assets and apply different criteria onto them (there is not much in the interface, but name can also be queried with SQL like operator). You immediately notice, that you can use polymorphic queries from NHibernate, which spans to all implementations of the given interface. They can be some problems with the queries efficiency (paging is done in the memory), but skipping this fact, you’ve done it. You have your list of assets presented to the user, who instantly notices that there are a few rows with the same id. What’s going on, you ask. Ahhh, you’re still using the old-fancy db identity identifier generator. Not only it’s generates unique id per table, but also removes all the bonuses connected with batching inserts. How can you overcome such an obstacle?
The solution is simple: use GuidGenerator, especially CombGuidGenerator, as your IIdentityGenerator. If your customer hastes these 128-bit long chains, use HiLo algorithm, which stores within the process a package of identifiers ready to be used. Once they’re used, it goes to the db to transactionally get another one. Span this HiLo for all tables/entities hierarchies which can be queried in a polymorphic way. For the best result, set it for all entities’ types, and enjoy having unique long/int identifiers across your whole database.

Polymorphic count with NHibernate

If you’re a user of NHibernate, I hope you enjoy using polymorphic queries. It’s one of the most powerful features of this ORM allowing you to write queries spanning against several hierarchies. Finally, you can even query for the derivations of object to get all the objects from db (don’t try this at home:P). The most important fact is, that having a nicely implemented dialect NH can do it in one DB call, separating specific queries by semicolon (in case of MS SQL)

// whoa!
var allObjects = session.QueryOver<object>().List();

Although the feature is powerful, you can find a small problem. How to count entities returned by the query without getting’em all to the memory. Setting a simple projection Projections.RowCount() will not work. Why? ‘Cause it’s gonna query each table with COUNT demanding at the same time that IDataReader should contain only one, unique result. It won’t happen, and all you’ll be left with it’ll be a nice exception. So, is it possible to count entities in a polymorphic way? Yes! You can define in a extension method and use it every time you need a polymorphic count.

private static int GetPolymorphicCount(ISession s, Type countedType)
{
    var factory = s.GetSessionImplementation().Factory;
    var implementors = factory.GetImplementors(countedType.FullName);

    return implementors
        .Select(i => s.CreateCriteria(i)
                .SetProjection(Projections.RowCount())
                .FutureValue<int>())
        .ToArray() // to eagerly create all the future values for counting
        .Aggregate(0, (count, v) => count + v.Value); // sum up counts
}

Happy counting!

NHibernate EntityAwareModelBinder for ASP MVC

It’s time to provide some more features before getting deeper into detached actions for ASP MVC. The very first requirement is to have a nice model binder, which not only uses a container to resolve all the parameter types (my previous model binder), but also is intelligent enough to deal with an ORM of your choice. And mine is NHibernate.

Before getting the final snippet, a few assumptions has to be made:

  • No hierarchies are bound automatically. For sake of simplicity, we’re considering only simple entities with no derivations.
  • All the collections, which reflect one-to-many relationships, are bound in the inverse way. The one ending has its collection marked as inversed (there is a drop-down for the many ending, where the parent can be selected)

To provide you with a better way of viewing the code, I pushed the file to the gisthub and it can be located under: https://gist.github.com/984310. It’s good time to take a look into it.

As you can see, the binder does some pretty nice things:

  • It still uses container as the fallback for all the models. Using Windsor you’d better be sure to have all of them registered
  • If entity has its id passed, it uses session to get it; otherwise a new instance is created. It’s up to you to save it in your session

Maybe it addresses a few concerns, like handling entities and non entities in one binder, but it’d be easier to get the whole idea having one straight class without the whole projects.

This is my default model binder in my current project so far and it provides strong base for the detached actions mechanism, which will be covered in the very next entry.

Thoughts?

NHibernate’s No-Proxy Laziness

It’s been a while since last post, but I’m alive and still kicking, so let’s go deeper into another aspect of one of my most favorite libraries. Today’s entry is all about lazy-loaded properties.

The setup
Whether you use FluentNHibernate with its property of PropertyPart, allowing you to choose a property’s laziness, or you still use xml description of your entities, you’ve got three choices for setting the laziness of your to-one (many-to-one, one-to-one) properties, with the default set to the second:

  • false
  • proxy
  • no-proxy

The performance
The very first one is easy to understand: do not lazily load this property. I want it always, I don’t care about all the stuff with getting to much data, possibly fetching the whole database into my session (if you can traverse a whole mapping graph from your type, that might happen). Use it wisely and sparingly, only when you know that every time you get the one object, you want to have another.
The second is a default one, NHibernate takes care of you, getting only one entity at time. It’s good, allowing you to set fetches explictly every time you need in your query (IQueryOver, ICriteria, IQuery, etc.) The problem is, when a type of a specified property has any derivations and this leads us to the third option: having your properties lazily loaded with their types being not proxified at all.
The whole situation is well described in Ayende’s post. When, for instance, you three classes mapped: A, B (which derives from A) and X, and X has a property of type A, after having this property lazily loaded you cannot cast this to B, hence, the type being hidden behind this property is a proxy type, let’s call it PA. It’s obvious, since in the .NET there is no multiple inheritance, the proxy of A (PA : A) cannot derive from B as well. Once you set the no-proxy on your property, the problem seems to be gone. But how? What’s happened?

The prestige
The property of type A has been altered. Every time it is called, it is not a simple getter. It’s been wrapped to return A, but with loading it on demand, when a property is called for the first time. How it might happen? The class X is not a class X. It’s a proxy (PX), with all the properties’ types preserved, hence, your type checking or casting A to B works. The thing can get a bit more complicated if you want to serialize X to JSON and return it as a action result (PX is not the best serialization candidate; proxy adds a few bonuses) or downcast X, to another class. Although it seems to be very powerful, use it sparingly to not be overwhelmed with having everything proxyfied.

NHibernate interceptor magic tricks, the example

Below, you can find the final example of working interceptor, which uses some methods described in text of the last few blog entries (1, 2, 3, 4 and 5). Scan the example and go below to get some explanation about it!

public class ExampleInterceptor : EmptyInterceptor
{
	private const int MaxStatements = 50;
	private static readonly ILog Logger = LogManager.GetLogger(typeof(UpdateInterceptor));

	private readonly InterfaceFinder _interfaceFinder;
	private readonly IUnityContainer _container;
	private ISession _session;

	private int _statementCount;

	public UpdateInterceptor(IUnityContainer container, InterfaceFinder interfaceFinder)
	{
		_container = container;
		_interfaceFinder = interfaceFinder;
	}

	public override void PostFlush(ICollection entities)
	{
		if (_session.Transaction == null)
		{
			throw new InvalidOperationException("Use transactions!");
		}
		base.PostFlush(entities);
	}

	public override void SetSession(ISession session)
	{
		base.SetSession(session);
		_session = session;
	}

	public override string GetEntityName(object entity)
	{
		if (entity == null)
		{
			return null;
		}

		var interfaceType = _interfaceFinder.GetDeepestInterface(entity);

		if (interfaceType == null)
		{
			return null;
		}

		return interfaceType.FullName;
	}

	public override SqlString OnPrepareStatement(SqlString sql)
	{
		if (_statementCount++ == MaxStatements)
		{
			Logger.WarnFormat("Max number of statements exceeded");
		}

		return base.OnPrepareStatement(sql);
	}

	public override object Instantiate(string clazz, EntityMode entityMode, object id)
	{
		if (entityMode == EntityMode.Poco)
		{
			var sessionFactory = _session.SessionFactory;
			var metadata = sessionFactory.GetAllClassMetadata()[clazz];
			var type = metadata.GetMappedClass(entityMode);

			if (type != null)
			{
				var instance = _container.Resolve(type);
				var classMetadata = sessionFactory.GetClassMetadata(clazz);

				classMetadata.SetIdentifier(instance, id, entityMode);

				return instance;
			}
		}

		return null;
	}
}

The constructor
As you’ve noticed, there is a dependency injection in here! Two arguments are: unity container instance; interface finder, which allows you to use interfaces with their implementation hierarchies. About the second, you can read here and here.

Post flush
does nothing more than ensuring that you’re running it in a transaction. Yep, one for all, all for one!

SetSession
remembers the session instance in a field.

GetEntityName
implementation indicates that there are some interfaces mapped, for instance IA and IB : IA. It allows the most nested interface to be easily find for the object type.

OnPrepareStatement
preserves a sane number of statements per session (hence, per request, because session per request scenario is considered).

Instantiate
is the final method. It uses the passed container to create an instance of the passed class. Having interfaces mapped, it’s must have since you cannot call new for interface :P

Unity registration
Having this interceptor we need a nice and easy way of registering any interceptor (which type is hold in _interceptorType field) in the container. That’s performed by the following unity extension:

public class NhUnityContainerExtension : UnityContainerExtension
{
	protected override void Initialize()
	{
		// ...
		// save configuration to container for any later use
		Context.Container.RegisterInstanceWithSingletonLifetimeManager(cfg);

		// build factory and register interceptor
		var factory = cfg.BuildSessionFactory();
		Context.Container.RegisterInstanceWithSingletonLifetimeManager(factory);
		Context.Container.RegisterTypeWithPerRequestLifetimeManager(typeof(IInterceptor), _interceptorType);

		var key =  NamedTypeBuildKey.Make<ISession>();
		// setup nhibernate session build plan policy
		Context.
			Policies.
			Set<IBuildPlanPolicy>(
				new DelegateBuildPlanPolicy(
					ctx =>
							{
								// create interceptor already registered
								var interceptor = BuilderContext.NewBuildUp<IInterceptor>(ctx);
								var buildUpFactory =
									BuilderContext.NewBuildUp<ISessionFactory>(ctx);
								return buildUpFactory.OpenSession(interceptor);
							}),
				key);

		// setup lifetime policy
		Context.
			Policies.
			Set<ILifetimePolicy>(CreatePerRequestLifeTimeManager(), key);
	}
		
	private LifetimeManager CreatePerRequestLifeTimeManager()
	{
		// ...
	}
}

If you know the architecture of Unity, this extension is pretty safe explanatory, event mine extension methods.

That’s the end of Interceptor journey. Happy Intercepting!

NHibernate interceptor magic tricks, pt. 5

The previous parts of NHibernate interceptor journey can be found here: 1, 2, 3, 4. In this last entry I will describe all methods not covered previously. The example will be added as a separate entry as it needs a few more tests to be done, but hey! Now you’ll know something about all methods of IInterceptor! So, let’s start!

When dirt is flushed
When a session is flushed, there is a dirty check which is performed for each entity stored in the first level cache (in other words: a session cache or a persistent context). The dirty check is done by raising a FlushEntityEvent. The event object contains all the needed information about entity and is processed by a chain of event listeners. There is one default event listener for this type of event, called DefaultFlushEntityEventListener. It’s the one which is responsible for checking whether a loaded entity needs an update. It’s out of scope of this post to go deeper into NH event model, hence finally, when an entity is marked as to be updated, an update action is created. During this process, under certain conditions,
bool IInterceptor.OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types) method can be called. I tend to use event listeners rather than using this method, not dealing with flushing.

Lock ‘N Load!
This one will be pretty straightforward: bool IInterceptor.OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types); is called each time an entity object is being preloaded (passing an event through all IPreLoadEventListener). There are two cases when this happens: an entity is being assembled from cache and when an entity is being just loaded from its db representation. The state passed as the table of objects, is the state retrieved from db/cache (the representation is the same: an array of objects), and if modified, will affect setting the properties of your entity. For instance if we change state[i] which represents a property of name propertyName[i] and is of type types[i], it will cause this property to set to the value. Even more, the new value will be saved as the original state of an entity and the dirty check will not mark an entity as dirty.

Format me this, format me that
SqlString OnPrepareStatement(SqlString sql) allows you to change the sql string which is being sent to the db. You may replace some parts, as well as create an interceptor which will write the whole SQL of your web app to the trace. It’s also the easiest way to check how many times you app hits db (if an interceptor is created and attached on per session basis and the session is created once, per request, then you can easly count SQL statements executed per request). The other, much nicer and elegant, way of logging all statements is attaching an appender to the right ILog. BTW, this is what NHProf does!

On save, save?
bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) method is called when an entity is saved. As in many cases, the last three tables contains: object properties values, property names, types of the properties. The method returns bool, which indicates whether values from the state should be copied onto object properties. If you return false, although the state is changes, NHibernate will not be notified to copy these values. I tend to use proper event listeners IPreInsertEventListener and IPreUpdateEventListener rather then making IInterceptor more rigid.

Preflush, postflush, inflush, outflush…
void PreFlush(ICollection entities); and void PostFlush(ICollection entities); methods do what they destined to do. The first is called with an collection of all entities which state is going to be changed during the flush which is comming, the second, is called with an collection of all entities which state was flushed already. Want to customize logging for all objects flushed (NHibernate does it already!)? That’s the place you should go!

An example will be provided soon!

NHibernate interceptor magic tricks, pt. 4

It’s the very last but one entry of NHibernate IInterceptor series (the first three: 1, 2, 3). We traveled through a few first methods of IInterceptor. It’s time to end this travel.

Am I transient enough?
Being transient in NHibernate world means nothing more than being not-persistent ever. The entity which you create with your new operator is transient till you call ISession.Save(object entity) method onto it, hence making it persistent. The persistent entities are being tracked for changes, their state is being saved/updated. Creating a new entity object not attached to the session is nothing more than creating a new object. It’d be simply garbage collected if no attaching to the session, via the mentioned method, occurred. How NHibernate recognizes if an entity is transient? It uses a static (ugh, yeah, the static method!) ForeignKeys.IsTransient method, which first of all, delegates its execution to IInterceptor.IsTransient. If you find a more elegant and intelligent way of resolving ‘being transient’ than calling IEntityPersister.IsTransient here you are your entry point. I did not find it useful in my whole journey with NHibernate.

I am collection and I need some action to be performed onto me
The following three methods of IInterceptor:

  • void OnCollectionRecreate(object collection, object key)
  • void OnCollectionRemove(object collection, object key)
  • void OnCollectionUpdate(object collection, object key)

are called during flushing collections, when a session flush occurs. The first step of flush is flushing of entities, the second – flushing collections. When the collection flush occurs, for each collection, it is determined what kind of action should be executed against this collection. The three choices matches the names of the IInterceptor methods. It’s worth to know and read something more about IPersistentCollection interface which an implementation instance is passed as the first parameter. As it was in the IsTransient case, I did not use any of this methods either.

I am being deleted!
When a delete occurres, the very first thing NHibernate does, is calling IInterceptor.OnDelete(object entity, object id, object[] state, string[] propertyNames, IType[] types) method. It does not provide any flow control and is simply called by the default IDeleteEventListener before scheduling the real delete action. What one can do in here, is checking whether an entity can be deleted and, for instance, throw an exception if this operation is not permitted.

In the last entry I will provide the description of the last, few methods as well as an example of full-blown implementation of IInterceptor.