This post outlines one way to safely disable specific code blocks through the use of conditional compilation statements which can be useful for the purposes of debugging. The approach taken in this article also aims to eliminate the risk of any such code getting accidentally disabled in a production environment.
A common scenario where you might want to disable or skip some code during debugging is in the case of an Authorization method which checks the credentials of a calling client. Consider the AuthorizeClient method pseudo code below
private void AuthorizeClient()
{
if(!ClientAuthorised(userIdentity)
{
throw new AuthorisationException(UnauthorizedUserMessage);
}
}
By putting the code inside a conditional DEBUG compile region, you can ensure that this check will only be skipped if the code is compiled in debug mode.
private void AuthorizeClient()
{
#if DEBUG
return;
#endif
if(!ClientAuthorised(userIdentity)
{
throw new AuthorisationException(UnauthorizedUserMessage);
}
}
However, sometimes it might be useful to perform the validation check in debug mode. For example, you might want to ensure that the validation is still working properly after making some changes.
In this case, you can add a configuration element to the application’s app.config file which can then be set to the value desired. Through the use of xml pre-processing we can also ensure that this key\value pair is populated only in a development environment thereby preventing the configuration file from getting littered with unused settings
1.) Put a key\value into the app.config file. This setting will only be present when the application is compiled in a developer environment as per your environmental settings
<!–#ifdef ${DEV_Environment}–>
<add key=“DisableAuthorityCheck” value=“true”/>
<!–#endif–>
2.) Modify the AuthorizeClient method to additionally check for the value of the DisableAuthorityCheck setting if it is present in the config file
private void AuthorizeClient()
{
#if DEBUG
if(ConfigurationManager.AppSettings.AllKeys.Contains("DisableAuthorityCheck")&& ConfigurationManager.AppSettings.Get("DisableAuthorityCheck") == "true")
return;
#endif
if(!ClientAuthorised(userIdentity)
{
throw new AuthorisationException(UnauthorizedUserMessage);
}
}
The approach outlined above is however not without it’s drawbacks. For example, overuse will result in code being littered with conditional compile blocks which may bloat the code and make it less readable.