views:

354

answers:

3

In any (non-web) .net project, the compiler automatically declares the DEBUG and TRACE constants, so I can use conditional compiling to, for example, handle exceptions differently in debug vs release mode.

For example:

#if DEBUG
    /* re-throw the exception... */
#else
    /* write something in the event log... */
#endif

How do I obtain the same behavior in an ASP.net project? It looks like the system.web/compilation section in the web.config could be what I need, but how do I check it programmatically? Or am I better off declaring a DEBUG constant myself and comment it out in release builds?

EDIT: I'm on VS 2008

+2  A: 

Look at ConfigurationManager.GetSection() - this should get you most of the way there.. however, I think you're better off just changing between debug and release modes and letting the compiler determine to execute the "#if DEBUG" enclosed statements.

#if DEBUG
/* re-throw the exception... */
#else
/* write something in the event log... */
#endif

the above will work just fine, just make sure you have at least two build configurations (right-click the project you're working on and go to "Properties" there's a section in there on Builds) - make sure that one of those builds has the "define DEBUG" checked and the other does not.

Andrew Theken
Thanks, ConfigurationManager.GetSection() is what I was looking for!
Loris
+4  A: 

To add ontop of Andrews answer, you could wrap it in a method as well

public bool IsDebugMode
{
  get
  {
#if DEBUG 
    return true;
#else
    return false;
#endif
  }
}
TheCodeJunkie
A: 

This is what I ended up doing:

protected bool IsDebugMode
{
    get
    {
        System.Web.Configuration.CompilationSection tSection;
        tSection = ConfigurationManager.GetSection("system.web/compilation") as System.Web.Configuration.CompilationSection;
        if (null != tSection)
        {
            return tSection.Debug;
        }
        /* Default to release behavior */
        return false;
    }
}
Loris