Month: March 2009

NHibernate, collection with composite-id.

In the previous post we saw how to map an entity with a composite-id.

Well but now if you have mapped an entity in this way and you need to create a collection of this entity or maybe you have a related child class that uses this primary keys … you are in trouble! Smile

The way to solve the problem is very easy. First of a short example to understand what I’m talking about:

   1: class Foo {

   2:     public string name { get; set; }

   3:     public string lastname { get; set; }

   4:     public IList<childfoo> listofchild { get; set; }

   5: }

   6: class childfoo {

   7:     public string name { get; set; }

   8:     public string lastname { get; set; }

   9:     public Foo father { get; set; }

  10: }

Now the first class will be mapped in this way if we assume that “name and lastname are the primary keys”. (Also remember to override Equals() and GetHashCode()!!).

   1: <class name="Foo" table="[Foo]" schema="xxx">

   2:   <composite-id>

   3:     <key-property name="name">

   4:       <column name="[name]" sql-type="varchar" length="50" not-null="true"/>

   5:     </key-property>

   6:     <key-property name="lastname">

   7:       <column name="[lastname]" sql-type="varchar" length="50" not-null="true"/>

   8:     </key-property>

   9:   </composite-id>

   1: <bag name="listofchild" table="[childfoo]" inverse="true"

   2:    cascade="all-delete-orphan" generic="true" lazy="true">

   3:   <key>

   4:     <column name="[name]" sql-type="varchar"/>

   5:     <column name="[lastname]" sql-type="varchar"/>

   6:   </key>

   7:   <one-to-many class="Foo" not-found="ignore"/>

   8: </bag>

Now we can go back to the child mapping file and reference the many-to-one foreign mapping in this simple way:

   1: <many-to-one name="Foo" lazy="proxy" not-null="false">

   2:   <column name="[name]" sql-type="varchar"/>

   3:   <column name="[lastname]" sql-type="varchar"/>

   4: </many-to-one>

So now my repository will be able to give me:

image

And in that moment my repository will go back and execute the sub-select.

NHibernate and the composite-id.

I’m working with the new version (2.0 GA) of NHibernate. The problem I have encountered today is about the composite-id.

Let’s say we have an entity that doesn’t have a personal id field. We don’t want to use the GUID or any other auto id generator class. We must implement the primary key logic in the corresponding table in the database. Now, imagine to have this table:

Key Column Name SQL Type Not null
yes Field01 varchar true
yes Field02 varchar true
yes Field03 varchar true
yes Field04 varchar true

At this point we will have a mapping XML in NHibernate in this way:

   1: <class name="classname" table="[tablename]" schema="schemaname">

   2:   <composite-id>

   3:     ... ...

   4:     <key-property name="Field02">

   5:       <column name="[Field02]" sql-type="varchar" length="5" not-null="true"/>

   6:     </key-property>

   7:     <key-property name="Field03">

   8:       <column name="[Field03]" sql-type="varchar" length="5" not-null="true"/>

   9:     </key-property>

  10:     ... ...

  11:   </composite-id>

If we compile the DAL of our project, we will receive a fancy error:

“composite-id class must override Equals()”

“composite-id class must override GetHashCode()”

The explanation is very simple. We are saying that this class has 3 fields to implement a comparison so the NHB must know how you can compare these fields … and off course the CLR doesn’t know how to do it.

This is the solution in our entity:

   1: public override bool Equals(object obj) {

   2:     if (obj == null)

   3:         return false;

   4:     MyEntity t = obj as MyEntity;

   5:     if (t == null)

   6:         return false;

   7:     if (this.f1 == t.f1 && this.f2 == t.f2 && this.f3 == t.f3)

   8:         return true;

   9:     else

  10:         return false;

  11: }

   1: public override int GetHashCode() {

   2:     int hash = 13;

   3:     hash = hash +

   4:       (null == this.f1 ? 0 : this.f1.GetHashCode());

   5:     hash = hash +

   6:       (null == this.f2 ? 0 : this.f2.GetHashCode());

   7:     hash = hash +

   8:       (null == this.f3 ? 0 : this.f3.GetHashCode());

   9:     return hash;

  10: }

