Pages

Tuesday, June 18, 2013

Conditionally exclude portions of ASP.NET Web application code (.NET)

Those of you with roots in Visual Basic might have long envied its ability to exclude a section of code based on the value of a conditional compilation constant. Well, envy no more: A new and improved solution to this problem is available right now in ASP.NET. Here’s how it works.

Start by opening the Properties dialog box for your ASP.NET project. Select Configuration Properties and then select Build. In the bottom half of the dialog box, you should see mention of the Conditional Compilation Constants you seek. Note that two are predefined: DEBUG and TRACE. There's also a field where you can define your own constants.

To mark a procedure so that it will respect a defined constant, simply reference the Conditional field in your procedure declaration, as shown here:

<Conditional(“StagingServer”)> Sub MyProc()
‘Code that might need to be ignored
End Sub


If the constant was set in the project’s properties, then it will be excluded—simple as that! And in an improvement over the old Visual Basic conditional compilation, even the calls to the excluded code will be excluded themselves. In VB 6.0, on the other hand, the marked code would be excluded, but calls to that code could still be attempted, resulting in compilation errors.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.