Conditional Compilation

Have you ever been in a situation where your application needs to behave one way in development and another in production? Perhaps you only want to send an email if the application is on the live server, or you’re developing an ASP.NET MVC application and need to add the [RequireHttps] attribute – but only if the code is running on the production server.

It’s a different problem from changing connection strings between live and development versions. That’s easy – you just need different config settings for Release and Debug. (We show you how to do this in Building Web Applications with ASP.NET and Ajax). But how do you change behavior? The answer turns out to be surprisingly simple – by using conditional compilation.

The problem:

  1. Visual Studio does not include an SMTP server. If you try to run code that sends emails, you will get an exception – but not if you tell the system not to compile the send line unless you are in release mode.
  2. In ASP.NET MVC, the [RequireHttps] (VB: <RequireHttps>) attribute on a controller redirects a request from HTTP to HTTPS. The login Action method needs it if it is going to be secure – but it won’t work in Visual Studio. Unless, that is, you tell the compiler only to add the attribute in Release mode.

Here is the solution using C#:

#if !DEBUG

   [RequireHttps]

#endif

Now the attribute will only be added if the page is not being compiled in debug mode. To change between compilation modes, just change the selected configuration in the dropdown in the Visual Studio toolbar.

Exactly the same approach works with code as well as attributes – thus solving our email problem.

Here is the solution in VB:


Dim m As New MailMessage(Me.FromTextBox.Text, Me.ToTextBox.Text, Me.SubjectTextBox.Text, Me.BodyTextBox.Text)

Dim s As New SmtpClient(“localhost”)

#If Not Debug Then

     s.Send(m)

#End If

Conditional compilation is a simple technique that’s been around for a long time, but it remains enormously useful. Combined with different config files for different compilations, it allows you to customize your build to do just what it needs to do in a particular setup.

Kevin Rattan

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.