Mapping a nullable bit column to an enum with NHibernate


I recently had to map an enum with 3 possible values (Pending, Approved, denied) to a nullable bit field in a SQL database. This type of mapping is not supported natively by NHibernate which by default translates enum values to their integer representation. I found several articles on handling the mapping to a string which is pretty straight forward using the … type but I haven’t found anything about this particular scenario.

This is where custom user types come to the rescue and this is what I am going to explain in this article.

To create a custom user type, we just need to create a class that implements NHibernate.UserTypes.IUserType. In our case, the implentation is pretty easy with the only methods that required a little bit of thinking being NullSafeGet and NullSafeSet.
This is how the class looks like:

public class NullableApprovalStatusType : IUserType
{
    public bool Equals(object x, object y)
    {
        return x == null ? y == null : x.Equals(y);
    }

    public int GetHashCode(object x)
    {
        return x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs, string[] names,
                              object owner)
    {
        bool? dbValue = (bool?) NHibernateUtil.Boolean
                                 .NullSafeGet(rs, names);
        switch (dbValue)
        {
            case true:
                return ApprovalStatusType.Approved;
            case false:
                return ApprovalStatusType.Denied;
            default:
                return ApprovalStatusType.Pending;
        }
    }

    public void NullSafeSet(IDbCommand cmd, object value,
                            int index)
    {
        var obj = (ApprovalStatusType) value;
        bool? dbValue = null;
        switch (obj)
        {
            case ApprovalStatusType.Approved:
                dbValue = true;
                break;
            case ApprovalStatusType.Denied:
                dbValue = false;
                break;
            case ApprovalStatusType.Pending:
                dbValue = null;
                break;
        }
        NHibernateUtil.Boolean.NullSafeSet(cmd, dbValue,index);
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public object Replace(object original, object target,
                          object owner)
    {
        return original;
    }

    public object Assemble(object cached, object owner)
    {
        return DeepCopy(cached);
    }

    public object Disassemble(object value)
    {
        return DeepCopy(value);
    }

    public SqlType[] SqlTypes
    {
        get { return new[] {new SqlType(DbType.Boolean)}; }
    }

    public Type ReturnedType
    {
        get { return typeof(ApprovalStatusType); }
    }

    public bool IsMutable
    {
        get { return false; }
    }
}

Now that we have our custom user type ready we can just do out mapping:

<property name="ApprovalStatus" column="is_approved"
          not-null="false"
          type="MyNamespace.NullableApprovalStatusType,
                MyAssembly" />

It is nice to notice that the custom user type doesn’t have to be in the same namespace or assembly as the mapped class which allows us to keep it in the data access layer and not introduce any NHibernate dependency to the business logic or domain objects.

Unit testing methods with date/time in .net


One of the very important rules of unit testing is to make sure that the result of the test is predictable and repeatable. This is fairly straight forward to achieve in most cases by using constants instead of random values for example but how do we deal with methods using the current date and/or time?

If we just use the DateTime.Now property, the value will change for each test run which will cause us to have unpredictable and sometimes unrepeatable results.

The solution to this problem is pretty simple, create a wrapper class for the DateTime methods that we may need so we can mock the call to methods returning time dependent values.

A very basic wrapper class could look like this:

   1: using System;

   2:

   3: public interface IDateTime

   4: {

   5:     #region Methods

   6:

   7:     DateTime Now();

   8:

   9:     #endregion Methods

  10: }

  11:

  12: public class DateTimeWrapper : IDateTime

  13: {

  14:     #region Public Methods

  15:

  16:     public DateTime Now()

  17:     {

  18:         return DateTime.Now;

  19:     }

  20:

  21:     #endregion Public Methods

  22: }

 

We can now use the DateTimeWrapper implementation of IDateTime in our code and the IDateTime interface can easily be mocked to return a constant value for the Now() method call.

WILT: XML encode a string in .net


Always wondered why I couldn’t find a method that would XML encode a string, effectively escaping the 5 illegal characters for XML. There is such a method but its location in the API is not intuitive at all. It’s in the System.Security namespace:

   1: public static string Escape(

   2:     string str

   3: )

Its usage is:

   1: tagText = System.Security.SecurityElement.Escape(tagText);

This will escape the 5 characters <, >, &, “ and ‘

MSDN: http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape.aspx

WILT: Inherit and Implement in C#


WILT: What I Learned Today

This is a new category of posts I decided to start to record by daily learnings. I am sure that a lot of those posts are going to be embarrassing because they will expose basic things I should have known for a long time but, oh well…
One of the things I enjoy the most with my job is that I learn everyday. Some days I learn about small details, other days I learn more complex techniques or theories.

Anyway, today’s post is about creating a class that both inherit from another class and implements an interface.

This is very straight forward and a frequent occurence but the little “trick” here is to list the inherited class(es) first.

   1: public class MyClassA

   2: {

   3:     ...

   4: }

   5:  

   6: public interface IMyInterface

   7: {

   8:     ...

   9: }

  10:  

  11: public class MyClassB : MyClassA, IMyInterface

  12: {

  13:     ...

  14: }

Flattening the WSDL for WCF services


Windows Communication Foundation is Microsoft’s latest implementation for distributed computing including web-services. One of the key features of SOAP based web services is the WSDL (Web Service Definition Standard) that allows client applications written in any language and running on any platform to discover how to communicate with the services.

In WCF, the WSDL generated for each service uses a feature that is part of the WSDL standard but is not yet widely supported – Import statements. This feature allows to have external files to define sub-sections of the WSDL. This becomes a problem when you are trying to consume a WCF service from systems that have web service implementations that do not support those statements.

This can be fixed by forcing WCF to flatten the WSDL. Christian Weyer wrote a very good article about this so I won’t try to rewrite it because I wouldn’t be able to do it better. Instead, just go and take a look at it for yourself: http://blogs.thinktecture.com/cweyer/archive/2007/05/10/414840.aspx#.

This helped me a lot when trying to make one of my WCF services consumable from Mercator. I hope this can save you some time too.

Follow

Get every new post delivered to your Inbox.