Sunday, March 15, 2009

A New at Standard Mapping with Fluent NHibernate

As I continue my research this weekend I decided to get into understanding the basics of the various types of mapping we commonly see in data driven programming: one-to-many, many-to-one, many-to-many.

To start, here is the entity class for Series:

   1:  public class Series
   2:  {
   3:       public virtual int SeriesId { get; private set; }
   4:       public virtual string Name { get; set; }
   5:       public virtual Studio Studio { get; set; }
   6:       public virtual IList<Season> Seasons { get; set; }
   7:       public virtual IList<Genre> Genres { get; set; }
   8:  }

And now a look at the mapping file:

   1:  public class SeriesMap : ClassMap<Series>
   2:  {
   3:       public SeriesMap()
   4:       {
   5:            Id(x => x.SeriesId);
   6:            Map(x => x.Name)
   7:                .WithLengthOf(100).Not.Nullable();
   8:            References(x => x.Studio, "StudioId");
   9:            HasMany<Season>(x => x.Seasons)
  10:                .WithTableName("Seasons").WithKeyColumn("SeriesId");
  11:            HasManyToMany<Genre>(x => x.Genres)
  12:                .WithTableName("SeriesGenres")
  13:                .WithChildKeyColumn("GenreId")
  14:                .WithParentKeyColumn("SeriesId");
  15:       }
  16:  }

To begin lines 5 & 6/7 are calls to simple mapping functions to define the unique identifier for Series and the Name field.  The code on the subsequent lines instruct NHibernate what relationships exist and where to map the data.

The first call is to the overload for References which allows to not only specify which property of the mapped object to point at, but also what columns represents the foreign key (in this case StudioId).  This is enough to declare the declaration with the minimal amount of extra information.  Here is the code again:

Well take a step now and define the other side of a one-to-many relationships, using the HasMany function.  This function defines, in this case, that our Series has many Seasons.  We make a subsequent call to .WithTableName to dictate which table the collection will pull from (the type is declared via the generic parameter) and we define the column on THE JOINING TABLE that will indicate a match, SeriesId in this case.

The final type of relationship we will show is the Many-to-Many.  Most ORMs that I have dealt with have always had difficulty handling this sort of relationship so complexity needed to be introduced either on the configuration side or the development side.  In this case, we introduce a SLIGHT amount of complexity on the configuration side, but as you can see from the code, it really is minute.

HasManyToMany<Genre>(x => x.Genres)
     .WithTableName("SeriesGenres")
     .WithChildKeyColumn("GenreId")
     .WithParentKeyColumn("SeriesId");

To begin we make our call to the generically typed function HasManyToMany passing the type we are going after, in this case instances of the Genre class.  The call to WithTableName denotes which table is the intermediary in this relationship and the two column calls dictate what columns to look at with what we are going after and from where we are coming. Overall, very well simplified.

Initially I had a lot of trouble with this code because my queries kept breaking due to bad SQL generation.  I could tell the reason was because NHibernate was assuming a standard naming convention under the hood, that I was not using because this is a database that I use for many person projects; changing table names would break the other applications.  I finally consulted with @jagregory asking about the way one tells NHibernate that a different table name is to be used; I assumed it would be an attribute on the entity, but he indicated it was a simple method call, like such, within the mapping file:

   1:  public class SeasonMap : ClassMap<Season>
   2:  {
   3:       public SeasonMap()
   4:       {
   5:            WithTable("Seasons");
   6:            Id(x => x.SeasonId);
   7:            Map(x => x.Name).WithLengthOf(100).Not.Nullable();
   8:            Map(x => x.Position);
   9:       }
  10:  }

Line 5 is the key method call here, with the method inherited from ClassMap<T>.  I did send my suggestion to the Fluent Team that perhaps an attribute would be better suited, however, I think the way they have it is best from an extensibility standpoint so that I can reuse mapping code.

The one thing I would like to be able to do, and I have yet to find an ORM yet that can do this easily is weighted relationships. In the example above you see that a Series has many Genres, but what you don't see is that there is a weight associated with the Genre as the Series may be more Action then Drama for instance. The only way I can see to do this now with the ORMs that I have used is via two One-To-Many relationships with a derived class from the traditional Genre entity you see above. The weight value is stored in the SeriesGenres table along with the SeriesId and GenreId. If anyone has any ideas how to create this, please send a reply to @jfarrell on Twitter.

Saturday, March 14, 2009

Fluent NHibernate and a New Project

This week marked the end of my stint on one of the biggest projects we have had in the last year.  Things went very well, as the remaining members of the team begin to move into the final beta phase, I am being reassigned as a billable consultant to a company in Holland, MI. The upside of this assignment is I get to work with PHP which is one of the first languages I did serious programming in and was my forte in college.  Getting the opportunity to work with it for the first time since I became strictly .NET is going to be fun, challenging, and exciting; its an opportunity that I am very much looking forward to.  The only downside is my current 10m commute to work now becomes an hour long commute as I must be onsite in Holland, but I think its well worth it.

