Wednesday 3 November 2010

Debugging code started from the Global.asax Application_Start event when using IIS 7 integrated pipeline

The new integrated pipeline with IIS7 is good... I think!? what I mean is that I know its good under the bonnet but it really doesn't affect me much once my website is running. So lets assume that we have converted our web.config to use integrated pipeline and everything is working fine... (this alone can take a while, but that's another blog...)

Then one day you need to step into some code that occurs whenever the Application_Start event fires from Global.asax... You find that even though you have breakpoints in the code, they appear to be ignored and the application starts up. The trick to getting into this code is...

  1. Run the website from visual studio - allow it to start normally - your breakpoints will be ignored as usual.
  2. Edit the web.config file - just adding a space character and then re-saving will do - you don't actually have to change any settings. 
  3. Editing the web.config in any way will cause the application to stop.
  4. Make a request to the website e.g. request a page, web service etc. This will cause the application to start.
  5. Because we are ALREADY attached to the process with the visual studio debugger, we will now get to step into the application_start event. 
  6. debugging joy!
I believe the reason we cant step into the application_start on normal visual studio debug startup is because by the time we have attached to the website process, the application_start event has already occurred.

This solution may not work if you are unable to make the website run in the first place, i.e. if the code in application_start doesn't allow the website to run because it is faulty/buggy etc.

Solutions that didnt work but looked good at the time...

  1. Visual Studio > Web site project property pages > Start Options > Start Action > Select "Dont open a page. Wait for a request from an external application" - I thought this would perhaps delay the first request to IIS and therefore delay application_start - meaning that when we do request a page, our debugger would be attached. This doesnt work though as the application will start regardless of this option. There must be another request sent from visual studio during the start up of the debugger. Todo: we should really investigate this by analysing the requests made to IIS when we start the debugger. There may be another setting?
  2. Recycling the application pool associated with the website you are debugging - unfortunately although this does cause application_event to fire, it also causes visual studio to detach from the process! No stepping in goodness to be had here :(