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.
Here is the solution using C#:
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
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.