Compiling Conditional Code into ASP.NET Websites

Posted by: Malcolm Sheridan , on 6/20/2009, in Category ASP.NET
Views: 33083
Abstract: The following article demonstrates how to compile conditional code into your ASP.NET assembly.
Compiling Conditional Code into ASP.NET Websites
 
In the software development lifecycle, there are three streams of environments; development, testing and production. For development environments you normally have extra information that is running to make the debugging experience easier, but for test and production environments you want that turned off so you can squeeze that extra bit of performance out of the application. Doing this can be a challenge without littering your source code with #if #else conditional compilation statements. Well this task is made simpler by the System.Diagnostics.ConditionalAttribute class. This class indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined. By using this class you can define builds for development environments so that debug or trace statements can be executed, and for production this can be removed from the assembly altogether.
To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. 
For this example, I want to demonstrate how to use conditional compilation statements to create different assemblies. I’ll create two builds; one for development and one for production. For development I want debugging information rendered in the browser, and for production I want that removed.
 
Getting started add a new class to the application and name it DebugOnly. As the name suggests this is for debug purposes only. Add the following code to the class:
 
C#
 
public class DebugOnly
{
      [Conditional("DEVELOPMENT")]
      public void ShowDebugControls(System.Web.UI.WebControls.Label lbl)
      {
            lbl.Text = "Debug control displayed at: " +                                   DateTime.Now.ToString();        
            lbl.Visible = true;
      }
}
 
VB.NET
 
Public Class DebugOnly
       <Conditional("DEVELOPMENT")> _
       Public Sub ShowDebugControls(ByVal lbl As System.Web.UI.WebControls.Label)
                  lbl.Text = "Debug control displayed at: " & DateTime.Now.ToString()
                  lbl.Visible = True
       End Sub
End Class
 
What makes the code special is that the method has been decorated with the Conditional attribute. The Conditional attribute accepts one parameter which is the string condition. This tells the compiler that this method should only be compiled if the conditional compilation symbol, DEVELOPMENT, is defined. 
 
Jumping back to the Default.aspx page you’ll need to add a Label control to the page:
 
<asp:Label ID="lblDebug" runat="server" Visible="false" />
 
I will use this control to display some debugging information. Open the code behind file and add the following code:
 
C#
 
protected void Page_Load(object sender, EventArgs e)
{
      DebugOnly debug = new DebugOnly();
      debug.ShowDebugControls(lblDebug);
}
 
VB.NET
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Dim debug As New DebugOnly()
       debug.ShowDebugControls(lblDebug)
End Sub
 
There is nothing special about the code above. An object reference is being created and the method is being called. But we only want this executed if this is a development build. To make this happen you need to right click the project in the Solution Explorer and select Properties:
 
Project_Properties
 
The project properties window is open. Click on the Build tab and enter DEVELOPMENT in the conditional compilation symbols text box:
 
Build_Tab_Development
 
If you run the project you’ll see the Label is now visible and has bugging information that looks similar to this:
 
Debug control displayed at: 17/06/2009 11:40:17 PM
 
Moving on let’s assume we are happy with the code and are ready to deploy into production. Update the conditional compilation symbol from DEVELOPMENT to PRODUCTION. Run the project again.
 
Build_Tab_Production
 
See anything different? The label is not visible. How is this possible even though we have coded it to call the debug code in the page load event? Well the answer lies with the conditional compilation symbol. Because PRODUCTION was defined, the compiler has removed any code that references the methods decorated with [Conditional("DEVELOPMENT")].
 
To see what’s happening under the covers you’ll need to open ILDASM. ILDASM is an MSIL Disassembler tool that contains Microsoft intermediate language (MSIL) code. This is normally located in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin. Once it is opened, on the file menu select File > Open. Navigate to the current projects bin directory and add the projects assembly. ILDASM loads the two classes defined in the project; Default and DebugOnly:
 
Project_ILDASM
 
If you expand _Default you will be able to see the Page_Load event. Double click this and a new window will open displaying the IL for the code:
 
IL_1
 
The code that was calling the debug methods has been removed from the assembly. If we changed the build from PRODUCTION to DEVELOPMENT, the IL would look like this:
 
IL_2
 
The code to call the debug method has been compiled back into the assembly. That’s pretty cool if you ask me!
 

By using conditional compilation symbols along with the System.Diagnostics.ConditionalAttribute class you can create different builds for different environments. And this is achieved without making you code unreadable and messy. Hopefully you can use this as much as I have in my projects.

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook