October 2009 - Posts

I recently setup my first continuous integration build server using JetBrains’ TeamCity product, and it couldn’t have been much simpler.  However I kept running into an issue with my test projects whenever I was using NHibernate or SQLite (very useful or regression tests against an in-memory database).

The Problem

Everything would run correctly locally using MSTest, but when TeamCity ran the tests I would get the following error:

Unable to load type 'NHibernate.ByteCode.Castle.ProxyFactoryFactory,
NHibernate.ByteCode.Castle' during configuration of proxy factory
class.
Possible causes are:
- The NHibernate.Bytecode provider assembly was not deployed.
- The typeName used to initialize the 'proxyfactory.factory_class'
property of the session-factory section is not well formed.

Solution:
Confirm that your deployment folder contains one of the following
assemblies:

Of course I’ve seen this error before and I double checked that I had a reference to the NHibernate bytecode provider and that my NHibernate.config file was configured correctly.  I thought maybe this was a x86 vs x64 issue, but that also did not seem to be the case.

Eventually running MSTest locally through the command line reproduced the error, and after I searched around for a while I found that NHibernate.ByteCode.Castle.dll was not be deployed into the specific TestProject\bin\Release\ folder (and neither was SQLite).

I made sure my test project had a reference to both DLLs, that is was set to copy local, and still they were not copied to my “deployment” directory.

The Reason

From what I could gather, msbuild was being ‘smart’ and optimizing my build such that the bytecode and SQLite DLLs were not being included since they were never directly referenced in code.  This is because they are referenced only in the NHibernate.config file.

The Solution (aka Major Hack)

In order to get the proper DLLs included in the build I had to reference them somewhere in code, so I made a totally unreachable class that should never be instantiated, as follows:

/// <summary>
/// NOTE: This is a hack to make sure that the castle 
/// and SQLLite assemblies are copied into the Test deployemnt directory
/// This class never gets called.
/// </summary>
public class ContinuousIntegrationDeploymentHack
{
    public ContinuousIntegrationDeploymentHack()
    {
        new NHibernate.ByteCode.Castle.ProxyFactoryFactory();
        new System.Data.SQLite.SQLiteException();
 
        throw new Exception("This class should never be called or instantiated");
    }
}

Adding this class anywhere into my test project does the trick – the castle bytecode and SQLite DLLs are now copied into the deployment directory and all tests run correctly.

The Future

I am sure the proper way to solve this was to use MSBuild or NAnt and copy the files correctly, but I am currently using the easy TeamCity sln2008 runner and thus there are no custom tasks that I can run.

I’ve recently switched from the Enterprise Library Validation Application Block to using NHibernate Validators. If you are not familiar with the NHibernate Validator project, they are part of the NHibernate Contrib project and offer Validation constraints, and validation runner, and tight integration with NHibernate (especially great if you use NHibernate to generate your DB).

One of the main reasons for my switch was integration with xVal (which EntLib Validation’s implementation prevents), and also to get some advanced but common validators like Email, Size, NotNullNotEmpty.

Anyway, I would recommend that you look at NHibernate Validator if you use NHibernate and are looking for a validation framework.  However, this post is about writing a new validator that will integrate with NHibernate Validators – the Required validator.

Motivation for the Required Validator

Many of the varchar/nvarchar columns in my database are set to NotNull, and I also want to go a step further and make sure that they can’t be empty strings or just spaces.

There does exist a NotNull validator and a NotEmpty validator which work correctly on their own or combined, and there is a NotNullNotEmpty validator as well.

However, the NotNullNotEmpty validator only works on IEnumerable types, even though the NotNull and NotEmpty validator work on strings.

So What Can We Do?

First, and simplest, is to put both a NotNull and a NotEmpty validator on each string property.  In my case, our team was already familiar with a required validator and I found they were confused when the NotNullNotEmpty validator didn’t combine the two.

Option 2 is to write your own validator, which I did with the Required validator.

Required Validator

In order to make a custom NHibernate Validtor with accompanying Attribute, you should write two classes.

The first is the validator class, which should implement IValidator (NHibernate.Validator.Engine.IValidator).  This just defines one method, IsValid() which returns a bool.  The whole implementation is as follows:

