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

Static vs Instance string.Equals Benchmark

A friend of mine commented on my last post asking about how much faster the static string.Equals method is than the instance string.Equals method. To satiate both of our curiosities, I have created this benchmarking application:

static void Main(string[] args)
{
    var stopwatch = new Stopwatch();
string a = &quot;hello&quot;;
string b = &quot;hi&quot;;

stopwatch.Start();
for (int i = 0; i &lt; 10000000; i++)
{
    a.Equals(b);
}
stopwatch.Stop();

Console.WriteLine(&quot;Instance string.Equals over 10,000,000 iterations: &quot; 
    + stopwatch.ElapsedMilliseconds + &quot; ms&quot;);

stopwatch.Reset();

stopwatch.Start();
for (int i = 0; i &lt; 10000000; i++)
{
    string.Equals(a, b);
}
stopwatch.Stop();

Console.WriteLine(&quot;Static string.Equals over 10,000,000 iterations: &quot;
    + stopwatch.ElapsedMilliseconds + &quot; ms&quot;);

Console.ReadKey();

}

The results of 5 runs, where “I” is the instance method and “S” is the static method, and the times are in milliseconds:

One minute to read

Static vs Instance string.Equals

As you may or may not know, static methods are usually faster than instance methods. This alone should be a good enough reason to use the static string.Equals method in .NET, but if that doesn’t do it for you, allow me to present a simple example.

string a = "hello";
string b = "hi";
bool result = a.Equals(b);

What is the expected result of these lines? A boolean value of false, of course. And it’d be true if the strings were identical. It’s also false if b is null. But what if a is null?

One minute to read

TPL and Error Handling & Continuation Tasks

Two of my colleagues (one from work and one from a user group) kindly pointed out to me that in my last post I omitted Continuation Tasks as a means of Error Handling for the TPL. As such, I will expand upon my last post with an example of handling errors via a Continuation Task.

Continuing where we left off last, the following code will utilize a Task Continuation to handle errors within Tasks.

2 minutes to read

TPL and Error Handling

As of .NET 4.0, the TPL or Task Parallel Library is king when it comes to parallelization. It allows for smooth, easy multi-threading for any application. There is a slight learning curve, however, and a major part of this is understanding how Exceptions bubble-up while using the TPL.

Let’s partake in a simple example. This code will create and run a task that throws an Exception, and then attempt to catch it:

5 minutes to read

Compiler Tricks - Inferred Types

The .NET compiler is a terrific thing… After all, it turns your C# into an executable program!

One nice feature of the .NET compiler, which is becoming better each release, is inferred typing. I’d like to lay out a few short examples that might help you develop your programming standards and practices.

Inferring a type when creating an array.

// Create and initialize an array
var myArray = new int[] { 1, 2, 3 };

Becomes:

2 minutes to read

Custom Output Caching with MVC3 and .NET 4.0 - Done Properly!

I came across a need at work today to re-implement some of the Output Caching for our MVC3 application which runs under .NET 4.0. I wanted to use standard Output Caching (via the OutputCacheAttribute class, why re-invent the well-working wheel?) but due to some of our requirements I needed more control over how my objects were cached. More specifically, I needed to cache them with a custom Cache Dependency. With a little bit of Google-Fu, I was delighted to learn of the Output Cache Provider functionality introduced in ASP.NET 4. I implemented a custom OutputCacheProvider, registered it in my Web.config file as the Default Cache Provider, and I was well on my way.
6 minutes to read

LINQ and Deferred Execution

As of .NET 3.0, LINQ (and the often related Lambda Expressions) have been available for our use and abuse. LINQ stands for Language INtegrated Query, and is a method of modelling OO data in a more or less relational sense that is not unlike databases. And just like databases, it comes with a cost.

To offset this cost, LINQ uses Deferred Execution. Deferred Execution means that the code is not executed until it is needed. This means that the LINQ code that you write is not actually executed until you NEED to execute it – typically during an enumeration of the results.

4 minutes to read

Make Your Debugging Life Easier

Sorry for the delay in posts, May has been a very busy month.

In order to accurately debug or profile an external assembly or library (AKA one you’re not directly compiling), you need the associated PDB files to accompany each of the DLLs. These files give the debugger some information about the compiled assembly so that your debugger or profiler can become aware of function names, line numbers, and other related meta data.

3 minutes to read