NHibernate 2.0 beta1 was release a couple of days ago, so I thought it was time to go through some more new stuff that has been added since version 1.2.  I found a new useful helper class named CritieraTransformer which can be used to clone ICritiera queries. This is very useful if you want to perform multiple queries with small variations (in the where clause for example). It also has a useful function that adds a row count projection to a query.

Example:

var customersCritiera = session.CreateCritiera(typeof(Customer));
var totalCustomersCritiera =  CriteriaTransformer.TransformToRowCount(customersCritiera);

var inGroupCriteria = 
  CriteriaTransformer.Clone(customersCritiera)
    .Add(Expression.Eq("Group", group));

var goldenInGroupCritiera = 
  CriteriaTransformer.Clone(inGroupCriteria)
    Add(Expression.Eq("IsGold", true);                          
                
IList results = session.CreateMultiCriteria()  
     .Add(inGroupCriteria)
     .Add(goldenInGroupCritiera)
     .Add(totalCustomersCritiera)
     .List();

IList inGroupCustomers = (IList)results[0];
IList customers = (IList)results[1];
IList counts = (IList)results[2];
int count = (int)counts[0]; 

The multi criteria feature allows you peform multiple database queries in a single database call, the downside is that the IMultiCritiera interface does not support generic lists.

ASP.NET MVC Preview 3 was released today and while browsing through the code I saw something which I have seen before but never really reflected on.

protected internal ViewResult View() {
    return View(null /* viewName */, null /* masterName */, null /* model */);
}

protected internal ViewResult View(object model) {
    return View(null /* viewName */, null /* masterName */, model);
}

See how they have an inline comment with the argument name for the null arguments? This is a really nice practice as it makes function calls where nulls are passed much more readable and understandable. Functions that take in objects that can be null or booleans can often be very cryptic since you don't know what argument they represent. In some languages like ruby you can optionally name arguments:

def View(model)
  return View(viewName: nil, masterName: nil, model: nil)
end

For functions taking in booleans you have the option to instead use an enum, this can in some cases make function calls a lot more understandable. For example:

FileStream stream  = File.Open (“foo.txt”, true, false);
FileStream stream  = File.Open (“foo.txt”, CasingOptions.CaseSenstative, FileMode.Open);

For parameters that can be null you could instead use the null object pattern but this might not be feasible in many scenarios so I think that having a short comment like in the first code snippet is a nice way to handle this.

image

A couple of weeks ago I finished a great book named The Language Instinct: How the Mind Creates Language by the psychologist and cognitive scientist Steven Pinker. It is not a book directly related to programming, but if you are interested in languages (be that human or computer languages) or just popular science in general I think you will enjoy it. It covers the theory that all human language share a common universal grammar, and that this grammar is innately encoded in the human brain.

It goes into great detail on how children learn language, a feat that every human child do by just listing to adults talk. The book can be quite technical with a lot linguistic jargon sometimes, but it is still very readable. I really like the chapter about how creole languages evolve from pidgin languages.

A pidgin language is (wikipedia):

A pidgin is a simplified language that develops as a means of communication between two or more groups that do not have a language in common, in situations such as trade. Pidgins are not the native language of any speech community, but are instead learned as second languages.

A pidgin is a language with a very simplified or non existent grammar which require a lot of context to be understandable (like physically pointing to what or who are are talking about). A creole language is a well defined and stable language that has evolved from a pidgin language. A popular theory (the one discussed in the book) describes how creole languages are created by young children learning a pidgin language as a native language, and in that process creates a more complex grammar, with fixed phonology, syntax, morphology, and syntactic embedding. I think it is amazing that children can create a fully developed language in only a single generation.

The book also covers the evolution of the human language ability, how languages change over time and how brain damage effects speech and speech recognition.

Sorry for a post about non .net/programming, but I just wanted to share this, and yes I was reading this book when I came up with the title for this blog, oh.. and while I am at it here are some other great popular science books that I read recently which I can highly recommend:

There is new project on codeplex called BooLangStudio that adds Boo as supported language in Visual Studio 2008. It is still in it's infancy but the basics are there, Class Library and Console Application projects are support, as is basic syntax highlighting. The project was created by Jeff Olson, but there are other contributors, for example James Gregory who has begun porting over some intellisense support from his Boo Visual Studio plugin.

The progress is looking good:

image 

 

I have been wishing for some Boo visual studio integration for a long time. I thought I would try to contribute to BooLangStudio, however the source is on github. That means I had to learns some Git :)