/// <summary>
/// Required Validator means the value can not be null or empty (or only spaces)
/// </summary>
public class RequiredValidator : IValidator
{
    public bool IsValid(object value, IConstraintValidatorContext constraintValidatorContext)
    {
        if (value == null)
        {
            return false;
        }
 
        var check = value as string;
        if (check != null)
        {
            return !string.Empty.Equals(check.Trim());
        }
 
        var ev = value as IEnumerable;
        if (ev != null)
        {
            return ev.GetEnumerator().MoveNext();
        }
 
        return false;
    }
}

Basically this first checks if the value is null – if it is we return that this object is not valid.  After that we just copy the code from the NotEmpty validator and check to see if a trimmed version of the string is not equal to string.Empty.  It also can check for empty Enumerables just like NotNullNotEmpty.

Required Attribute

The second class to write is an attribute which handles the parameters and message, and uses the ValidatorClass[] attribute to tell the validation runner which validator it executes.

[Serializable]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
[ValidatorClass(typeof(RequiredValidator))]
public class RequiredAttribute : Attribute, IRuleArgs
{
    public string Message
    {
        get { return _message; }
        set { _message = value; }
    }
 
    private string _message = "{validator.notNullNotEmpty}"; //Use the not empty language by default
}

Usage

Of course you can use this just like any other NHibernate Validator and even side by side with existing validators:

[Length(50)]
[Required]
public virtual string FirstName { get; set; }
 
[Length(50)]
[Required]
public virtual string LastName { get; set; }

Integration with xVal

Integration with xVal just takes one more line inside the validation rules provider (see my post on using xVal with NHibernate Validator)

ruleEmitters.AddSingle<RequiredAttribute>(x=>new RequiredRule());
 

Conclusion

We now have a Required Validator that we can use in our project, and it even integrates with xVal.  Now this was a really simple change, but I’ll write soon about some more complex custom validators which might prove helpful.

I’ve been playing with Visual Studio 2010 Beta a little and one of my favorite new features (and there are many) is the new web.config transformation feature. 

Web.config transformations are setup so there is one configuration “delta” for each build configuration that you have (default are Debug and Release).  When you build your solution (as a package, when you publish, etc) your original web.config is transformed according to the settings in your web.debug.config file (assuming the debug configuration).

There are plenty of blogs and msdn references out there for you to look at but I thought I’d write a quick post that would get you up to date on how to do the some common web.config transformations.

First, A Tiny Iota (That guy was great!) of XDT Review

As it pertains to web.config replacements, you need to know that every XML element can have two xdt attributes: xdt:Tranform and xdt:Locator

  • Transform: What you want to do with the XML element
    • You might want to Replace it, set an attribute (SetAttribute), remove an attribute (RemoveAttribute), etc.
  • Locator: Where is the element that needs transformation?
    • You probably want to transform an element that matches (Match) a specific attribute value

Case 1: Replacing all AppSettings

This is the overkill case where you just want to replace an entire section of the web.config.  In this case I will replace all AppSettings in the web.config will new settings in web.release.config.  This is my baseline web.config appSettings:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ValB"/>
</appSettings>

Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element.  I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.

<appSettings xdt:Transform="Replace">
  <add key="ProdKeyA" value="ProdValA"/>
  <add key="ProdKeyB" value="ProdValB"/>
  <add key="ProdKeyC" value="ProdValC"/>
</appSettings>

 

Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same.  Now let’s look at the generated web.config file what happens when we publish:

<appSettings>
  <add key="ProdKeyA" value="ProdValA"/>
  <add key="ProdKeyB" value="ProdValB"/>
  <add key="ProdKeyC" value="ProdValC"/>
</appSettings>

Just as we expected – the web.config appSettings were completely replaced by the values in web.release config.  That was easy!

Case 2: Replacing a specific AppSetting’s value

Ok, so case 1 was the nuclear option, what about doing something a little more practical?  Let’s go back to our original AppSettings web.config example:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ValB"/>
</appSettings>

 

Let’s say that we just want to replace KeyB’s value to something more suited for a production environment.  This time we get to use both xdt:Transform and xdt:Locator.