There we go!! Now you have implemented a full version of the method “Hey is this the entity I’m going to save or is this entity brand new?!?!”

Personal Consideration.

In my opinion NHB should be able to override this method by itself via reflection and not to ask you to rebuild thousand of entities if you want to use the standard pattern active Record.

UI Validation with the MVP pattern. #Part02.

For anyone of you that didn’t read the first part of this article (that I recommend) this is the address.

In this part we will go to build the UI layers, so the user interface, the presentation layer and the Windows form.

The user interface.

In the MVP pattern the interface in the contract that we want to share from the UI and the presenter. In our case we want to add to simple fields, the username and the password. This is a sample:

   1: public interface IUserView
   2: {
   3:     string Username { get; set; }
   4:     string Password { get; set; }
   5:     ///implementation ...
   6: }

Now we just have to reflect the two properties in our windows form in this simple way:

image

And this is the code coming from the view, because of course, in the MVP pattern our UI has to inherit the view.

   1: #region IUserListView Members
   2: public string Username
   3: {
   4:     get{return this.txtUsername.Text;}
   5:     set{this.txtUsername.Text = value;}
   6: }
   7: public string Password
   8: {
   9:     get{return this.txtPassword.Text;}
  10:     set{this.txtPassword.Text = value;}
  11: }

Now what we need is a method to send messages back to the user and then we can step into the presenter. So let’s declare a sendMessage method in the interface.

   1: void SendMessage(string message);

And the corresponding implementation in our Windows form:

   1: public void SendMessage(string message)
   2: {
   3:     MessageBox.Show(message, "Message", 
   4:     MessageBoxButtons.OK, MessageBoxIcon.Information);
   5: }

The presenter.

The presenter in the MVP pattern is the core of the UI. Of course everything has to be executed inside it, and the UI has only to call the corresponding method. Let’s build the presenter and the constructor:

   1: public sealed class UserViewPresenter
   2: {
   3:     IUserView view;
   4:     public UserListViewPresenter(IUserListView view)
   5:     {
   6:         this.view = view;
   7:     }
   8:     /// implementation ...
   9: }

