Archive for the ‘NHiberate’ Category

NHibernate 1.2.0 Alpha

July 20, 2006

This has been out for a little while… but I just thought I’d post a couple of bits I noticed in going forward.

1) Find is being deprecated – the new query stuff seems to look pretty tight and makes it heaps better – gives the comfort of some compile time checks which we all love 🙂

2) You now need to supply an interface for each of your mapped classes (well this is what I seemed to have to do when I recompiled my solution and ran it up). Fortunatelly I already had interfaces for each of my mapped classes but I had to add the following to the mapping file (the little proxy bit):

<class name=”Mappings.Client,TestConsole” proxy=”Mappings.IClient,Mappings”  table=”[Client]”>

 That seemed to get me to a point where I could just run my app that I had originally written on 1.0.2 🙂 Hopefully that helps someone else out there get there 1.0.2 stuff running smoothly on the new build 🙂


NHibernate – Find not returning a result?

July 20, 2006

I was having an issue with NHibernate a while back (which I fixed a while back :-P) – anyway – here’s the problem and a hopeful fix if anyone else has come across the same thing. Maybe it might be something to go into the NHibernate base… Although I noticed with the new 1.2.0 Alpha release Find is being deprecated so maybe this comes a little late but anyway… It might be something you also want to patch in as I did (into the 1.0.2 release and the 1.2.0 Alpha releases – it still exists in the 1.2.0 Alpha release) 🙂

 The problem was when I did a search over a entity and the field I was searching on contained both full stops(.) and commas(,), even though I could see the entity in the database, it wouldn’t return it – it would always say the entity didn’t exist (if I escaped it – rightly so – the fields wouldn’t match) but if I didn’t escape it it would start throwing exceptions – arrrhhh. For example, say I was looking for a company with the name “BigCompany, United.” using Find – I would get nothing (escaped) or would blow up (unescaped). What was going on? Time to bust out the source code 😀

 Here’s the query at fault:

