As of yesterday the comments on the blog here are now officially hosted by Disqus. If anyone has tried leaving comments in the past only to have them never show up (or disappear at some point), I apologize for that. The spam was a little crazy….and by a little crazy I mean effing insane, It got to the point where I was unable to separate the wheat from the chaff, and went through a couple different strategies to try and get things under control…Disqus is the latest (and hopefully last) of these strategies.

So I hope you enjoy the new and improved, and not quite so spammy comment system.

As of today I have updated several things on the site.  First, I have a new hosting provider, WinHost.  This was primarily a financial decision (saving $3.03 a month, not a lot but hey, every little bit helps, right?), but it looks like there are some nice technical advantages to switching as well.  Some of these are things like IIS 7 hosting, and SQL Server access.  Also you get unlimited domain name pointers, so the IThinkIn.Net domain that I registered a few years back and could never wire up is now live.  While I was in the process of moving to a new server I also updated to the latest version of dasBlog, seeing as I was still running the original .Net 2.0 version from sometime in early 2006 (I think).  I’m not sure whether there will be any immediate signs of new and exciting things, but you never know.  You should now be able to utilize Gravatar icons, and OpenID, so it can’t be all bad right?

Please contact me if for any reason there is an issue with any of the content.  As far as I know everything moved over without a hitch, but I’ve not verified everything at this point.


Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle – and for the launch will be giving out FREE licenses to bloggers and their readers.

The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers

So, to take a slightly different turn from my usual meta discussions of process, theory, and architecture, there have been several people who have offered up some examples of extension methods that they have found useful, now that .Net 3.5 is roaring along nicely.  There are some collections of such utilities, like the Umbrella project, and some folks like Bill Wagner who have written books on the subject (okay, there are other things in there too), so I thought I might as well throw my hat into the ring as well.  Specifically, there was this tweet from @elijahmanor a few days ago.  It points to a positing which includes some extensions on string to convert from strings to value types (int, long, short, etc).  I pointed out that in our current project we have distilled this down to a single extension method: To().

He suggested I blog about it, so here it is:

So we actually have two classes of conversions, one converts from a string to a value type, and they other converts from a string to a Nullable value type.  In the case of our project, the nullable version came first, and so it became very easy to create the version that returned a non-nullable value.  Here are the methods of interest:

public static T To(this string input) where T : struct
{
    return input.To(default(T));
}

public static T To(this string input, T defaultValue) where T: struct
{
    return input.ToNullable() ?? defaultValue;
}

public static T? ToNullable(this string input) where T : struct
{
    if (string.IsNullOrEmpty(input))
        return null;
    var tryParse = GetTryParse();
    return (T?)tryParse(input);
}

Okay, so this is pretty straight forward.  The non-nullable version calls through to the nullable version, and if it is null, it returns default(T).  But, as I’m sure you are an astute reader, you will see that there is some magic going on; namely the GetTryParse() method.  This little guy goes off and looks for a TryParse method on whatever T happens to be, and then returns a Func<> delegate that will run the string input through the try parse and return either a null (in case the TryParse fails), or a boxed version of the result.  So, lets see what it looks like before we discuss pros and cons

private static Func<string,object> GetTryParse()
{
    var tryParseEx = GetTryParseExpression();
    return (s) =&gt; tryParseEx.Compile()(s,default(T));
}

private static Expression&lt;Func&lt;string,object&gt;&gt; GetTryParseExpression()
{   
    if (_tryParseCache.ContainsKey(typeof(T)))
	return _tryParseCache[typeof(T)] as Expression&lt;Func&lt;string, T, object&gt;&gt;;

    MethodInfo tryParse = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });
    Ensure.IsNotNull(tryParse, string.Format("Cannot convert from type string to type {0} because {0} does not have a TryParse method", typeof(T).FullName));

    var stringArg = Expression.Parameter(typeof(string), "input");
    var tempArg = Expression.Parameter(typeof(T), "tmp");

    var tryParseEx = Expression.Lambda&lt;Func&lt;string,object&gt;&gt;(
        Expression.Condition(
            Expression.Call(tryParse, stringArg, tempArg)
                , Expression.Convert(tempArg, typeof(object))
                , Expression.Constant(null))
        , stringArg, tempArg);
    _tryParseCache.Add(typeof(T), tryParseEx);
    return tryParseEx;
}

