Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my code break when transitioning to .NET Framework 4.0

Tags:

c#

.net

I'd like to cause compiler errors local to methods that need to be changed once I make the transition to .NET Framework 4.0. See below:

Oops, while this is just an example, this code totally does not work, something I just realized. (a corrected version is available at the end, if you ever need this kind of functionality)

// ASP.NET 3.5 does not contain a global accessor for routing data
// this workaround will be used until we transition to .NET 4.0

// this field still exists in .NET 4.0, however, it is never used
// GetRouteData will always return null after the transition to .NET 4.0

static object _requestDataKey = typeof(UrlRoutingModule)
    .GetField("_requestDataKey", BindingFlags.NonPublic | BindingFlags.Instance)
    .GetValue(null)
    ;

public static RouteData GetRouteData(this HttpContext context)
{
    if (context != null)
    {
        return context.Items[_requestDataKey] as RouteData;
    }
    // .NET 4.0 equivalent
    //if ((context != null) && (context.Request != null))
    //{
    //    return context.Request.RequestContext.RouteData;
    //}
    return null;
}

Does anyone know of a trick that results in a compiler error once the transition is made?

This code actually does what the original version intended. This code is also not specific to the 3.5 version of the runtime, however, there are simpler yet ways of getting at the route data in 4.0.

if (context != null)
{
    var routeData = context.Items["RouteData"] as RouteData;
    if (routeData == null
        && !context.Items.Contains("RouteData"))
    {
        context.Items["RouteData"] = routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
    }
    return routeData;
}
like image 626
John Leidegren Avatar asked Jan 21 '23 18:01

John Leidegren


1 Answers

I think there is no built-in preprocessor symbol, but you could roll your own:

public static RouteData GetRouteData(this HttpContext context) 
{
    if (context != null)     
    {         
       return context.Items[_requestDataKey] as RouteData;     
    }
#if NET_4
#error Review code for .NET
#endif

    // .NET 4.0 equivalent     
    //if ((context != null) && (context.Request != null))     
    //{     
    //    return context.Request.RequestContext.RouteData;     
    //}     
    return null; 
} 

Then, when you compile your projects for .NET 4, add the "NET_4" symbol to the compiler's symbols (via VS.NET project properties or directly in the .csproj file).

Of course, this requires that you know the places of interest (i.e. via code review). I think there is no way to have it happen automatically.

like image 149
Christian.K Avatar answered Jan 31 '23 01:01

Christian.K