It wasn't that bad actually, I downloaded msysgit and followed this Guide. The cool thing about Git is it's distributed nature which makes it very different from Subversion. The first thing I did, since I wanted to contribute was to fork Jeff Olson's repository. This is very simple, just register on github and you click the fork button:

image

When you fork a github repository you get your own remote repository that you can push commits two. After I had created my fork I could ask git to create local clone of that repository. Git does not have local "working copies" but local full repositories. This means that you can view history logs, do commits, merges, branching all locally, without any network connection.

When I had done a commit I did a push to my github remote repository. Github has very nice commit/diff visualizations:

 image

 

In your local repository you can configure a list of other remote repositories that you can pull from (pull = fetch+merge). I noticed that James Gregory had a fork where he committed his initial work on intellisense, and I wanted to try this out. So I created a local branch, added James Gregory's fork as a remote repository and pulled his changes into that branch. The cool thing is that merging in git keeps the complete history of the commits you merge, it almost looks like James Gregory committed directly to my repository.

Everything is done at the command line, there is a TortoiseGit in the works I think but I am not sure what state it is in. Here is an example of how you can merge changes from a remote repository:

$ git remote add jagregory git://github.com/jagregory/boolangstudio.git
$ git checkout -b jagrefory/master
$ git pull jagregory master
$ git checkout master
$ git merge jagregory/master

Github has a very cool network graph that shows forks and commits and where they came from:

image

The red dots on my line represents the commits that I merged from the jagregory branch. If you hover over a a dot it will show the commit info! Git and the whole concept of a distributed source control system is very cool and interesting. The usability aspects are not quite there yet, it's a lot of git commands and parameters to learn, and it takes some time to get how the concepts work.

At developer summit in Stockholm a couple of weeks ago I attended a great talk by Jim Webber titled "Guerrilla SOA". On one slide he listed some causes for why SOA and ESB solutions quickly degrade to a pile of spaghetti.  One of the causes was that developers take:

"The Path of least resistance for individual applications"

This line really resonated with how I feel, not in a SOA scenario but for application architecture or just code in general. When you write code you constantly fight either your own design/architecture or some framework and what many developer end up doing (including me sometimes) is taking the path of least resistance, and depending on the application design this might often not be the right path.

Ayende had a post a couple of days ago about zero friction & maintainability in which he writes:

"As it turn out, while code may not rot, the design of the application does. But why?

If you have an environment that has friction in it, there is an incentive for the developers to subvert the design in order to produce a quick fix or hack a solution to solve a problem. Creating a zero friction environment will produce a system where there is no incentive to corrupt the design, the easiest thing to do is the right thing to do.

By reducing the friction in the environment, you increase the system maintainability"

A big goal when designing an application or framework should be to make the path of least resistance the right path. This is of course easier said than done and I think you will never get the perfect design where every right way is the easy way. So when we head down the path of least resistance knowing it is the wrong way, why do we do it? It could be time constraints, plain laziness or some other hurdle. When making the decision it is important to weigh in possible future problems and maintainability issues that could potentially be very costly.

Well that is all I had to say about this for now, stay away from the path of least resistance (unless it is the right path!).

There is a new framework in the NHibernate Contrib project named NHibernate.Validator. The project began as port of the java Hibernate.Validator project and is started by Dario Quintana. This framework allows you to validate objects in a similar way to other validation frameworks except that it has out of the box integration with the NHibernate's entity lifecycle. This means that you can configure it to do validation on entity insert/updates. The integration with NHibernate is not required however.

