Debugging production applications

A .NET program has two distinct compilation phases. The first phase happens at compile-time, when the language compiler creates the .exe or .dll by translating your source code into IL. The second phase happens at run-time, when the JIT compiler translates the IL into native code and then executes that code. I discussed this earlier when I talked about some potential dangers of using the code optimisation switch.

Normally, you want a production program to execute fast during normal execution. Because enabling debug tracking lowers performance a little and disabling code optimisation can lower performance significantly, you usually want to turn off debug tracking and turn on code optimisation. But when you need to investigate a production problem, you want the ability to turn debug tracking on and code optimisation off. If you could manage both of these settings on a per-execution basis without having to recompile your program, you could have the best of all possible worlds.

Step forward a configuration file called MyApp.ini, where MyApp is the name of your program. If you place an INI file with this name in the same folder as your .exe or .dll, it allows you to configure these two JIT compiler settings on a run-by-run basis. The lines in the INI file that control these settings are as follows, where 1 = true and 0 = false:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

This allows you to override the debug tracking and optimization settings that were specified when the .exe or .dll was built. It’s ideal for investigating those troublesome production problems that you’re unable to duplicate on your own machine. As long as you make sure that the correct debug symbol (.pdb) files are available, you can step through source code and do full debugging without having to recompile your production program or having to revert back to a debug version of your code.

This does means that you need to alter the default release build configuration of your projects to produce debug symbol files. To do this in Visual Studio .NET, right-click on the project in the Solution Explorer window and select Properties > Configuration Properties  > Build. Now change the Configuration dropdown in the top left of the window to read Release. Then if coding in VB, make sure that the Generate debugging information checkbox is selected. If coding in C#, make sure that the Generate Debugging Information option is set to true.

The only fly in the ointment is that you can't use this trick with a hosted environment such as ASP.NET. But for Windows Forms, console applications, Windows Services and so on, it works great.