Monthly Archives: January 2009
NHibernate – Lessons Learned
As usual doing a Hello World using a technology turns out to be quite simple. It’s only when you start getting into serious stuff, you run into issues & of course learn a lot. I am sharing few of my learning’s on NHibernate over last month. The DB I am using is Oracle which makes these observations more important as there is a lot available out there on NHibernate but only with SQL SERVER.
1) Optimistic locking: NHibernate has an element called <version>, defined right after ID which can handle concurrency for you. I used a TIMESTAMP column in oracle & mapped it to a DateTime property in my C# class.
<version column=”ROWVERSION” type=”DateTime” name=”RowVersion” />
Now when you insert an entity containing version as above, NHibernate would automatically generate the TimeStamp for you & on update it will also do an automatic comparison. If you need to catch the Exception arising out of this issue, it would be StaleObjectStateException.
2) Cascade issues: A good description of why / what are cascades can be found here, though there are still few issues you will run into. Consider an entity called Class, which has a many-to-one relationship with professor.
<many-to-one name=”Professor” column=”A_PROFESSORID” cascade=”none” lazy=”false” />
For unidirectional associations like many-to-one (there is no one-to-many back), it makes sense to assign “none” to cascade, otherwise you will see superfluous updates. In this scenario, whenever you modify class attributes / properties, it will fire updates for Professor.
Though you still may not be able to completely get rid of superfluous updates. Let me put up one more scenario. I have a Department & I have a Class (one-to-many). Now for this you would keep cascade=”all” for obvious reasons as a save / update /delete to Department should also save / update / delete Classes. But if you modify only a single property of department you will still end up updating all classes
. I hope such superfluous updates will be removed with upcoming versions.
In case you require a soft delete (which is the case for many applications, maintaining an IsActive Flag), you can keep cascade option as “Save-Update” in parent (one-to-many).
3) BiDirectional / UniDirectional navigational relationships / associations: If you want to define a one-way only traversal through NHibernate you may not be quite successful. Say, a department has classes (one-to-many). Now if your DB (Domain) says that classes can’t stand on their own they have to always belong to a department then you are in a fix. You must provide a bidirectional reference so that whenever you create a new instance of a class, you can bind it to Department.
E.g.
public virtual void AddUniversityClass(UniversityClass universityClass)
{
if(_classes == null)
_classes = new ObservableList();
universityClass.Department = this; //BiDirectional, Class has a department & department has classes
_classes.Add(universityClass);
}
If you don’t do above your insert of Class would fail as they would have a null foreign key for Department. Sounds obvious but looks more like database structure affecting your object model (navigation), which you normally don’t want. Yet some may argue in favor of it, citing benefits of explicit constraints. One way could be making your navigation relationship (many-to-one for instance) private.
4) For collections don’t forget inverse=”true”: Why? I could have elaborated but it’s already explained here. This tells that responsibility for updating the column value is on the other side (just specifying inverse=’true’ on the collection <one-to-many> association).
5) Oracle supports batching through adonet.batch_size: This was confirmed to me by Ayende and Tomer. Batching would club the CRUD statements & send them to DB at one shot giving decent performance gain. The only thing I don’t like here is the attribute name. After all if the batching is done for oracle also, why call it adonet.batch_size? It was confusing for me atleast
. Also this works only with ODP.NET.
6) Use fetch=”join” for one-to-many & many-to-one relationships: This is to avoid select N + 1 problem. In my infancy stage of programming I use fall into this trap (limited knowledge of SQL
). N.B. outer-join attribute is deprecated.
7) Always use Criteria queries unless you need to do a projection: Criteria Queries are easier to read, they leverage on configuration files (e.g. fetch=”join”), & they safely handle parameters (developers run into concatenation of parameters using HQL). But alas you can’t use Criteria Queries everywhere. For instance if you need to fetch only few fields of a given entity (no associations, only selected properties for a lookup display), HQL is the only way out.
E.g.
string hqlQuery = “select new Department(D.ID, D.Name) from Department as D”; // Your class needs to have this constructor along with the default one
IQuery _query = Session.CreateQuery(hqlQuery);
IList _list = _query.List();
var observablelist = new ObservableList();
foreach (Department department in _list) { observablelist.Add(department); }
N.B. Projections are of utmost importance in NHibernate. Try to avoid bringing any unnecessary data to the client even if you have to resort to untyped objects. You can use a reader like loop to create your typed object graph & throw that graph back to client.
8 ) Many-To-Many doesn’t work with extra columns: Many-To-Many is normally expressed in database with help of third table. Though NHibernate doesn’t require a corresponding class for the third (mapping) table, but if third table contains additional columns other then the primary keys of involved tables, NHibernate won’t be able to support them. Solution we found was to move those additional attributes from the third table to the involved tables.
9) Components are of good value: To be frank I ignored the components completely when I started with NHibernate. In fact the whole concept of Entity vs. Value objects wasn’t clear to me even after going through DDD books. I mean, I got Value objects don’t require an identity but how does that affect my programming. But boy, I was wrong. I could have elaborated on the same here, but would request you to go through Hibernate in Action section 3.5 (starting page 92-93).
10) unsaved-value is important: You can use it to specify default values for columns. NHibernate also uses it to distinguish between new & modified entities.
E.g. Session.SaveOrUpdate(“Department”, department); //unsaved value would be used here to determine whether to do an insert or update. My Id reads as below for Oracle:
<id name=”ID” column=”A_ID” unsaved-value=”0″>
<generator class=”Infrastructure.GenerateID, Infrastructure” /><!– GenerateID is a class that implements IIdentifierGenerator interface, in my case it returns a GUID. There is no identity column in Oracle !–>
</id>
11) NHibernate supports database views: You can have a mapping file point to a database view as well. I normally use it for summary display (complex queries). Ensure you check your performance before getting into it (especially no where clauses attached). Views typically won’t have an primary column but your mapping file would still required one for ID element. So you can pick a column of your choice which is unique and make it part of ID by removing the same from property mapping. You can point generator class to native (an easy way to get away).
<id name=”_year” column=”YEAR” unsaved-value=”0″ access=”field”>
<generator class=”native” />
</id>
12) Parameterized Queries: If you are using NHibernate ideally you would talk to underlying DB with Criteria queries, HQL or raw SQL. NHibernate supports safe parameter passing in all of them as show below:
a) Criteria Queries: ICriteria criteria = Session.CreateCriteria(typeof(Post), “P”).Add(Expression.Eq(“P.PostId”, postId));
b) HQL or Raw SQL: s.CreateQuery(“from Post p where p.Title = :title”).SetString(“title”,”NHibernate”).List();
You also need to add a line to NHibernate configuration as discussed here – <property name=’prepare_sql’>true</property>
13) NHProf: Finally you should use NHProf to improve your understanding on the way NHibernate works.
I would appreciate your observations on above points.
Unit Testing Links
I have been using Unit Testing for quite some time now. So I thought to collect some good links on it, for anybody who is about to embark this journey.
One such link is this, which does a nice differentiation between unit testing, integration testing & system testing.
Another awesome article is here and a small follow up on it.
I am not sure if I should include this one, here, but i will do it just to indicate the importance of unit testing.
This one is an interesting way of naming unit tests.
I would appreciate if you can append the ones which have helped you.
Inside WPF’s DependencyObject & DependencyProperty
This is one of my older post, which I would like to copy here. WPF programmers (& also WF programmers) would have heard the names of these 2 classes. It’s quite easy to take these 2 classes for granted (unless you are into custom control or custom activities creation). The lines below provide some motivation from WPF perspective & also clearly differentiates between both classes. I found them useful, so thought of copying it here. Hope you find it too
.
————————————————————————————————–
If you have spent some time drilling into WPF you are bound to run into 2 classes – DependencyObject & DependencyProperty. They two together provide the base for underlying Property System of WPF. It’s well documented that DependencyObject is nothing but a glorified hashtable, but the same holds true for DependencyProperty too.
For e.g. have a look at following code:
public class Person : DependencyObject //CTRL + K + X -> Insert snippet shortcut for inserting Dependency Property
{
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof (string), typeof (Person));
public string Name
{
get
{
return (string) GetValue(NameProperty);
}
set
{
SetValue(NameProperty, value);
}
}
}
The function that caught me in the above code was DependencyProperty.Register – What the heck is that doing? On probing further I discovered that DependencyProperty maintains a Hashtable internally called PropertyFromName. PropertyFromName is where all the dependency properties of WPF are stored. A property is uniquely identified on basis of it’s name & owner. For instance if you try to register another property in the above code (may in a different class) with the same name & owner type (that is Person) you will get an ArgumentException. DependencyProperty also stores other attributes like default value of the property (e.g. every Person can have a default name called ‘Unknown’).
E.g. Person.NameProperty = DependencyProperty.Register(“Name”, typeof(string), typeof(Person), new PropertyMetadata(“Unknown”));
Let’s focus on DependencyObject now. DependencyObject itself internally maintains an hashtable. DependencyObject contains 2 important methods called GetValue & SetValue which are used to retrive values from the internal hashtable. The hashtable comes into play when you try to modify the default value of DependencyProperty. For e.g. the default name of every person is let’s say ‘Unknown’ & you are setting it to your name. So the value you are giving goes & sits inside the DependencyObject’s hashtable. Important thing to note here is in many cases the value may not be explicitly set by you but the value may be derived from surroundings. E.g. let’s say the creator of class Button has set it’s default background to white & you haven’t explicitly set the background but when you run the application you see that background color is black. Now this may be due to Operating System’s theme you have selected. Hence many developers refer to DependencyObject as a value engine.
So the question that comes to mind is why such complexity was required in first place? Answer is quite simple. If this properties weren’t dependency properties then would have been normal .NET properties allocated per instance. Dependency properties are created per type & can be customized if required (like per instance). So if your screen has 20 buttons you storage space for properties occupied is as good as for one button. Of course things can change if all the properties of buttons are modified for all 20 buttons which is a very rare scenario.
How about calling this a sparse storage design pattern
?
Enhancing Team’s Productivity – .NET, VS.NET
Software projects normally have a scary deadline. One way to meet them is to increase your team’s productivity. I am going to jot down few practices I have been following, & look forward to read the ones you follow:
1) Using Macros for VS.NET repetitive tasks: I normally have a complex VS.NET folder Structure & this structure gets repeated for every module added. For instance creating a new module in my current solution requires you to create about 10 folders, starting from DTO, Factories, Domain Model, Exceptions, etc. This took quite a bit of time of developers about start a new module. So I created a VS.NET macro to automate this task.