Our strategy will be to define (in web.release.config) an appSettings section that has just the replacements we want to make.  It will initially look like this:

<appSettings>
  <add key="KeyB" value="ProdValA" />
</appSettings>

Now we want to add in the transforms so that we replace any appSetting that matches this key (KeyB).

<appSettings>
  <add key="KeyB" value="ProdValA" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>

 

Once we publish our resulting web.config file looks like this:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ProdValA"/>
</appSettings>

 

Perfect – We replaced KeyB but left KeyA (and any other keys if they were to exist) alone.

Case 3: Replace Compilation Debug=”true”

This is a simple one because Microsoft gives it to us out of the box – but I’ll reproduce it here anyway because it illustrates a common scenario and shows that there are more transforms then just Replace:

<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>

There are also ways to SetAttributes, Remove elements, Insert elements, and much more

To Infinity – And Beyond

We have obviously just scratched the surface, but for now that’s as deep as I need to go.  Until next time, you can look at the MSDN reference for Web.Config transformations at http://msdn.microsoft.com/en-us/library/dd465326%28VS.100%29.aspx.

Enjoy!

When using ASP.NET MVC you will eventually want to do a select (drop down) or even a multiple select list, and your first though might be to use <%= Html.DropDownList %>.  Unfortunately you will soon notice that ASP.NET MVC always looks for a match between the name of the dropdown and a property on the model, and if it finds a match, it OVERRIDES the selected value(s) of the select list.  Now of course not being able to reliably set the selected value(s) is a major problem – if you Google this you will get a ton of results and most people solve the issue by just changing the name of the Html.DropDownList(“name”) to something that doesn’t match a model property.

Of course we can put this into the “hack” or “workaround” category, and I don’t like doing that on my nice shiny MVC project.  However, the biggest problem is if you are doing advanced model binding (I have my own impl, but as an example look at SharpArchitecture), changing the name of the drop down will break model binding and model state errors.

So – how do we use drop down lists and maintain our control over naming and selected items?  Enter MVCContrib’s FluentHTML:

MVCContrib FluentHTML Select and MultiSelect

Once you copy the MVCContrib.FluentHTML DLL into your project and resolve the namespace, you get a whole bunch of nice Html helpers right on the base View Data Container.  We want to look at the Select and MultiSelect options, which you would use as follows:

<%= this.MultiSelect("User.Projects").Options(Model.Projects) %>

Now moving past the default case, you’ll want to choose which properties to bind and maybe which values are selected.  The following is how I attempted to do this at first:

<%= this.MultiSelect("User.Projects")
.Options(new MultiSelectList(Model.Projects, "ID", "Name",
Model.User.Projects.Select(a=>a.ID)))%>

There is also another option which involves calling .Selected() instead of putting the selected values directly in the MultiSelectList ctor.
 
<%= this.MultiSelect("User.Projects")
.Options(new MultiSelectList(Model.Projects, "ID", "Name"))
.Selected(Model.User.Projects.Select(a=>a.ID)) %>

The Problem

When using NHibernate, or likely any other ORM, you run into a subtle problem.  Occasionally you will get the following errors when binding MultiSelect (note this problem also happens using the Select):

Object does not match target type.

Exception Details: System.Reflection.TargetException: Object does not match target type.

It takes a lot of debugging, but you eventually discover that this only occurs when binding to proxied instances.  So for this example, I had NHibernate get me a list of all Projects and since lazy-load was set to true (the default), some of these came back as proxies.  When trying to get the ID value of these proxies, you get the exception thrown from within System.Reflection.
 

The Solution

The solution here is to use an overload of Options() to put the valueField and textField into the method call and NOT into the constructor of a SelectList/MultiSelectList.  You can either use strings of selectors, as you can see below:

<%= this.MultiSelect("User.Projects")
.Options(Model.Projects, "ID", "Name")
.Selected(Model.User.Projects.Select(a=>a.ID)) %>
 
OR

<%= this.MultiSelect("User.Projects")
.Options(Model.Projects, a=>a.ID, a=>a.Name)
.Selected(Model.User.Projects.Select(a=>a.ID)) %>
 
Now, there is no reflection errors.  Enjoy!
More Posts