array = (ArrayList)session.Find(string.Format(“from Business.Mappings.Company as company” +
      ” where company.Name = ‘{0}'”,

The problem exists down in the parsing of the find string. When it comes across commas and full stops it tried (if it wasnt escaped) to cast it to a class in the solution – if it failed to cast it would blow up. Trying to modify the source as little as possible, so everything else will stay the same, (theres some code down in here that really needs to be tidied up by the NHibernate crew – sorry guys) I did the following:

In the class ReflectHelper, in the method GetConstantValue I moved the try up 2 lines – so the exception will get caught and then the code that calls this will fall back on the “else” action (to pass the string through as a parameter – what we want). Here’s the modified method:

public static object GetConstantValue( string typeName, string fieldName )
        System.Type clazz = System.Type.GetType( typeName, false );

        if (clazz == null)
            return null;
            return clazz.GetField(fieldName).GetValue(null);
    catch( Exception )
        return null;

Drop that guy in and away you go 🙂 The problem is that with any extension dll’s they are compiled against a signed version of the NHibernate dll 😦 (which I dont have) To get around this I either had to recompile the extension packages from source – or – using reflector dissassemble the dll back to source so I could recompile it – or – in one case (where reflector was throwing hissy fits on some generics that were being used) dump the dll out to msil – delete the signed part form the msil code (its near the top of the file) and then reassemble it – turned out to be a little mission but fixed a bug that was really bugging me… Was good to get it solved 🙂

If anyone finds this useful then let me know/forward on a link to the Nhibernate guys… 🙂

NHibernate – SQL2005 Dialect

July 20, 2006

I had a random error happening the other day when I was running an NHibernate based app I was working on – the problem was the error (“Unable to perform find”) would only happen every now and it wasnt consistantly occurring in the same place. After a bit of digging I read a few other people where having similar issues – running on Sql2005 – something to do with the way 2k5 works with returning rows in certain block sizes… anyway I grabbed the Sql2005 dialect, compiled a dll and chucked it in – as I said the errors seemed to be sparatic… hopefully its fixed now but if anyone else is having the same problem then maybe give this a shot 🙂

 I originally got the dialect file off a link from Ayende Rahien’s blog:

I can’t find it now but I’m sure google might show you some love 🙂 If not then flick me an email and I’ll send you a copy…

In the config file you need to change the dialect setting:

<add key=”hibernate.dialect” value=”NHibernate.Dialect.Extension.MsSql2005Dialect, NHibernate.Dialect.Extension” />

Note the fully qualified class name and then the assembly name (the assembly you compile containing the new dialect will need to be referenced in the project or signed and placed in the gac) 🙂


June 9, 2006

Hmmm – time for a few blog posts I think… well some short ones just on a few random bits and pieces I've played with (in amongst the busy but boring times at work lately 🙂 ). One product I had a bit of a play with about a month ago is Vanatec's OpenAccess. While I don't agree with some of there statements regarding NHibernate I did think it had a few pretty good features (they just need to be finished/extended). If your playing with NHibernate then this maybe worth a look at too just as a comparison.

One thing that is pretty cool is how smoothly it integrates into Visual Studio along with the "in the box" reverse engineering option – no need for bamming out your own generator 😉 – basically from inside Visual Studio you can point it at a database and you get your initial cut of classes to work with… thats pretty cool as you can try something pretty quickly – im not sure how good/robust it is for use in a real world scenario though – Ill leave that up to you 🙂 . Theres also a few other bits like web service support etc (its in there but to me still looks to need some work) which is nice to see but is not really as complete as I would like it to be – no doubt it will continue to be extended 🙂

The model seems pretty easy to work with and it does seem to work but one thing I didnt like was debugging it – sometimes it wasnt that intuative (and there seems to be some j# / java going on under the scenes (its been a while since I fired it up) – but its not that cool to see .java.lang… throwing out errors when your running on .net 🙂 )

 Anyways – not really here nor there on it but it is worth a bit of a play with if your looking around at O/R mappers and have been investigating NHibernate. They have a free trial download so install it, read the help, look at the samples and see what you think 🙂

Castle Project

April 10, 2006

I’ve been meaning to post about this stuff for weeks but I can’t seem to find the time so just go here and check it out for yourself 🙂 It’s definitely worth the effort! In particular I was loving the Active Record pattern/generator they have built to sit over NHibernate. I could’nt get the generator gui to work (seemed to be broken) but I may have just been having “one of those moments” at the time 🙂

It seems to be getting better and better – lots of examples in the solution and it seems to be pretty self explanitory at how the basics work – if you have written an NHibernate solution then there’s no doubt you will love this – if you havent then it’s probibly not a bad idea just to grab this guy straight off the bat 🙂

NHiberate Configuration

March 4, 2006

One of the things that kind of confused me when I first started with NHibernate was the configuration and session factory etc. With the use of the NHibernate Contrib package the code in the configuration section changes a little.

(btw an excellent book to read is Hibernate in Action by Christian Bauer and Gavin King if you are just starting out with NHibernate – although Hibernate is the java version with NHibernate being the .Net port the Hibernate examples, patterns, help etc are all VERY relevant – you do the same stuff with NHibernate – this was something I didnt realise when I first started out so if your checking out NHibernate then google Hibernate because that will probibly throw up the answer you are looking for 🙂 )

Anyway, back to configuration – when you use the attribute package load the classes mappings use something like the following:

NHibernate.Cfg.Configuration nhConfig = new NHibernate.Cfg.Configuration();

using (Stream s = new MemoryStream())
     HbmSerializer.Default.Serialize(s, typeof(Business.Mappings.Team));
     s.Position = 0;

_nhFactory = nhConfig.BuildSessionFactory();

If you arent using the contrib package and are using xml mapping files then make sure the mapping file is included as a resource in the project and then replace the whole using block with: nhConfig.AddClass(typeof(Business.Mappings.Team));

Here I prefer to load one class at a time rather than the whole assembly because if you havent remembered to include the xml mapping file as a resource then that class map wont be loaded and it wont be obvious why (you’ll be stumped at why something isnt working / isnt saved – so easy to miss) and if there is a problem with a mapping you know exactly where to look – when you load the entire assembly at once you just get told theres an error but it may not tell you where – very hard to fix – when you load them one at a time it will point you straight to the class with the problem 🙂

Another tip here is NOT to call nhConfig.Configure(); If you call this it will go looking for an xml configuration file for the NHibernate settings rather than looking in the App.Config. You dont want any other configuration files to look after (or maybe you do – its up to you) so just let it do its thing and it will look for the nhibernate configuration section in your App.Config 🙂 (just make sure its in there of course)



NHibernate – Generics

March 4, 2006

 Following on from my last post here’s what I found and how I used the package at for generics in NHibernate 1.0.2 and 1-many type relationship mappings:

Your variables need to follow a particular naming notation (otherwise it will complain that it cant find it). This can be overridden but I found it was just easier to make sure that your classes followed the default expected notation which is: underscore followed by a small letter followed by anything else eg: _oTeam, _riders etc would be valid member variables – _OTeam, m_riders etc would be invalid. Pretty simple since thats probibly the notation most people use anyway but it is something to watch out for 🙂 There are two classes you should know about to just get something running with generics at the very minimum. EntityRef of T and EntityList of T.  At one end of the relationship you will have the collection (in the example this is in the Team class and the collection is of type Rider), In the team class we have something like:

private EntityList _riders;

and in the default constructor you would have:

public Team()


_riders = new EntityList(

delegate(Rider o) { o.OTeam = this; },

delegate(Rider o) { o.OTeam = null; });


The first part of the delegate is what happens when a rider is added to the teams riders collection (links it up) while the second part is when the rider is removed from the teams riders collection (breaks the link). So now you dont need to do any special linking code in other methods – you can get rid of those .AddX methods 🙂 (I hadnt thought about using this so I was like – oh yeah – good thinking 🙂 )

You need to use delegates in the default constructor to setup the adding / removing functionality for the collections – once you start using them you get to understand what is going on but at the start you may be like – say what? If you have any other constructors then just use a : this() to make sure the default constructor is called and all these delegates are setup each time 🙂

The attribute markup for the collection would be (note the Access attribute and lack of setter):

[NHMA.Bag(0, Lazy = true,
                     Inverse = true,
                     Cascade = NHMA.CascadeStyle.AllDeleteOrphan,
                     Access = “NHibernate.Generics.GenericAccessor, NHibernate.Generics”,
                     Name = “Riders”)]
[NHMA.Key(1, Column = “TeamID”)]
[NHMA.OneToMany(2, ClassType = typeof(Rider))]
public IList Riders
       get { return _riders; }

In the riders class we need the other part of the link. This is where the EntityRef comes in.

private EntityRef _oTeam;

In the Rider constructor we also need to setup some delegates (note the Add/Remove):

public Rider()

           _oTeam = new EntityRef(
                     delegate(Team o) { o.Riders.Add(this); },
                     delegate(Team o) { o.Riders.Remove(this); }

and then finally the attribute markup for the team would be something like the following (note the .Value, the type  – Team not EntityRef, and the Access attribute):

[NHMA.ManyToOne( Name = “OTeam”,
                Access = “NHibernate.Generics.GenericAccessor, NHibernate.Generics”,
                Column = “TeamID”,
                NotNull = true,
                ClassType = typeof(Team) )]
  public Team OTeam
           get { return _oTeam.Value; }
           set { _oTeam.Value = value; }

So as you can see – a few tricks to get this one working but it does work – just reference the dll and away you go. Should keep fill the gap while the NHibernate 2.0 effort is underway 🙂 The source code and the tests/examples at the svc source are a good place to start to see what is available and how something is done. If you havent got an svc client then a good one can be found here : (thanks JD!)

NHibernate – Generation, Attributes, Nullables, and Generics

March 4, 2006

Over the past few months I’ve been working on a little generator which will generate a thin layer (classes, data access objects, configuration etc) that will sit over NHibernate from a database schema and allow you to work against a particular database. Its pretty simple at the moment – Just point and click go. As I’ve learnt a bit more about it and found out some of the little tricks here and there I’ve gradually extended the template to a point where it is pretty solid (as always theres still some ironing out to do). The things I’ve been integrating into the generation template so far have been:

1) Using classes decorated with attributes (this attribute package is found in the NHibernate Contrib package) rather than the xml mapping files. I decided that the xml mapping files where just something extra to look after in the solution – I thought the less the better. The attributes on the other hand do make these base classes a bit messy but I figured I should never have to look at the generated code – The classes should just be there to use. Although generating the mapping files from the database/inserting attributes like this is really chucking out a whole heap of functionality that NHibernate will allow, I figured I could go back at a later time and extend the generator to provide a richer model. At the moment I just purely want a single class to table mapping and it should just all work.

2) Adding support for Nullable types (I’m using a dll I found called NHibernate.Nullables2.dll – not the one in the NHibernate Contrib package. This can be found here: This is a very cool package as it allows us to use the new .Net 2.0 nullable type notation eg. bool? _flag; in our code/base classes but in the attribute or mapping fies declare it as a special type like: NullableBooleanType 😀 Whats cool here is that from our program side of things these types are transparent while from the NHibernate side of things it understands what we are talking about. And using it is so easy – just reference the dll and change the type in the mapping file :-D. Here’s at example of using NHibernate.Nullables2 with the attribute package:

[NHMA.Property( Name = “RiderNumber”,Column = “RiderNumber”,NotNull = false,TypeType = typeof(NullableInt32Type) )]public int? RiderNumber{get { return _riderNumber; }set { _riderNumber = value; }}

 On the other hand when you use the Nullable package from the contrib you have to use the special types throughout your program code – not very nice 😦

3) Adding in the support for generic collections. This has been what I’ve been working on for the last week or so after work (when I can), and after playing around a bit I have it working – not as nicely as I would have liked but working none the less. The package I used to provide support for generics can be found here: (this is a cool blog too – add it to your feeds if you have one 🙂 ).

The reason putting generics in there was so important for me was that I’m working in .Net 2.0 and then suddenly with NHibernate only under 1.1. I had to go back to using IList – as the developer you have to remember what is in that collection when you come to use it. Generics on the otherhand provide a strongly typed collection IList of T so when you come to use it you know exactly what it is! No casting exceptions for me :-). To get this to work is not the easiest (not hard – but more a case of looking at an example and then just copying it) and then fixing the errors that come up when you run the app up. I’ll give an example of these bits and pieces in another post since this ones getting pretty long …

4) Working on adding enumeration suppport to the generation process – this is working but I’ll keep you posted once I have tested it and used it a couple of times in some app’s I’m working on at the moment 🙂