So here we have some code looking for a TryParse method, and building an expression (using Linq Expression Trees) to execute it.  Now, I’ll be honest, this is not the code I’m using in the project where this originally came from…mostly because I didn’t think of it then.  In that case I’m actually doing a big case statement, checking the type of T and running the appropriate method.  This is much shorter, but potentially much slower at runtime.  So that is where the _tryParseCache comes in.  This is a simple static dictionary which contains the expressions created for each of the types, which means you only get the runtime performance hit once when you first ask to parse a specific type.  The declaration for this object looks like this:

private static Dictionary _tryParseCache = new Dictionary();

There you have it, my first (and possibly last??) contribution into the world of extension methods. Please commence criticisms

We had a friend visiting from out of town last night, and she is apparently fond of “Top Chef”.  This was the first time I had encountered this particular “reality” based show, and I found in a lot of ways it was like the majority of the rest of the shows out there; trying hard to create drama where there really isn’t any.  In this particular episode there was a challenge to cook food for a neighborhood block party.  The group that did the worst in this particular case cited the fact that they were preparing food for everyone including kids, as a reason for not getting jiggy with the menu (in a culinary sense).  The response from the judges was that good food would speak for itself, and they should have considered it their responsibility to raise the collective bar of quality for the neighborhood.

I find this quite interesting because it mirrors an internal dilemma I am facing with the code I am currently putting together.  The dilemma is this:  Should I create things which are more “advanced” and more difficult for those who are not familiar with the concepts, or should I take the audience into consideration, and forego some of the more advanced concepts in favor of simplicity and discoverability?

My gut tells me that I should do the latter.  I’m a big believer in the power of writing code that is easy to understand and maintain.  This is particularly true whenever you are writing code which will potentially be consumed by other developers working within the application.  If someone cannot figure out how to utilize the work you’ve done, then chances are they are going to go off and duplicate it.  The eventual result of this being half a dozen ways to accomplish what is basically the same thing.

The idea brought up on the show seems to go against this philosophy by suggesting that you have the ability to expand the pallets of those who are consuming your work (the food metaphor is staring to get pretty rich here), and so you would be doing them a disservice not to.  In my case, I’ve found places where my choice to keep things more like what everyone is used to has added complexity and ugliness elsewhere. 

So does this mean I should forge ahead and present concepts which are going to be new to others on the team, and potentially create code that will not be re-used as it should because it does not make sense to those needing to re-use it?  If I don’t introduce these concepts am I missing an opportunity to bring up the overall quality of the code being by everyone?  Am I just struggling to fid answers to questions that I really shouldn’t be asking, since the YAGNI police are keeping their eyes on things?

About two weeks ago I crafted my first Fluent Interface.  Since then I’m finding myself seeing more and more places where I think such an approach would be useful.  The part that I’m finding odd is that it is something that just recently became a possibility for me.  The big motivating factor behind that I believe was reading the post that Martin Fowler did on the subject, in which he basically describes it as a super-great idea (okay, I’m paraphrasing, but you get the idea).  The concept is fairly simple; write an API that reads like a sentence. 

This isn’t a new concept, in fact I seem to recall reading quite a bit in the world of agile and TDD in which the authors encourage you to make method/property/variable names verbose and more like natural language in order to improve readability of code, and make the items more self-documenting.  I think the big difference, though, is that fluent interfaces tend to be more granular.  Instead of a single method that reads like a sentence, you are building a sentence using method and property names, with Intellisense there to help you determine what is possible at the end.