You can specify the validation rules either as property/field attributes directly in the code or in a separate xml file with a schema similar to that used in NHibernate mapping files.

Example:

public class User
{
  public virtual int Id
  {
      get { return id; }
  }

  [NotEmpty, NotNull]
  public virtual string UserName
  {
      get { return userName; }
      set { userName = value; }
  }

  [Email]
  public virtual string Email
  {
      get { return email; }
      set { email = value; }
  }

  [Past]
  public DateTime CreatedDate
  {
    get { return createdDate; }
    set { createdDate = value; }
  }

  [Min(18, Message="You are to young!")]
  public int Age
  {
    get { return age; }
    set { age = value; }
  }

  [CreditCardNumber]
  public string CreditCardNumber
  {
    get { return creditCardNumber; }
    set { creditCardNumber = value; }
  }
  
  ///... 
}

If you don't like to clutter your code with attributes you can use the xml config option, example:

<nhv-mapping xmlns="urn:nhibernate-validator-1.0">
  <class name="NHibernate.Validator.Demo.Winforms.Model.Customer, NHibernate.Validator.Demo.Winforms">    
    <property name="FirstName">
      <not-empty/>
      <not-null/>
    </property>    
   
    <property name="Email">
      <email/>
    </property>

    <property name="Zip">
      <pattern  regex="^[A-Z0-9-]+$" message="Examples of valid matches: 234G-34DA | 3432-DF23"/>
      <pattern  regex="^....-....$" message="Must match ....-...."/>
    </property>    
    
  </class>  
</nhv-mapping>

