Defensive Code #1 – Input Validation

By Digbyswift at July 26, 2010 03:52

Firstly, these “defensive code” articles are not meant to be a definitive, just practices I feel are important to the way I code. The reason I’m compiling this list is partly so that I can have a reference for myself, but also because I wanted to present something to the team I work in.

Input validation

There are two types of input validation:

  • Input from an external source; and
  • Input from within the application.

An external input may be a user submitting a form or it may be the stream from a file you are importing. Input from within your application may simply be the passing of variables as parameters from on method to the next.

In both cases I choose to take the stance that input is almost always likely to be invalid or just plain wrong.

External input

Regardless of the input, it is imperative that you check:

  • The input exists

    There is no point further validating a null string or stream. This should be the first step in ANY input validation.

  • The data should be of the correct format

    If a user inputs a value into a decimal field, it should be validated to ensure that the decimal has the correct point accuracy, e.g. 2 decimal places for a monetary value. This can be done without the need to cast the value.

  • The input data is of the same type that is expected

    If a user inputs a value into a decimal field, the value should be validated to ensure that it is a decimal and not a string.

  • The input data is within the correct boundaries

Obviously, there are scenarios where this is overkill. For example, you wouldn’t need to check that a textual input is of a string type! But regardless of the input method, these can all be applied to ensure that the data collected is valid.

Internal input

I think controlling internal input is easier, just more time consuming. Essentially, for any method, you should check that the values passed or pulled in are valid. Again, there are scenarios where this is not required but my personal rule is to assume that input is invalid.

You will hardly ever have to validate parameterized input is of a specific type as this can be defined by the parameter type. However, all the guidelines from above can be applied.

  • Data exists;
  • Data is in the expected format;
  • Data is within the correct boundaries.

With values that are pulled in, i.e. not parameterized but maybe from a global variable, it is even more important that the guidelines from above are adhered to. This is because otherwise there is an assumption that some other process is validating the data pulled in, which of course you cannot rely on.

Consider the case that a class has a username property which is used in a method but not passed in via a parameter. In this case, it is worth having a separate, global method for handling the validation of the username, i.e. IsUsernameValid(). This way, other routines can make use of the same validation method.

Upgrading to MVC2: No parameterless constructor error

By Digbyswift at February 25, 2010 05:00

I cam across this today and it bugged the hell out of me. I am using a custom ControllerFactory (kindly provided by Steve Sanderson’s awesome Pro ASP.NET MVC Framework) set in the global.asax.cs as such:

protected void Application_Start() 
{ 
    RegisterRoutes(RouteTable.Routes); 

    // Configure log4net 
    log4net.Config.XmlConfigurator.Configure(); 

    // Configure CastleWindsor 
    ControllerBuilder
        .Current
        .SetControllerFactory(new WindsorControllerFactory()); 
}

During the upgrade this stopped working and i started getting the following error:

System.MissingMethodException: No parameterless constructor defined for this object


I tracked the error down to the fact the constructors in my Controllers were not being initialized and I found the following quote from the breaking changes section of the What’s New in ASP.NET MVC 2:

Custom controller factories are often used to provide dependency injection for ASP.NET MVC applications. To update the custom controller factories to support ASP.NET MVC 2, change the method signature or signatures to match the new signatures, and use the request context parameter instead of the property.

After a little digging, the only change I needed to make was altering my custom ControllerFactory’s GetControllerInstance() override from:

protected override IController GetControllerInstance(Type controllerType) 
{ 
    return (IController)_container.Resolve(controllerType); 
}


to

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) 
{ 
    return (IController)_container.Resolve(controllerType); 
}

.Net Extension Methods

By Digbyswift at November 06, 2009 06:57

Two words. Code re-use.

Think of a specific, probably basic bit of code that you find yourself writing a lot, e.g. validating a string to ensure it is either null or not empty. Generally you’d have to write:

if (value == null) 
    return null; 

value = value.Trim(); 
return (value.Length == 0) ? null : value;


Using extension methods, you can wrap this in a tidy method:

public static string TrimToDefault(this string value) 
{ 
    if (value == null) 
        return null; 

    value = value.Trim(); 

    return (value.Length == 0) ? null : value; 
}

I also overload this so that I can specify a default value:

public static string TrimToDefault(this string value) 
{ 
    return TrimToDefault(value, null); 
} 

public static string TrimToDefault(this string value, string defaultValue) 
{ 
    if (value == null) 
        return defaultValue; 

    value = value.Trim(); 

    return (value.Length == 0) ? defaultValue : value; 
}

I can then implement the methods like so:

string stringToSave = txtTitle.Text.TrimToDefault();

or

string stringToSave = txtTitle.Text.TrimToDefault("Not specified");


Alternatively, you can overload existing methods. So you could simply overload String.IsNullOrEmpty().

You might say, that this isn’t really a time saver but the value is that if you have a library of such methods you can maintain consistency across different projects but also enforce a little consistency in the way fellow developers on your team code too. This will save you time.

Lovely.

Discovering MvcContrib

By Digbyswift at September 01, 2009 06:01

Why have I only just found this? Ok, I must admit that when I started researching ASP.Net MVC I was probably overcome with the amount of information I had to digest. So its entirely possible that I missed it or ignored it.

Having briefly read through the documentation MvcContrib provides a massive library of alternatives and additions to the core ASP.Net MVC library. With thousands of downloads, this it usefulness speaks for itself.

So far my personal fave has to be the Grid. I love things that make life easier and this is a gem. There is also a fantastic introduction on the grid this here.

A borrowed example of how easy the Grid is to implement is shown below:

<%= Html.Grid(Model.People).Columns(column => {
         column.For(x => x.Id).Named("Person ID");
         column.For(x => x.Name);
         column.For(x => x.DateOfBirth).Format("{0:d}");
     })
     .Attributes(style => "width:100%")
     .Empty("There are no people.")
     .RowStart(row => "<tr foo='bar'>") %>

Sweeeet.

Kieron McIntyre

C# .Net Developer, based in Leeds. Married, happy and always learning