The big shift, I think, is in the realization that within this context method names like With, For, and And are perfectly okay, and as a matter of fact make things better in the end.  Its like a taboo has been lifted, and suddenly I have a whole new landscape of possibilities opened up.

Since the original implementation of a small fluent interface I created for a small part of my project (I’m using it to describe discrete elements of a document to be parsed), I’ve found myself creating a new fluent interface to play with .Net 3.5 extension methods (replicating the Ruby 10.Minutes.Ago semantics), and also adding a new interface to the same production project as the first which is being used to grab component services from my IoC container.

I’m not sure if this is a new paradigm, or just a new hammer looking for nails, but it is interesting none-the-less. It has also opened up new challenges around testing and intellisense documentation, which I’ve not quite figured out yet.

I ran into this issue today when trying to find a quick and dirty script to enforce redirection from HTTP to HTTPS for an intranet site we’re enabling for HTTPS (yes, I know SSL on an intranet???  One word – Audit).  I thought this would be easy…I half expected that there would be an IIS setting to handle this for me; I was wrong on both counts.  So what I ended up doing is using an old DNN HttpModule which was set up to allow the user to specify specific tabs in DNN for SSL, and greatly simplifying things to work to my advantage.  I thought I would post it so I wouldn’t have to look for it again.

To give a quick overview of what is going on, this is an HTTP Module which looks at a value in the web.config to determine whether or not to enforce HTTPS or not.  If the setting is set to true (or yes), then I’m just grabbing the Url property from the Request object, loading it up in a UriBuilder, and setting the Scheme to “https”, and the port to 443 (this may not be necessary, but it was generating an URL with a port of 80 before, which defeats the purpose so I decided to play it safe).  It then feeds the generated URI to Response.Redirect(), and your off.  There is some additional code in there to disable the feature if your on localhost, which is mostly to keep from blowing up your dev box.

Here is the class:

using System;
using System.Configuration;
using System.Web;


namespace HTTPSRedirectHandler
{
    /// <summary>
    /// An HttpModule which redirects traffic to HTTPS based on configuration settings.
    /// </summary>
    public class HttpsRedirector : IHttpModule
    {
        HttpApplication _context;

        public HttpsRedirector()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        /// <summary>
        /// Initializes a module and prepares it to handle
        /// requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the
        /// module that implements <see langword="IHttpModule."/>
        /// </summary>
        public void Dispose()
        {
            _context.BeginRequest -= new EventHandler(context_BeginRequest);
            _context.Dispose();
        }

        #endregion

        /// <summary>
        /// Handles the BeginRequest event of the current Http Context.
        /// </summary>
        private void context_BeginRequest(object sender, EventArgs e)
        {
            bool useSSL = false;
            string result = null;
            if((result = ConfigurationSettings.AppSettings["RequireSSL"]) != null)
            {
                if(result.ToUpper() == "TRUE" || result.ToUpper() == "YES")
                    useSSL = true;
            }
            if (useSSL)
                EnforceSSL();
        }

        /// <summary>
        /// Enforces a redirection to HTTPS if the current connection is using HTTP (port 80).
        /// </summary>
        private void EnforceSSL()
        {
            if(_context.Request.ServerVariables["SERVER_NAME"].ToLower() != "localhost")
            {
                if(_context.Request.ServerVariables["SERVER_PORT"] == "80")
                {
                    UriBuilder uri = new UriBuilder(_context.Request.Url);
                    uri.Scheme = "https";
                    uri.Port = 443;
                    _context.Response.Redirect(uri.ToString());
                }
            }
        }
    }
}

 

Here is the web.config settings you need to use it:

<httpModules>
    <add name="SSLRedirect" type="HTTPSRedirectHandler.HttpsRedirector, HTTPSRedirectHandler" />
</httpModules>
 
<appSettings>
<add key="RequireSSL" value="True" /> </appSettings>