2) Code Generators: I have seen many companies having a framework wherein they take care of common tasks starting from transactions to Workflows, etc. Their implementation normally revolves around Factory method or Template method patterns. If you follow this approach, using code generator you can create “Fill-In-The-Blanks” template for your developers. I don’t have a framework like this, but I have still created few code generators. I normally use NHibernate for my projects. Given it’s a fantastic tool, it takes sometime to generate mappings & corresponding classes which again might be error prone. I have created a code generator which not allows you to create mappings & classes but also creates Factories & Repositories for entities that are generated. (N.B. You can find one alternative approach to mapping files here).
3) Extracting Code Snippets: I use Snippet Designer a lot to extract common code patterns & insert them with zero effort. This definitely saves a lot of valuable time.

4) Tools: Though they cost we can’t program without them
– ReSharper, CodeRush, etc. I personally use ReSharper. You can also check out plugins available for these tools. You can find a good plugin here.
5) Design Techniques: I normally prefer making cross cutting concerns oblivious to developers. This includes things are Security, Transactions, Logging, etc. They help in reducing lot of developer’s key strokes. You catch my recent article on same here. You can also use techniques like Visual Inheritance, though it’s tough to get it right with WPF (for a way out you can look here).
6) Keyboard Shortcuts: Although minor this can save lot of mouse clicks. The ones I use most frequently are CTRL + K + D (Alignment), CTRL + K + C (Comment), CTRL + K + U (UnComment), F12 (Navigate to a type) (though I prefer ReSharper shortcuts over above). An awesome way to speed up with XAML editing in VS.NET is this.
7) Proper Training: I guess all of us understand the importance of this but the level to which we get it is always less. I would also recommend productivity trainings once you master the basics of a technology / framework. I have written about one such technique here.
8 ) Appropriate Hardware: I pity the developers running on 1 GB Ram with VS.NET 2008, SQL Server, Oracle, etc. (even 2 GB is less).
9) Shared knowledge base: When working with a team you find many issues are recurring. A issue solved today by one developer is faced tomorrow by another developer. Keeping a shared knowledge base for team definitely boosts productivity.
10) Builds that always work: Integration of local working copies can consume a lot of valuable time of your projects. Normally developers have a tendency to get away with their check in. Have an hour per day where developers can integrate their work (or you can have couple per week). You can automate the build to save more time, but I leave it as a personal choice considering competency & cost involved.
11) Holidays/Working hours/Re-creation: Hmm… May be I am getting into aspects which I shouldn’t be not to mention salary. So I will stop here.
Let me know what you do to gear up your team’s producitivity
.
HAPPY NEW YEAR
Happy new year, Guys
. Sorry for being late on this one. I intended to first publish a long pending article as a small new year gift. Finally the article is up & you can see it here. It talks about applying AOP with Unity on NHibernate. It doesn’t contain ground breaking stuff, but it was exciting personally to connect these diverse pieces. Hope Unity would bring DI & AOP into the mainstream of .NET development (I have used Spring.NET in past for these techniques).
As part of new year I have chosen new hobbies, Photography & Automobiles to be precise. I guess its imperative to start each year with a new productive hobby which stimulates your mind towards a new joy. I will have few posts on my new hobbies soon.
Though I started this blog only in June (previous was here) below are my top posts (going by number of views) for last year:
Total Posts: 27 (
– Improvisation required)
1) Debugging an XBAP / WCF application – Windows Vista + VS.NET 2008
2) Issues using Workflow with Code Separation (.xoml)
3) Installing Team Foundation Server (TFS) on Windows 2008
4) WCF Certificate Security with XBAP / IIS Issues
5) Logging Best Practices
Keep Rocking
.
