Thursday, March 19, 2009

nHibernates poor validation of mapping files

One thing that I have come to notice as I've been using nHibernate is that it does a very poor job at validating that mapping files make sense. One could argue that I shouldn't write poor shoddy mapping files in the first place. I would beg instead to tell me when I've written a poor shoddy mapping file.

Here's the scenario I just faced. I was working with an Entity which has a One to One relationship with some legacy code which doesn't use nHibernate. When I first mapped this I had an identity column on the table. After thinking about it, I want to enforce that we have a one to one so I then modified my schema and mapping file to use the FK field as its identity. I went from this:



class name="MyOptions"  lazy="false">


    <id column="id" name="Id"  >


        <generator class="native"/>


    </id>


    <property name="FkId"/>


</class>





To this:



<class name="MyOptions"  lazy="false">


    <id column="FkId" name="FkId" unsaved-value="any">


        <generator class="assigned"/>


    </id>


    <property name="FkId"/>


</class>




I fire this up, and we have no initialization issues, I am also to read data in without an issue. But when I go to save the data, I get an IndexOutOfRange exception when nHibernate tries to access a parameter.

Do you see the issue? I left my property for FkId in the mapping file. I needed to remove it since it is now the Id. Which caused parts of nHibernate to break. Interestingly enough when I look at the insert statement it only had the FkId field being inserted into once. So part of nHibernate handles my shoddy mapping file but other parts do not.

Anyways nHibernate is still an awsome tool, and hats off to the people who devote their time without pay to such a great tool.

Dynamically call a Generic method using Reflection

While working on a request to make the Database Logging add-on I discussed previously, I came accross an interesting problem.

I wanted to be able to define the name of the ExpressionGroup, stored procedure and connection to use when logging to the database in a config file. I figure this was the first step in enabling configuration to the system. In order to do this I needed to create an instance of Expression<T>.

The expression cache already has a CreateGroup<T>() method which I wanted to use. So how can I call this method if I don't know the type of T until runtime? Its actually very easy.

Essentially you want to get a reference to the Method via Reflection. There are lots of ways to do this. Once you have a MethodInfo class, you can call MakeGenericMethod which takes a parameter array of type objects. It will use these type objects to subsitute in place for the Generic type T.

At this point you can call the method just like any other method via reflection, using the Invoke() method on MethodInfo. The code looks like this:



var meth = this.GetType().GetMethod("CreateGroup");


var genericMeth=meth.MakeGenericMethod(getType(grpConfig.AuditLogEntryType));


IAuditLoggerExpressionGroup expGroup = (IAuditLoggerExpressionGroup)genericMeth.Invoke(this, new object[] { grpConfig.Name, grpConfig.ConnectionName, grpConfig.Procedure });


this.Add(expGroup);





That's all there is to it.

Wednesday, March 11, 2009

Extension Methods & Null Objects

I ran into an issue that I had learned about a while ago but the code that I was working on predated this. I find it interesting enough to share. I love the various predicate / action methods on List<T> that allows you to interact with a list by passing in a delegate.

I've always been a little dissapointed that these methods aren't part of the IList<T> interface; however, with Extension methods we can rectify this. I defined a new method in a static class as:

        public static T Find<T>(this IList<T> col, Predicate<T> match)

        {

            if (match == null)

            {

                throw new ArgumentNullException("match");

            }

 

            for (int i = 0; i < col.Count; i++)

            {

                if (match(col[i]))

                {

                    return col[i];

                }

            }

            return default(T);

        }



This has been working fine for almost a year now, until today when I got a null Reference exception on the for loop. The interesting thing with Extension methods is they are nothing more then a static method that the compiler does some magic with.

To prove this go ahead and create a simple console application. Add an extension method on your favorite type (I choose a string), and call this from your main method. Here's what I used:

    static class Extensions

    {

        public static void ToMe(this string value)

        {

            if (value == null)

            {

                Console.WriteLine("Null value");

            }

        }

    }



static void Main(string[] args)

        {

            string s = null;

            s.ToMe();

            Console.ReadLine();

        }



After you compile this go ahead and fire up reflector or Ildasm and have a look at the IL. In my case I had the following instruction:
call void ConsoleApplication4.Extensions::ToMe(string)


Since all we are doing is calling a static method and passing in a reference to the variable which the extension method was called off of, it becomes perfectly legal to call extension methods on a null reference.

Now in my opinion this is wrong, and a side effect of the implementation, and we should not rely upon this behavior. The correct code should look like:

       public static T Find<T>(this IList<T> col, Predicate<T> match)

        {

            if (match == null)

            {

                throw new ArgumentNullException("match");

            }

            if (col == null)

            {

                throw new NullReferenceException();

            }

            for (int i = 0; i < col.Count; i++)

            {

                if (match(col[i]))

                {

                    return col[i];

                }

            }

            return default(T);

        }

Monday, March 9, 2009

Benefits of obfuscating and pointless licensing systems

Recently I was faced with a difficult problem. A component that a contractor choose for a site which I now maintain, is licensed per domain name. The site is for a relativley young company which hadn't choosen how it was going to brand the software they were selling.

