Category Archives: Unit Tests

ASP.NET/Razor Custom Helpers, DLL’s & Unit Tests

All of the tutorials and sample code I seem to come across for writing a custom @helper using Razor syntax seem to only show how to pass string parameters. I’m building a website that uses bigint, int, nvarchar, datetime and money types in the database.

Obviously bigint maps to long, int to int and nvarchar to string, but for some reason I couldn’t seem to figure out what to map the database money type to, or check for null against a datetime (DB) value. Maybe there is a mapping table specific to razor out there, but I couldn’t find it.

In the end I figured out that the database Money type maps to the .net Decimal type. So the @helper call in my .cshtml file to get the profit from a sale, looks like this:

@MyHelper.GetProfit( @item.Buy, @item.Sell, @item.Qty )

The @helper implementation is:

@helper GetProfit( decimal buy, decimal sell, int qty) 
    var zero = new Decimal(0.0);
    if ( qty > 0 && sell > zero )
        var profit = (sell – buy) * qty;
        @string.Format(“{0,0:C2}”, profit);
        var str = “n/a”;

This seems to work well and prints out a nicely formatted $10,170.00, –$1,340.00 or n/a thanks to the {0,0:C2} formatter string.

If you are editing some values and need to process them on the postback for storing in the database, you need to figure out if you are working with the string value from the form data, or need a strongly typed object ready to pass to your db.Execute( ) statement.

In the top of your .cshtml file you are going to need something like this:

    var buyPrice = “$”;
    var sellPrice = “$”;
    var quantity = “”;
    var sellDate = “”;
    SqlDateTime sellDateDT = DateTime.Now;

To perform validation and any data manipulation you will need to work with the ‘var‘ values (ie. string’s). eg: testing if the date entered by the user is a valid date etc… Once you’ve done that, you have to decide whether to pass a DateTime object, set to the entered value, or a null value (if allowed in the database). For that, you are going to need an SqlDateTime object – set to the correct value, or else set to SqlDateTime.Null.

As I started to create more and more .cshtml pages with these sorts of values to stored in the database, I realised that I needed some utility methods to perform the repetitive, mundane tasks of sanitizing the data received from the posted form.

This led me to write my own little custom .dll with a series of utility classes. I put all of the sanitise methods in there. Some include:

public static string SanitiseCurrency(string input) {}
public static SqlDateTime SanitiseDate(string input) {}
public static string SanitiseWholeNum(string input) {}
public static string SanitiseStr(string input) {}

A sample implementation of one of these santitise methods could look something like this:

public static SqlDateTime SanitiseDate(string input)

    SqlDateTime result = SqlDateTime.Null;
        if (!string.IsNullOrEmpty(input))
            result = SqlDateTime.Parse(input.Trim());
    catch (Exception)
        result = SqlDateTime.Null; // just to make sure
    return result;

Notice that most methods return a string object, which works nicely for using parameterized SQL Queries, but the DateTime method must return a strongly typed instance to satisfy the DB driver type mappings etc…

I edit and compile this .dll in Visual Studio 2010, and have a post build success event that copies the output assembly into the /bin folder of my WebMatrix project. It’s so simple to do, no playing with paths, or imports or assembly references etc… Just drop it in the /bin directly and it’s immediately available to your Razor code.

Now, some might think this is a little overkill, but there is a nice side effect – I can create a Unit Test Project under the same solution that holds my utilities project. And suddenly I can edit, build, and test my code! If it passes all my test, I can deploy it to the WebMatrix /bin directory with confidence that my financial/money utility methods are correct with their processing.

Another benefit of having an external project like this, is that you can also call out of your @helper code into your C# .dll and gain the benefit of the feature rich environment in Visual Studio if your @helper performs some complex operations or calculations. This allows you to unit test your @helper too!!

So using the example from the very start of this post again, once I have moved the @helper code out into my utility project, it now looks like this:

@using MyApp.Core;
@helper GetProfit( decimal buy, decimal sell, int qty)
    @Utils.GetProfit( buy, sell, qty );

Don’t forget to import any namespaces you have used in your .dll, otherwise ASP.NET won’t find it when it attempts to compile the page.

So I now have nice clean HTML code in my .cshtml file; I have nice clean code in my @Helper code; and I have a set of fully unit tested utility functions I can access from my custom .dll.

Very Nice!