So at this point we go back to the UI and declare and initialize our presenter …

   1: public partial class formUser : IUserView
   2: {
   3:     UserViewPresenter presenter;
   4:     public formUser()
   5:     {
   6:         InitializeComponent();
   7:         this.presenter = new UserViewPresenter(this);
   8:     }

Now we are fine and this is the normal way to use the MVP pattern. But what about the validation??

Validate the valid able …

Suppose that in your presenter you have a simple method called save that will be called by a button in your UI. What you have to do is to check the entity you are going to save, before save it!

   1: public void Save()
   2: {
   3: User user = this.view.SelectedUser;
   4: if (user.IsValid())
   5: {
   6:     ///save the entity
   7: }
   8: else
   9: {
  10:     this.SendValidationErrors(user);
  11: }

Because when we call the method IsValid() we already populate the list of errors in our entity, what we have to do now is to simple read them and build a message for the user:

   1: private void SendValidationErrors(User user)
   2: {
   3:     foreach (string error in user.ListResults)
   4:     {
   5:         this.view.SendMessage(error);
   6:     }
   7: }

This is just an example, not very well done, on how to use the UI validation in the MVP pattern. You can agree or you cannot. I always appreciate comments and idea to share.

In the next post I will show you how to build a more strong validation and a simple way to reflect the validation to every simple control of the Windows form with the error component.

UI Validation with the MVP pattern. #Part01.

This is the first of 3/4 posts about the implementation of the UI Validation in a Windows Form application using the MVP Pattern.

In order to be able to follow my article you must have and know:

  1. Microsoft Enterprise Library UI Validation, available at this link.
  2. Basic knowledge of the MVP pattern.

Analysis.

First of all I want to explain why I’m going to validate the domain and not the UI. The concept is that a validation represent a constraint on the data. In most of the case the UI layer is never fixed and stable, but for the domain, at most, we have to change a field or an entity, so less effort.

Second point, why I should contact a DAL layer and validate the entity if I can do it before and save some bandwidth and resources??

If we add the validation in the domain, in the future, we will be able to carry our domain everywhere without tacking care of problem like the validation. If we add the validation in the UI, our presentation layer will be strictly connected to our domain, and this is something we don’t want.

The basic object.

One of the most helpful technique in the OOP (object oriented programming) is the inheritance. We can build a basic class with some useful methods and properties and use it like a contract for the other inherited classes.

In our case we want to build a simple domain object class that will represent all the instances of our domain.

image

Let’s view the simple code to build this class.

   1: using System;
   2: using System.Collections.Generic;
   3: using Microsoft.Practices.EnterpriseLibrary.Validation;
   4: using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
   5:  
   6: namespace XXX.Core
   7: {
   8:     public abstract class DomainObject
   9:     {
  10:         private ValidationResults Validate()
  11:         {
  12:             Validator validator = ValidationFactory.CreateValidator(Type.GetType(this.ToString()));
  13:             ValidationResults errors = validator.Validate(this);
  14:             IList<string> list = new List<string>();
  15:             foreach (ValidationResult result in errors)
  16:             {
  17:                 list.Add(result.Message);
  18:             }
  19:             this.ListResults = list;
  20:             return errors;
  21:         }
  22:         public virtual bool IsValid()
  23:         {
  24:             return this.Validate().IsValid;
  25:         }
  26:         public virtual IList<string> ListResults
  27:         {
  28:             get;
  29:             private set;
  30:         }
  31:     }
  32: }

I have just create the set methods as private because I don’t want to modify them outside the domain object class. Of course anyone of you will have a different solution here. I must use virtual because I hardly use the NHibernate Proxy.

At this point we have just to inherit from this class, any entity of our domain, also the entities that should not be persisted. Why? Because the validation we are going to do now it’s very straightforward. Then decorate the entity with some attributes.

Note: I don’t know why and I have found a lot of concerns about this solution but actually the Enterprise Library doesn’t have a nice way to implement the inheritance directly and the only way to do that is to use the constructor that uses the reflection:

  12:Validator validator = ValidationFactory.CreateValidator(Type.GetType(this.ToString()));

The entity.

Now let’s build the first entity that will inherit form our domain object. It should be something like that:

   1: namespace XXX.Core.USER
   2: {
   3:     public class User:DomainObject
   4:     {
   5:         ///Class implementation
   6:     }

After that what we need? Of course the fields of our entity! In this case I use the NET Framework 3.5 lazy creation where you don’t have to declare the private accesses.

   1: public virtual int Id { get; set; }
   2: public virtual string Username { get; set; }
   3: public virtual string Password { get; set; }

Now let’s define some business validation rules:

  1. Each of these fields cannot be null.
  2. The Username cannot be lower than 5 characters and longer then 20.
   1: [NotNullValidator(MessageTemplate="Id cannot be null")]
   2: public virtual int Id { get; set; }
   3:  
   4: [NotNullValidator(MessageTemplate="Username cannot be null")]
   5: [StringLengthValidator(5,20,MessageTemplate="Username has to be from 5 and 20 charactersS")]
   6: public virtual string Username { get; set; }

There we go!

The decoration attributes.

The enterprise library offers a very nice and configurable solution for the UI validation. This list is only a part of them and you can also build custom group of validation rules.

  • ContainsCharactersValidator – Performs validation on strings by verifying if it contains a character set.
  • DateTimeRangeValidator – Performs validation on DateTime instances by comparing them to the specified boundaries.
  • NotNullValidator – Logs a failure when validating a nullNothingnullptr reference.
  • RangeValidator – Performs validation on T instances by comparing them to the specified boundaries.
  • RegexValidator – Performs validation on strings by matching them to a Regex.
  • StringLengthValidator – Performs validation on strings by comparing their lengths to the specified boundaries.

The next post will show you how to integrate this Framework (If we can call him a framework …) with the Presentation Layer.