QuickTip: Attach the VS Debugger to IIS’s Worker Process in a single keystroke

I’ve been spending a lot of time lately debugging through some web-hosted applications.  Some of these applications are hosted by Visual Studio’s own internal web server (Cassini), and others are hosted by my local instance of IIS.

Web projects hosted locally get automatic attached to the VS debugger when you press F5.  Projects hosted under IIS do not.  In order to debug IIS hosted projects, you must attach the Visual Studio debugger to the IIS worker process (aspnet_wp.exe or w3wp.exe) manually. 

Traditionally, you attach by selecting Attach To Process from the Debug menu, scrolling the list of processes until you find the worker process and then clicking “Attach”.

Thanks to this handy macro I found by HologramX at snipplr.com, I’m able to attach with a single keystroke:

To add this macro to your environment,  Tools > Macro IDE > Add new item to MyMacros > Select Module, Name 'AttachToWebServer' > Copy/paste code.

Code Snippet

  1. Imports System

  2. Imports EnvDTE80

  3. Imports System.Diagnostics

  4. Public Module AttachToWebServer

  5.     Public Sub AttachToWebServer()

  6.         Dim AspNetWp As String = "aspnet_wp.exe"

  7.         Dim W3WP As String = "w3wp.exe"

  8.         If Not (AttachToProcess(AspNetWp)) Then

  9.             If Not AttachToProcess(W3WP) Then

  10.                 System.Windows.Forms.MessageBox.Show(String.Format("Process {0} or {1} Cannot Be Found", AspNetWp, W3WP), "Attach To Web Server Macro")

  11.             End If

  12.         End If

  13.     End Sub

  14.     Public Function AttachToProcess(ByVal ProcessName As String) As Boolean

  15.         Dim Processes As EnvDTE.Processes = DTE.Debugger.LocalProcesses

  16.         Dim Process As EnvDTE.Process

  17.         Dim ProcessFound As Boolean = False

  18.         For Each Process In Processes

  19.             If (Process.Name.Substring(Process.Name.LastIndexOf("\") + 1) = ProcessName) Then

  20.                 Process.Attach()

  21.                 ProcessFound = True

  22.             End If

  23.         Next

  24.         AttachToProcess = ProcessFound

  25.     End Function

  26. End Module

To set as a keyboard shortcut go to Tools > Options > Keyboard, and search for the name of the macro (AttachToWebServer) and then assign a keyboard shortcut.

IIS-Attached Debugging is now one keystroke away.

This article is part of the GWB Archives. Original Author: ChrisD

New on Geeks with Blogs