A Case We Shouldn’t Use Stored Procedure’s In

Filed Under (Development, NHibernate) by Emad Alashi on 09-06-2009

Tagged Under : , , ,

We are working on this big project at work in which several teams are assigned to different modules. The modules are, naturally, overlapping in certain areas where they they need to interact with each other through API’s.

One of these modules is central and crucial to the rest of the modules, the dependency is very high that the team has to provide many API’s. Certain API’s was needed by different modules; our team needed a list of entity X, and another team also wanted a list of entity X, BUT…we had different criteria!

For example, Entity X had an Enum property called “Type”. The API provided a parameter to filter on this Type, but the options were limited to couple of choices; either you get entities of THIS type, or you get all entities.  If you needed type A and B only, you will have to get all the entities in the database, or make two hits to the database and join the two lists.

A solution was to give all the various options to the user as optional parameters some of which was Array of values. This resulted in an ugly API signature that had many optional parameters, and when ever a new criteria is needed, the signature would change and break all the already existing calls for the API, and I will not even imagine how the SP would look like!. An ugly alternative as well is to create new SP for each different criteria. Both choices are maintenance killers.

In such cases, the dynamic queries are just wonderful; depending on the properties the end user needs to filter on, a query will be created dynamically with proper operator passed. Usually ORM engines, or similar engines, will provide you with an “internal language”, e.g. SubSonic:
——————
Episode  ep = new Select().From<DA.Episode>().Where(“Title”).Like(“SOA”).ExecuteSingle<DA.Episode>();
—————-

Another example is the “query by example” in NHibernate (code snippet is taken from NHibernate help):
——————-
IList episodes = session.CreateCriteria(typeof(Episode))
    .Add( Expression.Like(”Title”, “SOA%”) )
    .List();
—————–

And, of course, LINQ:
—————–

var episodes = from x in db.Episodes where x.Title.Contains("SOA") select c; ---------------

Or you can build your own ;) .

I hope this gives an insight.

Importance of Documentation

Filed Under (Bunian, Development, NHibernate, software management) by Emad Alashi on 26-12-2008

Tagged Under : , ,

 

documentation

Lately we have decided in Bunian to move on to NHibernate 2.0, and the contributor assigned to the move started out, only to send an email one day after: “THERE IS NO DOCUMENTATION!’.
We had errors as a result to the move which couldn’t be fixed without a documentation explaining why this happened.

After searching for a while, we found two resources of the new documentation:

Neither links were included anywhere in the NHibernate zipped file.

I didn’t realize how important a documentation is until it stopped us from moving on in our project; Only after we made sure that the documentation is available we decided to move on to version 2.0. The lesson to be learned is that if you are an enthusiast developer and want to add another piece of code to the world, keep in mind that your project is not only code; it is people, resources, community, ease of use, documentation, and any other simple thing that people need while you think it’s not important.

Of course I couldn’t find developers or contributors to open source projects greater than the NHibernate team, having such a project in the first place is awesome, and I thank each and everyone of them. I hope one day I can really contribute back to NHibernate. Thanks again guys.

HttpApplication EndRequest Event Invoked Many Times In Single Request?

Filed Under (Bunian, Development, NHibernate) by Emad Alashi on 14-12-2008

Tagged Under :

The other day I was putting the last touch of a temporary way to manage the NHibernate session (ISession) in Bunian. So part of the task was to bind a method to the HttpApplication EndRequest event (in the Global.asax.cs file) like the following:

public override void Init()

{

       this.EndRequest += WorkContext.NHibernateSessionManager.Instance.HttpRequestEnded;

}

By doing this, at the end of each page request the NHibernateSessionManager.Instance.HttpRequestEnded() will be called and I can clean the session then. But to my surprise this method was called at least 10 times!! So I thought maybe the Global.Init() method is called many times for some reason and I ended up binding the same method to the EndRequest event many times, so I set a breakpoint at the Global.Init() method and…it’s called one time only.

That was strange, ok so it’s only the HttpRequestEnded() mehtod that is called many times, but I am requesting only one page!! how come there are 10 requests!

So I opened Firefox which is already “armed” with the magnificent add-on Firebug, and I requested the page again, Firebug showed the following:

CropperCapture[1]

And that was it!! the page contained 10 resources (1 CSS file and 9 images), OH! so it is one page, but for each resource referenced on the page you get a request, hence a raise of the EndRequest event.

I couldn’t love Firebug more; I am not only happy that I wasn’t doing something wrong, but yet I learned something new about the ASP.NET internals. awesome.

Introduction to NHibernate Session at Jordev Was Good

Filed Under (Development, Misc, NHibernate, Personal) by Emad Alashi on 05-12-2008

Tagged Under : , , , ,

The feedback was very good, and I was glad that everybody liked it. Jordev is really moving ahead, and I am very excited being part of it :)

Below is the slide show (it’s an enhanced version from my previous one):

