Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable "Debug mode" in ASP.NET MVC app through the use of C# directives

My actions in ASP.NET MVC controller are decorated with numerous properties like this

    [OutputCache(Duration = 86400, Location = OutputCacheLocation.Client,
        VaryByParam = "jsPath;ServerHost")]
    [CompressFilter]
    public JavaScriptResult GetPendingJavaScript(string jsPath, string serverHost)

What I would like to do is to wrap this in something like #if and #endif, and have DebugMode setting in my web.config file. When this setting would be set to true, the decorating properties should be disregarded - I want to enable debug mode and in debug mode no compression and caching should occur.

So essentially it would be like commenting out those decorating properties (what I'm actually doing now and got fed up with it):

    //[OutputCache(Duration = 86400, Location = OutputCacheLocation.Client,
    //    VaryByParam = "jsPath;ServerHost")]
    //[CompressFilter]

Obviously #if and #endif work with defined (#define) C# symbols, I couldn't find any example where this would work with other types of condition (like web.config values, etc.).

Help appreciated

like image 756
mare Avatar asked Jan 26 '10 23:01

mare


1 Answers

Instead of this, I would make use of Web Deployment Projects, and the configSource attribute in the web.config.

I would split the web.config into two files for each component. For example, for your output cache would be split into outputcache.dev.config and outputcache.live.config. You should enter the config source as the dev config file.

Your dev.config would basically tell your app that you don't want to cache running (enableOutputCache="false").

Then, when you run your deployment project, you can have settings to replace the dev.config strings with live.config instead.

More discussion on configSource and Web Deployment Projects.

As for your CompressFilter problem... Well, I would simply have an app setting value in your config files. Following on from splitting the config files, you would have appsettings.dev.config, and appsettings.live.config. In your dev, you would have something like:

<add key="InLiveMode" value="false" />

And in your live.config, yep, you've guessed it:

<add key="InLiveMode" value="true" />

Then when you use the attribute, you can simply against the InLiveMode app setting.

FYI: I much prefer having some sort of facade class so I'm not dealing with magic strings in the code, but for the sake of simplicity, you'd have something like:

//CompressFilter class
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
  bool inLiveMode = bool.Parse(ConfigurationManager.AppSettings["InLiveMode"]);

  if(inLiveMode)
  {
    //Do the compression shiznit
  }
}
like image 91
Dan Atkinson Avatar answered Sep 26 '22 04:09

Dan Atkinson