Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code only in debug mode in ASP.NET

I have an ASP.NET web application and I have some code that I want to execute only in the debug version. How to do this?

like image 863
Omu Avatar asked Nov 14 '09 16:11

Omu


People also ask

How do I run a .NET debug?

You can do this by clicking on the arrow next to Run button in Visual Studio and selecting 'Project Debug Properties'. From there, you can go to 'Application Arguments' and enter the arguments you want.

How do I skip a line while debugging in Visual Studio?

You can also click on the line you want to skip to and hit Ctrl+F10 (Run to Cursor). It will jump directly to that line.

How do I enable debugging in web config?

In the Web. config file, locate the compilation element. Debugging is enabled when the debug attribute in the compilation element is set to true. Change the debug attribute to false to disable debugging for that application.


3 Answers

#if DEBUG
your code
#endif

You could also add ConditionalAttribute to method that is to be executed only when you build it in debug mode:

[Conditional("DEBUG")]
void SomeMethod()
{
}
like image 78
empi Avatar answered Oct 19 '22 13:10

empi


Detecting ASP.NET Debug mode

if (HttpContext.Current.IsDebuggingEnabled)
{
    // this is executed only in the debug version
}

From MSDN:

HttpContext.IsDebuggingEnabled Property

Gets a value indicating whether the current HTTP request is in debug mode.

like image 27
dtb Avatar answered Oct 19 '22 14:10

dtb


I declared a property in my base page, or you can declare it in any static class you have in applicaition:

    public static bool IsDebug
    {
        get
        {
            bool debug = false;
#if DEBUG
            debug = true;
#endif
            return debug;
        }
    }

Then to achieve your desire do:

    if (IsDebug)
    {
        //Your code
    }
    else 
    {
        //not debug mode
    }
like image 11
Shimmy Weitzhandler Avatar answered Oct 19 '22 12:10

Shimmy Weitzhandler