Second Life of a Hungarian SharePoint Geek

June 12, 2009

I got tired of attaching debugger to w3wp.exe. And you?

Filed under: Debugging, SharePoint — Tags: , — Peter Holpar @ 04:18

As a SharePoint developer, I spend most of my days developing and testing web parts, custom pages, fields and event receivers. Part of this activity is debugging, where one should attach the debugger to the w3wp.exe process instance that belongs to the application pool of the web site we developing on.
If you have done that yet, you know it is not an exciting task to select the correct process if you have dozens of instances. You can do that by trial and error, and checking if the red lights next to the breakpoints are turned on, or you should look for the next instance. It is one step better to run iisapps.vbs as described here, and use the process id it displays for the correct application pool, but it is still a cumbersome manual process, that a developer does not enjoy.
Developers enjoy development, and developing tools that help development. A good platform for those tools is the Visual Studio IDE and in that environment maybe the simplest way to create tools is writing macros.
To help my job I created a macro in Visual Studio 2005 that attaches the debugger to the w3wp.exe instance of the configured application pool. I hope it works for Visual Studio 2008 too, but I have not tested it with that yet.
Configuring the name of the application pool in Visual Studio
The configuration can be done using the project properties. These properties are stored in the csproj.user file of the project, so if you use version control and work in a team, the value can be different for teammates. I selected the Command line arguments text field on the Debug tab to store the name of the application pool we want to attach the debugger to.
There might be multiple projects in the solution, and each project may be multiple configuration (like debug or release), so I decided to use the debug configuration for the first startup project. It is important, because there may be multiple startup projects in a solution.


The macro
After this introduction, let’s see the code of the macro. We need the import the following namespaces:

  1. Imports System
  2. Imports EnvDTE
  3. Imports EnvDTE80
  4. Imports System.Management
  5. Imports System.Text.RegularExpressions

The entry point for the macro is the AttachMacro sub. In that we first determine the project whose configuration we will use. If there is only a single project in the solution we can go with that, if there are multiple projects then at least one of the must be set as startup project, but only the configuration of the first one will be used.
If we found the projects, we use the GetArgumentsForDebug function (see details later) to read the application pool name from the configuration.
Finally we call the AttachToAppPool function (see details later) to attach or debugger to the process of the application pool.
  1. Public Sub AttachMacro()
  3.     Try
  4.         ' get the startup project first
  5.         Dim project As Project
  6.         Dim solutionBuild As SolutionBuild = DTE.Solution.SolutionBuild
  7.         Dim startUpProjs As Array = solutionBuild.StartupProjects
  8.         Dim projName As String
  10.         If startUpProjs.Length = 0 Then
  11.             If DTE.Solution.Projects.Count = 1 Then
  12.                 project = DTE.Solution.Projects.Item(1)
  13.             Else
  14.                 MsgBox("There is no startup project and solution contains multiple project!", MsgBoxStyle.Exclamation, "Alert")
  15.                 Exit Sub
  16.             End If
  17.         Else
  18.             projName = solutionBuild.StartupProjects(0)
  19.             project = GetProjectByName(projName)
  20.             If project Is Nothing Then
  21.                 MsgBox(String.Format("Startup project '{0}' not found by name!", projName), MsgBoxStyle.Exclamation, "Alert")
  22.                 Exit Sub
  23.             End If
  24.         End If
  26.         Dim appPoolName As String = GetArgumentsForDebug(project)
  28.         If String.IsNullOrEmpty(appPoolName) Then
  29.             MsgBox(String.Format("Command line arguments property is not set for stratup project '{0}', debug mode!", projName), MsgBoxStyle.Exclamation, "Alert")
  30.             Exit Sub
  31.         End If
  33.         Dim processFound As Boolean = AttachToAppPool(appPoolName)
  35.         If Not processFound Then
  36.             MsgBox(String.Format("No worker process found for application pool called '{0}'!", appPoolName), MsgBoxStyle.Exclamation, "Alert")
  37.             Exit Sub
  38.         End If
  40.     Catch ex As System.Exception
  41.         MsgBox(ex.Message)
  42.     End Try
  44. End Sub

The GetProjectByName function is a simple helper method to get
the project object using the name of the startup project.
  1. Private Function GetProjectByName(ByVal projectName As String) As Project
  3.     Dim result As Project = Nothing
  4.     For Each project As Project In DTE.Solution.Projects
  5.         If project.UniqueName = projectName Then
  6.             result = project
  7.             Exit For
  8.         End If
  9.     Next
  11.     GetProjectByName = result
  13. End Function

