Trigger IValidatableObject.Validate When ModelState.IsValid is false

I recently came across an ASP.NET MVC issue at work where the validation for my Model was not firing correctly. The Model implemented the IValidatableObject interface and thus the Validate method which did some specific logic to ensure the state of the Model (the ModelState). This Model also had some DataAnnotation attributes on it to validate basic input.

Long story short, the issue I encountered was that when ModelState.IsValid == false due to failure of the DataAnnotation validation, the IValidatableObject.Validate method is not fired, even though I needed it to be. This problem arose due to a rare situation in which ModeState.IsValid was initially false but was later set to true in the Controller’s Action Method by some logic that removed errors from the ModelState.

3 minutes to read

MVC4 Conditional HTML Attributes

MVC4 made one simple and yet awesome improvement to View rendering that I don’t think many people are aware of.

Have you ever had to conditionally add an attribute to an HTML element in your MVC View based on the presence of a variable? The typical use case is applying a CSS class to a div. Most of the time that code looks something like this:

<div @(myClass == null ? "" : "class=\"" + myClass + "\"")></div>

What a pain – not only to write but to read… This destroys the View’s readability and clutters the HTML up big time!

One minute to read

Automatically Generate POCOs From DB With T4

The T4 template engine is insanely powerful. I didn’t really realize just how powerful it was until I had a use case for it today. I stood up a database with about 40 tables in it, and planned to use an ORM to access the database. To use the ORM, I needed POCOs (Plain Old C# Objects) that represented my database. Some of these tables had 30-50 or so columns and I didn’t want to code all of this by hand – it would take literally days.
5 minutes to read

Web API Mapping QueryString/Form Input

If you’re using the Web API as part of the MVC4 framework, you may encounter a scenario in which you must map parameters of strange names to variables for which characters of the name would be illegal. That wasn’t very clear, so let’s do this by example. Consider part of the Facebook API:

Firstly, Facebook servers will make a single HTTP GET to your callback URL when you try to add or modify a subscription. A query string will be appended to your callback URL with the following parameters:

One minute to read

Generic Comparer

Have you ever had to write a comparer for a specific type, only to be frustrated when you needed to write a second and third comparer for other types? Fear not, a generic comparer can take care of this for you!

/// <summary>
/// Compares two objects of any type.
/// </summary>
/// <typeparam name="T">The type to be compared.</typeparam>
public class GenericComparer<T> : IComparer<T>
{
    // The compare method
    private readonly Func<T, T, int> _compareMethod = null;
/// &lt;summary&gt;
/// The constructor.
/// &lt;/summary&gt;
/// &lt;param name=&quot;compareMethod&quot;&gt;The compare method.&lt;/param&gt;
public GenericComparer(Func&lt;T, T, int&gt; compareMethod)
{
    // Sanitize
    if (compareMethod == null)
    {
        throw new ArgumentNullException(&quot;compareMethod&quot;);
    }

    _compareMethod = compareMethod;
}

/// &lt;summary&gt;
/// Compares two objects.
/// &lt;/summary&gt;
/// &lt;param name=&quot;x&quot;&gt;The first object.&lt;/param&gt;
/// &lt;param name=&quot;y&quot;&gt;The second object.&lt;/param&gt;
/// &lt;returns&gt;Less than 0 if x is less than y, greater than 
/// 0 if x is greater than y, 0 if they are equal.&lt;/returns&gt;
public int Compare(T x, T y)
{
    return _compareMethod(x, y);
}

}

Just pass a method to the constructor that takes 2 objects of type T and returns an int, and you’re all set!

One minute to read

Make Mostly Read, Seldom-Written Lists Much More Efficient

One of the many things that I do at work is run a full-blown Search Engine which I also developed from scratch. This Search Engine feeds all product related information to our websites. A search index consists of a pre-computed collection of products, their properties, a list of words that are correctly spelled, and some pre-computed faceted/guided navigation. A search index, until this week, took up approximately 10.7 gigs of memory. This was becoming too large as we added new products every single day.
8 minutes to read

A Better MIME Mapping Stealer!

In the interest of self-improvement and sharing knowledge, I felt that I should share an update to my last post. I discovered a slightly better way to create the GetMimeMapping delegate/method via reflection that involves less casting and overhead, and is more Object Oriented in a sense. It allows the signature of the reflected method to be Func<string, string> instead of MethodInfo. Code below, note the use of Delegate.CreateDelegate(Type, MethodInfo):

/// <summary>
/// Exposes the Mime Mapping method that Microsoft hid from us.
/// </summary>
public static class MimeMappingStealer
{
    // The get mime mapping method
    private static readonly Func<string, string> _getMimeMappingMethod = null;
/// &lt;summary&gt;
/// Static constructor sets up reflection.
/// &lt;/summary&gt;
static MimeMappingStealer()
{
    // Load hidden mime mapping class and method from System.Web
    var assembly = Assembly.GetAssembly(typeof(HttpApplication));
    Type mimeMappingType = assembly.GetType(&quot;System.Web.MimeMapping&quot;);
    _getMimeMappingMethod = 
	    (Func&lt;string, string&gt;)Delegate.CreateDelegate(typeof(Func&lt;string, string&gt;), 
		    mimeMappingType.GetMethod(&quot;GetMimeMapping&quot;, 
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.FlattenHierarchy));
}

/// &lt;summary&gt;
/// Exposes the hidden Mime mapping method.
/// &lt;/summary&gt;
/// &lt;param name=&quot;fileName&quot;&gt;The file name.&lt;/param&gt;
/// &lt;returns&gt;The mime mapping.&lt;/returns&gt;
public static string GetMimeMapping(string fileName)
{
    return _getMimeMappingMethod(fileName);
}

}

One minute to read

Determine MIME Type from File Name

I recently had a need, in an ASP.NET MVC3 application, to read raw HTML, CSS, JS, and image files from disk and return them to the user… A sort of “pass-through” if you will. Normally I’d have simply routed to a custom HTTP handler per file type or just allowed MVC3 to map existing files to supply its own .NET HTTP handlers and do all of this work for me, but in this case I needed the mapped “directory” to switch behind the scenes based on Session settings… So I ultimately had to feed these files through a Controller and Action Method to gain access to the Session.
4 minutes to read