Omitting and Including Debug Code
I'm working on an application that allows users to retrieve and then filter/sort their data. The rules for filtering the data seem especially bizarre to me (there are actually two sets of filters) and the users keep piling on requirements.
Since I'm modifying existing code (and don't want to take the time to rip it all out and start over again) I've been including some code to print out useful information to the Output window that helps me debug problems. I don't want this code to go into production, of course, because it would slow the application down microscopically.
I've also got to test how this whole application works based on the security of the particular user. The application determines what security to apply by reading my Windows logon Id and then validating that against a table of users. Changing my security settings would require me to log off and log back on as another user every time I wanted to run through a set of tests. To simplify testing, therefore, I've put in a backdoor that lets me arbitrarily set my security level. I really don't want that code to make it into production.
The Conditional attribute is what saves my Canadian bacon here. I simply include my offending code in a method and mark it with the Conditional attribute. I pass the Conditional attribute some test that checks a compiler variable to see if the method should be included. This example checks to see if a constant called DEBUG is present:
Public Sub AssignSecurity
I use the DEBUG constant because it's automatically included by Visual Studio when you're compiling in debug mode…and automatically excluded when you compile in release mode (though you can override that).
As you can imagine, I still worry that my security bypass code will make it into production. To help ensure that it doesn't, I have another method, that puts a big red "IN TEST MODE, NOT SECURE" message on the title screen when I'm running in non-secure mode. In addition, before arbitrarily setting the security settings, my code looks for a digitally encrypted key only installed on my development machine. I still worry ... but I can live with that.
Posted by Peter Vogel on 03/11/2015 at 2:20 PM