Logo
BUG: EnvDTE.CodeFunction.Parameters causes COM Exception with C# event add/remove methods in Visual Studio macros or add-ins

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio 2005
Date: July 2009   Microsoft Visual Studio 2008

Introduction

When you have a C# event with add/remove methods and you use the file code model to get the parameters of methods, the EnvDTE.CodeFunction.Parameters call causes a COM exception.

More Information

Steps to reproduce the problem:

  • Create a class with this code:
Language: C#   Copy Code Copy Code (IE only)
namespace ClassLibrary1
{
   public class Class1 
   {
      public event System.EventHandler Event1
      {
         add 
         { 
         }
         remove
         { 
         }
      }
   }
}
  • Create and execute this macro:
Language: VB.NET   Copy Code Copy Code (IE only)
Sub Macro1()

   Try
      ShowParametersCodeElements(DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements)
   Catch ex As System.Exception
      MessageBox.Show(ex.ToString)
   End Try

End Sub

Sub ShowParametersCodeElements(ByVal codeElements As EnvDTE.CodeElements)

   Dim codeEvent As EnvDTE80.CodeEvent
   Dim codeFunction As EnvDTE.CodeFunction

   For Each codeElement As EnvDTE.CodeElement In codeElements

      If TypeOf codeElement Is EnvDTE.CodeNamespace Then

         ShowParametersCodeElements(DirectCast(codeElement, CodeNamespace).Members)

      ElseIf TypeOf codeElement Is EnvDTE.CodeType Then

         ShowParametersCodeElements(DirectCast(codeElement, EnvDTE.CodeType).Members)

      ElseIf TypeOf codeElement Is EnvDTE80.CodeEvent Then

         codeEvent = DirectCast(codeElement, EnvDTE80.CodeEvent)

         codeFunction = codeEvent.Adder
         If Not (codeFunction Is Nothing) Then
            MessageBox.Show(codeFunction.FullName & ".add: " & codeFunction.Parameters.Count.ToString & " parameters")
         End If

         codeFunction = codeEvent.Remover
         If Not (codeFunction Is Nothing) Then
            MessageBox.Show(codeFunction.FullName & ".remove: " & codeFunction.Parameters.Count.ToString & " parameters")
         End If

      End If

   Next

End Sub

Go back to the 'Resources for Visual Studio .NET extensibility' section for more articles like this


Top