Personally I can barley stand the NHibernate xml mapping files (don't like to poke around in xml files that much) so I think I prefer the attribute version. But it is nice to have this option. It makes it possible to validate objects in third party assemblies that you do not have the code for. There are many more validators than the ones used above and it is very easy to create custom validators.

You can configure the validation engine in code or in app/web.config, this is how you can do it in code:

NHVConfiguration nhvc = new NHVConfiguration();
nhvc.Properties[Environment.ApplyToDDL] = "false";
nhvc.Properties[Environment.AutoregisterListeners] = "true";
nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";
nhvc.Mappings.Add(new MappingConfiguration("NHibernate.ValidatorDemo.Model", null));

ValidatorEngine validator = new ValidatorEngine();
validator.Configure(nhvc);

Since NHibernate.Validator uses the event listener system I think you have to use NHibernate 2.0 if you want the NHibernate integration. To validate an object you simply use the Validate function, here is a simple example (using MonoRail):

public void Create([DataBind("user")] User user)
{
  InvalidValue[] errors = validator.Validate(user);

  if (errors.Length > 0)
  {
    Flash["errors"] = errors;
    RedirectToAction("index");
  }
  else
  {
    repository.Create(user);
  }
}

And here is the view:

<div>
    <h2>Create user</h2>    
    
    ${Html.FormToAttributed("Home", "Create", {@id: "create-form"})}
    
    <p>    
        <label for="UserName">UserName:</label>
        ${Form.TextField("user.UserName")}
        
        <label for="UserName">Email:</label>
        ${Form.TextField("user.Email")}
        
        ${Html.SubmitButton("Submit")}
    </p>
            
    ${Html.EndForm()}
    
    
    <?brail if IsDefined("errors"): ?>
        <ul>
        <?brail for error in errors: ?>
            <li>${error.PropertyName}: ${error.Message}</li>    
        <?brail end ?>
        </ul> 
    <?brail end ?>
</div>

This is of course a very simple example. You probably want to have the error message after each field and some client based validation. I think I will do another post about trying to integrate NHiberante Validator with JQuery validation.

If you want to try NHibernate validator and do not want to build it from the trunk there is a 1.0 alpha release available on sourceforge. The release contains a WinForms examples that shows how to integrate it with the WinForms error provider system.

Last week Fredrik Normén had a couple of nice posts on argument validation using C# extension methods. It got me thinking on a different approach where a method interceptor could handle the validation.

First a short recap on argument validation. I guess everyone have seen or written code with some kind of argument validation, like this for example:

public void Add(string value)
{
  if (string.IsNullOrEmpty(value)) 
      throw new ArgumentException("The value can't be null or empty", "value");
    
  ///...
}

To make argument validation easier I have (to a small extent) used a modified version of this design by contract utility class. This utility class lets you write argument validation like this:

public void Add(string value)
{
  Check.Require(value != null, "value should not be null");
    
  ///...
  
  Check.Ensure(Count > 0);
}

So this got me thinking on how you could handle argument validation using method interception. With a method interceptor you could inspect the function arguments checking for validation attributes. I envisioned code looking like this: 

[Ensure(() => this.Count > 0)]
public void Register([NotNull] string name, [InRange(5,10)] int value)
{
  ///...
}

Getting the ensure post condition to work like that will be impossible since you can only use constant expressions in attribute constructors. This is something I think they should look at for C# 4.0, being able to define lambdas in attribute arguments would make interesting scenarios possible (like this). The NotNull and InRange attributes were very simple to implement: 

public abstract class ArgumentValidationAttribute : Attribute
{        
  public abstract void Validate(object value, string argumentName);
}

[AttributeUsage(AttributeTargets.Parameter)]
public class NotNullAttribute : ArgumentValidationAttribute
{
  public override void Validate(object value, string argumentName)
  {
    if (value == null)
    {
        throw new ArgumentNullException(argumentName);
    }
  }    
}    

[AttributeUsage(AttributeTargets.Parameter)]
public class InRangeAttribute : ArgumentValidationAttribute
{
  private int min;
  private int max;

  public InRangeAttribute(int min, int max)
  {
    this.min = min;
    this.max = max;
  }

  public override void Validate(object value, string argumentName)
  {
    int intValue = (int)value;
    if (intValue < min || intValue > max)
    {
      throw new ArgumentOutOfRangeException(argumentName, string.Format("min={0}, max={1}", min, max));
    }
  }
}

This is of course the easy part. It is the actual interceptor that is making the magic happen. This implementation is just a proof of concept, and not optimal from a performance stand point.

public class ValidationInterceptor : IInterceptor
{
  public void Intercept(IInvocation invocation)
  {
    ParameterInfo[] parameters = invocation.Method.GetParameters(); 
    for (int index = 0; index < parameters.Length; index++)
    {
      var paramInfo = parameters[index];
      var attributes = paramInfo.GetCustomAttributes(typeof(ArgumentValidationAttribute), false);

      if (attributes.Length == 0)
        continue;

      foreach (ArgumentValidationAttribute attr in attributes)
      {    
        attr.Validate(invocation.Arguments[index], paramInfo.Name);
      }            
    }

    invocation.Proceed();
  }        
}

To make this interceptor more feasible for production you would probably have to add some smart caching mechanism. This interceptor based argument validation is of course somewhat limited in applicability. You have to use a dynamic proxy generator to get the interceptor functionality and only interface and virtual functions can be intercepted. But it is an interesting idea and shows another nice usage scenario for method interception.

The concept of being able to intercept method calls is something that would be great if it was built into a future version of the CLR runtime. That way static and non virtual methods could be intercepted. It is a nice way to implement cross-cutting concerns (like validation). But until then we will have to live with proxy generators, it works nicely for interfaces:

public interface IRegistrationService
{
  void Register([NotNull] string name, [InRange(5, 10)] int value);

  void Register([NotNullOrEmpty] string name);
}

If you specify the attributes on an interface you do not need to duplicate them on the implementation methods! A small update to the interceptor to support validation of the return value would allow something like this:

public interface IUserRepository
{
  [return: NotNull]
  User GetById([GreaterThanZero] int id);
  
  ///...
}

The syntax for attributes on return values are kind of funky. If Spec# isn't the future (I hope it is) then maybe something like this can be :)