[slideshare id=821222&doc=introductiontonhibernate-1228487480885456-9&w=425]

Code is the same of the previous one which you can download from here

My First Talk at JorDev .net

Filed Under (Development, Misc, NHibernate, Personal) by Emad Alashi on 21-11-2008

Tagged Under : , , , ,

JordevLogo  nhib-logo04

JorDev .net is a .net user group founded by enthusiastic Jordanian IT professionals. On Wednesday the 26th of November I will be doing my first session of a series about NHibernate.
Details of talk is here:

Overview NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform. it provides an easy to use framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.NHibernate is free as open source software that is distributed under the GNU Lesser General Public License
Target Audience .NET Developers, Software Designers, Software Engineers, Software Architects
Date Wednesday, November 26, 2008
Location MIC (Microsoft Innovation Center, Royal Scientific Society Building, 3rd Floor)
Time 6:30 pm – 8:30 pm (Amman-Jordan local time)
For More Info Mohamed Saleh @0788716457
Ayman Farouk    @0795727344
Reminders Â
image006Live Calendar
image002Facebook event
image004Outlook Calendar
image008Google Calendar

NHibernate possible bug in IQuery.List<T>()

Filed Under (Development, NHibernate) by Emad Alashi on 22-09-2008

Tagged Under :

recently, we had to clean the database from all the testing data, when an error similar to the following appeared:

The value “” is not of type “System.Nullable`1[System.DateTime]” and cannot be used in this generic collection

The code I executed was:

            IQuery query = DbManager.MySession.CreateQuery(“select max(dateObject.EndDate) from DateDomain dateObject”);

            IList<DateTime?> list = query.List<DateTime?>();

When I debugged NHibernate code, I reached to the following AddAll() method in the ArrayHelper class:

  152 // NH-specific

  153         public static void AddAll(IList to, IList from)

  154         {

  155             foreach (object obj in from)

  156             {

  157                 to.Add(obj);

  158             }

  159         }

You can find the explanation of the error here.
Which brings us to the interesting question: why the implementation of IList Add method doesn’t consider the “nullability” of the T object? and why the parameter is of type IList ?!

 Am I missing something? should I report it as a bug?

NHibernate Inverse attribute

Filed Under (Development, NHibernate) by Emad Alashi on 22-08-2008

Tagged Under : , , ,

I had to read documentation, articles, many blog entries and go into discussions with colleagues… all to get the root of this ambiguous attribute of NHibernate, it is trickey!
This blog entry is another trial to explain the attribute, but with taking one more detailed step into the explanation.

NHibernate is meant to persist objects as well as to manage their relations to each other, lets take a look at the following example of Parent and Child classes:

public class Parent

    {

        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual IList<Child> MyChildren { get; set; }

    }

    public class Child

    {

        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual Parent MyParent { get; set; }

and we have corresponding tables to these two classes like the following:

Parent

Child

(note 1: as we are proceeding that there is no Null constraint on the ParentId foreign key in the Child Table)
Finally, we check the interesting part of the mapping files:

  1. Parent:

    <bag name=MyChildren table=Child cascade=all>

          <key column=ParentId/>

          <one-to-many class=Child/>

  2. Child:

    <many-to-one name=MyParent class=Parent >

          <column name=ParentId/>

        </many-to-one>

(note 2: all what the cascade=”all” attribute in the MyChildren bag does is that when ever you save the Parent, all the Child objects in the MyChildren collection are forced to be saved as well; and we are only talking about the Save operation; not interfering or changing any of the values of the Child properties)

Now if we execute the following code:

Parent par = Session.Get<Parent>(8);

            Child ch = new Child();

            ch.Name = “Emad”;

            par.MyChildren.Add(ch);

            Session.Save(par);

As you may expect, both objects “par” and “ch” will be saved due to note 2 we mentioned above, but the surprise is that when you check the values in the database, you will see that the ParentId field was set as well although we didn’t set it explecitly in the code!

dbValues

The reason is that there is a hidden attribute called “Inverse” in the bag part of the Parent map file whose default value is “false”; when this attribute is set to false like the default value, then the Parent says: “Oh, so it is my responsibility to maintain the relationship with my child objects, ok then when ever a child is added to my collection, when I am saved…I will perform an update SQL statement to their foreign key to point at me”

So when the Save is called, the “par” object is saved, and the “ch” is inserted because calling Session.Save(object) when the object is new it will be inserted.  And after all that happens, an explicit update SQL statement will be executed to update all the child objects to set the foreign key ParentId to the par object Id.

This goes all fine in our case, only due to note 1 (scroll up again); we don’t have an Null constraint on the foreign key ParentId, so the Insert statement is excuted without exceptions, but in most cases in the world, DBA do put this constraint, by that we will get a “cannot insert Null value in ParentId” exception!

The solution is to set the Inverse attribute to “true”, which means that the Parent will NOT updated the Child objects foreign key, it will only call Session.Save(ch) due to the cascade attribute, so the result will be like the record 6:

dbValues2

But then how to solve this problem?! we want to set the value of ParentId AND be able to preserve the Null constraint; so we need to set the MyParent property of the Child to the Parent “par” like line 4:

    1 Parent par = Session.Get<Parent>(8);

    2             Child ch = new Child();

    3             ch.Name = “Emad”;

    4             ch.MyParent = par;

    5             par.MyChildren.Add(ch);

    6             Session.Save(par);

and to make it graceful, we can create custom collection for the Children and in the Add method of the collection we set the passed Child objects property MyParent to the parent.

You can download the code sample here.

I hope this is detailed enough to explain what the Inverse attribute exactly is, how to go about the Null exception, and to understand that the attributes “Inverse” and “cascade” are different things.

Mapping Enumeration of type int in NHibernate

Filed Under (Development, NHibernate) by Emad Alashi on 19-08-2008

Tagged Under : , , , ,

I wanted to map an integer enumeration type in NHibernate, I googled “mapping enumeration in NHibernate” and the best explanation was of Jeremy Miller in his post here.

But as it appears (and according to my understanding) that the enumeration type should be mapped to a database column of characters type (varchar, char,…etc).
What if the database column was int? well…do exactly like what jeremy did except simply use “NHibernate.Type.PersistentEnumType” instead of “NHibernate.Type.EnumStringType“.

The sole purpose of this post is that I didn’t find this solution fast enough on google, so I hope it helps others faster.

My “Introduction to NHibernate” presentation and slides

Filed Under (Development, NHibernate) by Emad Alashi on 02-07-2008

Tagged Under : , ,

I have delivered the presentation I talked about in my previous post here.

Actually it was pretty simple and straightforward, the slides them selves don’t have code content; all the code was shown in VS directly (I always found it better to see the code in its really environment to better understand).
The attendees were handful, but if felt really great when they expressed how excited they were about the whole thing.

You can find the Power Point slides and the sample code in the following zipped file:

http://www.freedrive.com/file/395364,emadnhibernatepresentation.zip

I intend also to share with you the process I went through in order to conclude to the presentation in its final state.

I hope you benefit from it :)

Update: I did this presentation again with enhanced slides, you can find those slides on this post

Columns’ case-sensitivity in NHibernate

Filed Under (Development, NHibernate) by Emad Alashi on 28-06-2008

Tagged Under : ,

The other day I wanted to create an HQL query to retrieve data from one object (WorkOrderFault) that has many-to-many relation with another. so I created the following:

ISession session = NHibernateOrmSessionFactory.CurrentNHibernateSession;

IQuery query = session.CreateQuery(

   “select wof from WorkOrderFault wof join wof.WorkOrderTechnicians as tech where tech.Id = 43334″);

IList<WorkOrderFault> objects = query.List<WorkOrderFault>();

The query ran successfully, and I got my results.

Then I wanted to use paging and get certain amount of results starting from certain record, so I added these two lines directly after I instantiated the IQuery object :

query.SetMaxResults(10);

query.SetFirstResult(0);

Simple and nice, but instead I got the following error:

System.Data.SqlClient.SqlException : The column ‘FaultId10_’ was specified multiple times for ‘query’.

When I checked my mapping file of WorkOrderFault, it had the following lines (I am including the lines we are interested in only):  

<property name=FaultId type=System.Int32 column=FaultID not-null=false access=field.camelcase-underscore/> 

<many-to-one name=Fault class=GRP.Maintenance.Domain.Settings.Faults column=FaultId

                fetch=select insert=false update=false not-found=exception

                access=field.camelcase-underscore/>

Ok, I know it’s wrong to map the same column for two different properties (don’t ask about the reason), but this is the current situation; one property to hold the Id (as an integer), and another property to hold everything. There might be more justifying situations where you want to map two properties to one column, so let’s assume it’s ok.

NHibernate is smart enough, when using queries, to query the database field only once; in situations like this NHibernate figures out that there are two properties mapped to one column so it shouldn’t retrieve it twice (i.e select columnx as x1, columnx as x2…..).
But not in this case!! It just didnt’ work!

I had no explanation for this, except when I looked closely to the map file, I noticed that the field that was causing the problem “FaultID” was written once with capital d (D), and the other with small d (d)!

So as it appears, NHibernate has schizophrenia when it comes to database columns case sensitivity; because SQL itself is case insensitive, but NHibernate code distinguishes between the uppercase and lowercase.

Keep an eye on your map files, try to make them EXACTLY the case like the database is, and unify that through all your map files.

UPDATE:
the effect SetMaxResults() produced is it wrapped the original SQL sentace with “WITH query AS (…“, and only then the SQL refused the duplicate columns in the result, hence the SQLException took place.

original SQL: “select workorderf0_.RecID as RecID10_, workorderf0_.WorkOrderID….

SQL after SetMaxResults: “WITH query AS (SELECT TOP 10 ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__,  workorderf0_.RecID as RecID10_…