In the GetArgumentsForDebug function we read the Command line arguments value that is stored in the StartArguments parameter from the debug config of the specifed project.
  1. Private Function GetArgumentsForDebug(ByVal project As Project) As String
  3.     Dim configuration As EnvDTE.Configuration
  4.     GetArgumentsForDebug = String.Empty
  6.     For Each configuration In project.ConfigurationManager
  7.         If configuration.ConfigurationName = "Debug" Then
  8.             Dim startArgsObj As Object = configuration.Properties.Item("StartArguments")
  9.             If Not startArgsObj Is Nothing Then
  10.                 GetArgumentsForDebug = CType(startArgsObj.Value, String)
  11.             End If
  12.             Exit Function
  13.         End If
  14.     Next
  16. End Function

An interesting part of the macro is the GetProcessIdByAppPoolName function. In this function we use WMI (IMPORTANT: don’t forget to reference the System.Management assembly!) to get the list of all w3wp.exe processes, and select the one that belongs to the specified application pool. The ID of the process is returned.
In the comparison we use the GetAppPoolNameFromCommandLine function (see later), that receives the CommandLine property of the process, that looks like this for a w3wp.exe process:
c:\windows\system32\inetsrv\w3wp.exe -a \\.\pipe\iisipm5f3cda83-745a-423a-88b2-103a2f632200 -ap "MyAppPool"
You can see that the name of the application pool is at the end of the string.
  1. Private Function GetProcessIdByAppPoolName(ByVal appPoolName As String) As Long
  3.     GetProcessIdByAppPoolName = -1
  4.     Dim scope As ManagementScope = New ManagementScope("\\localhost\root\cimv2")
  6.     Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher("select * from Win32_Process where Name='w3wp.exe'")
  7.     searcher.Scope = scope
  9.     For Each process As ManagementObject In searcher.Get()
  10.         Dim commandLine As String = process.GetPropertyValue("CommandLine")
  11.         If GetAppPoolNameFromCommandLine(commandLine).ToUpper() = appPoolName.ToUpper() Then
  12.             GetProcessIdByAppPoolName = process.GetPropertyValue("ProcessId")
  13.             Exit For
  14.         End If
  15.     Next
  17. End Function

In the GetAppPoolNameFromCommandLine function we use a simple regular expression to get the name of the application pool from the CommandLine string.
  1. Private Function GetAppPoolNameFromCommandLine(ByVal commandLine As String) As String
  3.     GetAppPoolNameFromCommandLine = String.Empty
  4.     Dim re As Regex = New Regex("-ap ""(.+)""", RegexOptions.IgnoreCase)
  5.     Dim matches As MatchCollection = re.Matches(commandLine)
  6.     If matches.Count = 1 Then
  7.         If matches.Item(0).Groups.Count > 1 Then
  8.             GetAppPoolNameFromCommandLine = matches.Item(0).Groups(1).Value
  9.         End If
  10.     End If
  12. End Function

In the AttachToAppPool function we attach the debugger to the process having the same process ID that we determined earlier.
  1. Private Function AttachToAppPool(ByVal appPoolName As String) As Boolean
  3.     Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
  4.     Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
  5.     Dim dbgeng(3) As EnvDTE80.Engine
  6.     dbgeng(0) = trans.Engines.Item("T-SQL")
  7.     dbgeng(1) = trans.Engines.Item("T-SQL")
  8.     dbgeng(2) = trans.Engines.Item("Managed")
  10.     AttachToAppPool = False
  11.     For Each process As EnvDTE80.Process2 In dbg2.LocalProcesses
  12.         If process.ProcessID = GetProcessIdByAppPoolName(appPoolName) Then
  13.             process.Attach()
  14.             AttachToAppPool = True
  15.             Exit For
  16.         End If
  17.     Next
  19. End Function

To make things even more comfortable it is the best to assign a keyboard shortcut to the macro using the Visual Studio Tools/Options… menu item as shown on the screenshot below:

1 Comment »

  1. […] method and attaching the debugger to the worker process, so you can catch the event if it fired. One of my former posts shows you how to attach the debugger […]

    Pingback by My event receiver doesn’t fire « Second Life of a Hungarian SharePoint Geek — February 15, 2010 @ 01:00

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: