Logo
BUG: EnvDTE.CodeFunction.Attributes doesn't work with C# property get/set methods in Visual Studio macros or add-ins

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

Introduction

When you have a C# property the attributes applied to its get/set methods are not returned by the file code model when calling EnvDTE.CodeFunction.Attributes. The file code model retrieves attributes correctly if the property is written in VB.NET instead.

More Information

Steps to reproduce the problem:

  • Create a class with this code:
Language: C#   Copy Code Copy Code (IE only)
namespace Namespace1
{
   [System.AttributeUsage(System.AttributeTargets.All)]
   public class MyAttribute: System.Attribute
   {
   }
   
   public class Class1
   {
      internal int Property1
      {
         [MyAttribute()]
         get
         {
            return 1;
         }
         [MyAttribute()]
         set
         {
         }
      }
   }
}
  • Create and execute this macro:
Language: VB.NET   Copy Code Copy Code (IE only)
Sub Macro1()

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

End Sub

Sub ShowAttributeCodeElements(ByVal codeElements As EnvDTE.CodeElements)

    Dim codeElement As EnvDTE.CodeElement
    Dim codeProperty As EnvDTE.CodeProperty
    Dim codeFunction As EnvDTE.CodeFunction

    For Each codeElement In codeElements

        If TypeOf codeElement Is EnvDTE.CodeNamespace Then

            ShowAttributeCodeElements(DirectCast(codeElement, CodeNamespace).Members)

        ElseIf TypeOf codeElement Is EnvDTE.CodeType Then

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

        ElseIf TypeOf codeElement Is EnvDTE.CodeProperty Then

            codeProperty = DirectCast(codeElement, EnvDTE.CodeProperty)

            codeFunction = codeProperty.Getter
            If Not (codeFunction Is Nothing) Then
                MessageBox.Show(codeFunction.FullName & ".get: " & codeFunction.Attributes.Count.ToString & " attributes")
            End If

            codeFunction = codeProperty.Setter
            If Not (codeFunction Is Nothing) Then
                MessageBox.Show(codeFunction.FullName & ".set: " & codeFunction.Attributes.Count.ToString & " attributes")
            End If

        End If

    Next

End Sub


Go to the 'Visual Studio Extensibility (VSX)' web site for more articles like this (Articles section)


Top