One of the other happenings is I have finally started to take a serious looking into NHibernate as something that RCM may go to from our current open source custom framework (The Kinetic Framework).  Its part of the normal aging process for a framework.  NHibernate is highly touted and looks to be a good alternative to using the still not ready for prime time Entity Framework.  However, one of the long standing problems with NHibernate, is configuration and that really is true for most ORMs that exist today.  Microsoft has generally released good tools built into Visual Studio to aid programmers in configuring the ORM products it releases, this is not the case for NHibernate.  To counter this, Fluent NHibernate was created that allows you to "fluently" define mappings for entity objects.

The main advantage behind this notion of fluent programming is that we take procedures that normally are relegated to external programming and bring them under the control of the compiler, to allow for easier compile time checking.  An example of this is Microsoft LINQ - where developers are able to querying databases (for example) using standard type safe C# code as opposed to passing a string off to a black box (the database) and magically getting a rectangular result set.

This is the same idea with Fluent NHibernate which removes the XML configuratioin files and allows you to define this configuration using C#, below is an example:

   1:  public class SeriesMap : ClassMap<Series>
   2:  {
   3:       public SeriesMap()
   4:       {
   5:            Id(x => x.SeriesId);
   6:            Map(x => x.Name).WithLengthOf(100).Not.Nullable();
   7:            References(x => x.Studio).TheColumnNameIs("StudioId");
   8:            HasMany<Season>(x => x.Seasons).WithKeyColumn("SeasonId");
   9:            HasManyToMany<Genre>(x => x.Genres)
  10:                .WithTableName("SeriesGenres")
  11:                .WithParentKeyColumn("SeriesId")
  12:                .WithChildKeyColumn("GenreId");
  13:       }
  14:   }

This being the mapping file, it would help to show you what the entity itself looks like:

   1:  public class Series
   2:  {
   3:       public virtual int SeriesId { get; set; }
   4:       public virtual string Name { get; set; }
   5:       public virtual IList<Season> Seasons { get; set; }
   6:       public virtual Studio Studio { get; set; }
   7:       public virtual IList<GenreWeight> Genres { get; set; }
   8:  }

Note that we define properties we want NHibernate to "fill" as virtual.  But take note of the correlation between the property names and the calls to properties in the mapping class.  The link below will provide more of a reference to the various calls available from the mapping class:
http://wiki.fluentnhibernate.org/show/HomePage & http://fluentnhibernate.org/

Once you have these classes in place you can use the standard NHibernate calls, either via the Criteria API or HQL (Hibernate Query Language) to extract your data. Also have a look at the Linq to NHibernate project. While it is still in its infancy stages it has great potential. I think Linq and NHibernate are actually made for each other as the DataContext pattern that Microsoft employs to track changes matches very well with the repository pattern employed by NHibernate, I look forward to some great stuff in the future from the meshing of these two technologies.

Saturday, March 07, 2009

Context Driven JavaScript Programming

First let me say that while I will be focusing on JQuery for the framework of choice, this can really be accomplished with most of the frameworks available.

The idea of context driven JavaScript programming is actually use JavaScript to do what you are intending and make things easier.  Many programmers often assume that JavaScript can do very little and thus create tremendous tasks for themselves when in fact the code is very simple if they would simply employ the concept of context and utilize what JavaScript is giving them.  Lets look at an example of some bad JavaScript:

  1: var selectBox = null;
  2: window.onload = LoadingFunction;
  3: 
  4: function LoadingFunction() {
  5:     selectBox = document.getElementById('selectGender');
  6:     selectBox.onchange = HandleChange;
  7: }
  8: 
  9: 
 10: function HandleChange() {
 11:     var value = selectBox.options[selectBox.selectedIndex].value;
 12:     alert(value);
 13: }

First thing I want to point out is that some of you may say, well why do I need to define my handlers in JavaScript, I can just define them in the markup and pass what I need. I would say, yes that does work, but its a mixing of your presentation and interaction layers and will get you into trouble as you work on larger more complex JavaScript driven processes.  But lets turn our attention to this code.  Seems alright, but lets rewrite it using context:

   1:  window.onload = function() {
   2:      document.getElementById('selectGender').onchange = function() {
   3:          alert(this.options[this.selectedIndex].value);
   4:      }
   5:  }

This is quite a few lines less then what we were using.  You see the use of the word this within an anonymous function assigned as event handler gives you a reference to the object firing the event, this allows you to easily use the same event handler over and over.  Using anonymous functions in this way also allows you to utilize scope convergence and include scope outside of the function, with static functions from the first example you would not have this ability.

  1: window.onload = function() {
  2:     var name = prompt("What is your name?");
  3:     document.getElementById('selectGender').onchange = function() {
  4:         alert(name + " is " + this.options[this.selectedIndex].value);
  5:     }
  6: }