After they had choosen the domain they wanted, we switched the site over and the component as we knew was going to break. We had emailed the control's manufacturer three times over a three month period, and they never replied to us. So now I was stuck with the following choices. Either we buy another license through their channel, replace the control, or find a plan c.

Considering they hadn't responded to any of my emails, I was reluctant to send them any more money. The control was used extensivley in a site that isn't worth the time to replace so that leaves us with plan c.

I have to state that plan c is a temporary fix until they respond to our emails. So I started digging around in the compiled assemblies wondering if there was a way to get around this licensing issue (again as a temporary fix).

What I saw shocked me. First the assembly wasn't obfuscated. Had it been obfuscated, I probally would have given up, as I only wanted to spend 20 minutes on this max. The second thing was that licensing scheme basically makes a call to an external assembly which returns a decrypted string that the caller then used to match against the URL's, or it would match against the host name if the string was properly formated.

Well this was easy to fix. All I had to do was create a new assembly which matched their signature, and return a very simple string. This was the only thing this assembly did.

This is where obfuscating becomes important, it is not fool proof but again nothing is foolproof, if the computer can understand someone somewhere can understand but you want to raise the bar high enough to make it so that it is not worth ones time to break through.

I'm also confused why they shipped this assembly seperate had it been compiled with the rest of their stuff it would have been riskier for me to mess around with it. Lesson learned here is either protect your code a little bit, or at least be competent enough to respond to customers emails.

Sunday, March 1, 2009

ASP.net MVC Model Binder

Model Binders is a powerful extension point to the ASP.NET MVC. It allows you to define your own class which is responsible for creating parameters for your controller actions. Scott Hansleman had a good example showing how to decouple a controller from HttpContext's user property.

Recently I've started a new Proof of Concept site which is based upon REST. My goal was to build a single web site which would expose its resources as addressable items. That is the URL defines the resource. This site should also be able to serve multiple clients which want different representations of the same resource.

For example assume we have an Automobile Parts catalog. We might have the browser point to http://myPartsCatalog.com/Ford/OilFilters/ which would render an HTML page of all the ford oil filters. Now let us say we want to implement an AJAX callback on the page so as a user mouse overs a specific part, the site might send a request to http://myPartsCatalog.com/Ford/OilFilters/fl1a, with the intention of gathering additional data about the part to display to the user. For this request we don't want to get an HTML representation of the part, we want the part rendered as JSON or XML, which will let us programatically access the part information.

I have grown tired of having to support multiple sites / pages one that renders the HTML and another that provides an API and exposes the data. The natural seperation of concerns that the MVC model gives us makes this an ideal platform to build a single web site which can serve HTML, XML, JSON or any other content we could imagine (for example what about a PDF version of the HTML page for offline usages).

To do this imagine we have the following controller defined:


public class PartController : Controller

{

public ActionResult List(string oem)

{

}

public ActionResult Detail(string oem, string partnumber)

{

}

}



We need a way to determine how the client wants the data to be returned. We could put that in the URL; however, that doesn't feel very restful. A key idea of a REST implementation is leveraging the capabilities in the HTTP protocol to define the resource your requesting. One of the Http Header's is Accept.

The Accept header allows us to define the content type that the client is requesting. So we could indicate in our request that we want text/json or text/xml. We could then put the following code in our controller:



        public ActionResult List(string oem)

        {

            //Get the Model for OEM.

            switch (HttpContext.Request.AcceptTypes[0])

            {

                case "*/*":

                case "text/html":

                    return View("PartList.aspx");

                case "text/json":

                    return View("PartList.json.aspx");

            }

        }



Warning: I am not finished investgating how ASP.Net handles the Accept header and my switch statement might not work; however, this is an example to highlight the flexibility of ASP.Net MVC.

So this works great; except that we want to unit test our code to ensure we are returning the right view for each request; however our controller is bound HttpContext which can be difficult to unit test. So the question is how do we decouple our controller from HttpContext? IModelBinder's are the answer.

We can define a ModelBinder by implementing the IModelBinder interface. The interface requires a single method that takes a couple parameters which provide context about the request, and returns an object.



    public class ContentTypeModelBinder : IModelBinder

    {

 

        #region IModelBinder Members

 

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

        {

            if (controllerContext == null)

            {

                throw new ArgumentNullException("controllerContext");

            }

            if (bindingContext == null)

            {

                throw new ArgumentNullException("bindingContext");

            }

 

            return controllerContext.HttpContext.Request.AcceptTypes[0];

        }

 

        #endregion

    }




The return value from the function will be used to pass in to a parameter in a controller. This allows us to change our controller definition to:

        public ActionResult List(string oem, [ModelBinder(typeof(ContentTypeModelBinder))]string contentType)

        {

            //Get the Model for OEM.

            switch (contentType)

            {

                case "*/*":

                case "text/html":

                    return View("PartList.aspx");

                case "text/json":

                    return View("PartList.json.aspx");

            }

        }



The magic here is the ModelBinder attribute which is applied to the contentType parameter. This tells the ASP.Net MVC runtime to use our own custom IModelBinder to provide the value for the contentType attribute.



The thing I don't like about this is that we have to use an attribtue in our controller. It is possible to indicate that all instances of a specific type use a specific binder. But I will leave that for a different article.

Enjoy