Notice how name is declared outside the anonymous function but used inside without anything special. If you were to do this with the first sample of code you would need to make name a global variable or find a way to pass it to the function, using context you can have it passed automatically.  Now keep in mind this is a very simple example.  One of the places where I use this principle heavily and it shows its worth is client side binding.

The scope of these functions is "saved" to the runtime of JavaScript and thus can be referenced later on when an instance of the event is called.  I invite you to read more about my experiments with JQuery as this comes in huge when we start talking about data driven programming as it eliminates the need to store lots of data in hidden fields for client side operations.

As our final step with this code, we will introduce JQuery and see how it simplifies this code:

  1: $(document).ready(function() {
  2:     var name = prompt("What is your name?", "Fred");
  3:     $("select").change(function() {
  4:         alert(name + " is " + $(this).val());
  5:     });
  6: });

As you can see, the code is not that different from the previous example, but I do want to point out a few things.  First is $("select"); in this example we only have one so this query will return to us just that one instance and bind the event handler to the change event.  However, if we had more then one, then it would do this for each one - this is one of the things about JQuery that make it so great, being able to apple context specific event handlers en masse, this way. You also notice the simplified syntax for getting the value of the select box using the val() function. Finally the one weakness with the second example of code is the lack of graceful degradation.  In the case of JQuery, if the select box were somehow removed without removing the JavaScript, the page would still load error free, not the case with the JQuery-less code, thus you would need to employ a check to make sure you actually have an object to bind the event to, for example:

  1: window.onload = function() {
  2:     var name = prompt("What is your name?");
  3:     var elem = document.getElementById('selectGender');
  4:     if (elem != null) {
  5:         elem.onchange = function() {
  6:             alert(name + " is " + this.options[this.selectedIndex].value);
  7:         }
  8:     }
  9: }

Context driven programming has many advantages, but yet few use it heavily or near the level appropriate, why? Perhaps the biggest reason is laziness; both in desiring to understand and have the will to do it right, rather then quick and dirty. In the same way that it takes discipline to separate the layers of our web app and ensure that no SQL strings are ever found in a code-behind, so to do programming unobtrusive JavaScript.  Truthfully, unobtrusive is very difficult without a framework, as you see in the code above for the final example, but frameworks such as JQuery render this point moot and really shows the laziness of the person programming or perhaps their stubbornness with changing the way they program.

Additionally, most developers seem to scoff at the idea of a user browsing the site without JavaScript and in some cases its worked into the project contract that the is assumed to have JavaScript.  I find this silly, when really a simple toggle box that shows if JavaScript is not enabled performs the tasks quite admirably of steering off users who don't have JavaScript.  This is certainly better to the alternative.

Finally, most designers, if you ask them, are driven nuts by having their HTML littered with event handlers.  They do not belong here, they are not part of the presentation, they are part of the interaction, like entity objects and data access layers, they should be separated into their own layers so you can emphasis code reuse.

The last point I have heard made against this style of programming is maintainability. Some appear to feel that wiring up your events like I have shown above limits your ability to change if element names were to change.  There is certainly some truth to this, but context driven programming counters this with its emphasis on The Principle of Localization.  When you are coding your handlers correctly the brunt of the code that could change is concentrated in a single block, thus negating the need to scroll around making sure you found all the references.  Furthermore a framework like JQuery is very flexible in how it can query for elements, and understanding the ways you can do this is essential.  Simply knowing the basic selectors is not enough; in fact I have observed that if you start to break away from attaching to simply ids the code becomes more abstract and easier to change.  The downside is that because JQuery is designed to degrade gracefully, you will not see any errors when you are running, so your unit tests are not properly designed you may miss a bug.

The final thing I would like to say is that JQuery is and unobtrusive JavaScript are designed to work no matter how your elements are arranged or how many there are.  I have seen cases where programmers try interesting methods to mask the elements being passed, its a interesting method because it tends to result in ugly code that does not operate using context, all because they fear an element name changing.  Such an approach is very Web 1.0ish and quickly shows its limits when you start doing any kind of client side binding, which is very common in Web 2.0 apps.

One of the most important concepts Web 2.0 is bring us is that there is a dire need to understand how to architect our JavaScript in the application.  Most good developers understand the importance of properly architecting server side code (think of the number of patterns that exist), but there is a lack of understanding for architecting client side code. Understanding what you can make a function and what you should not will be critical along with understanding core JavaScript concepts like prototyping and JQuery concepts like extending.

To conclude, as the web continues to move forward in terms of the expectation for web site interaction JavaScript is becoming the front line fighter in creating the memorable experience people want.  The age of static JavaScript programming is coming to an end and is being replaced by context driven programming where developers leverage what the language gives them to make their code cleaner and more coherent. Though certain concerns exist about this new methodology most are simply borne from either worrying too much about the odd case, or a lack of desire to change on the part of the programming. With a framework like JQuery programming your JavaScript to be unobtrusive is easy and quick, further understanding how to leverage context in your code gives you an easy way to reference the elements you care about without tying your interaction to your design.  This makes changes easier and makes your code better and easier to understand for the next person.