PRB: ProjectItem.FileCodeModel returns null for Visual Studio 2005 Web projects if the file is not open

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio 2005
Date: February 2006    

This article describes a change of behavior retrieving the ProjectItem.FileCodeModel in Visual Studio 2005 Web projects.

More Information

In Visual Studio .NET 2002/2003 projects, you could retrieve the ProjectItem.FileCodeModel of project items belonging to Web projects even if the project item was not open. In Visual Studio 2005, ProjectItem.FileCodeModel returns null (Nothing) in the same circumstances. The following macro allows you to test the different behaviors:

Sub GetFileCodeModel()

   Dim objProjectItem As ProjectItem



   Catch ex As System.Exception

   End Try

End Sub

Sub GetFileCodeModelRecursively(ByVal colProjectItems As ProjectItems)

   Dim objProjectItem As ProjectItem

   If Not (colProjectItems Is Nothing) Then

      For Each objProjectItem In colProjectItems

         If objProjectItem.FileCodeModel Is Nothing Then
            MessageBox.Show(objProjectItem.Name & " FileCodeModel is nothing")
            MessageBox.Show(objProjectItem.Name & " FileCodeModel is NOT nothing")
         End If



   End If

End Sub

When you run the macro with a Web project and no document window is open, Visual Studio .NET 2002/2003 returns a non-null FileCodeModel for .aspx.vb and .aspx.cs files while Visual Studio 2005 doesn't.

The workaround is to open the code window invisibly before trying to retrieve the file code model, and close it afterwards:

Dim objProjectItem As ProjectItem
Dim objWindow As Window
Dim bHasOpenWindow As Boolean

bHasOpenWindow = objProjectItem.IsOpen(EnvDTE.Constants.vsViewKindCode)
If Not bHasOpenWindow Then
   objWindow = objProjectItem.Open(EnvDTE.Constants.vsViewKindCode)
End If

' TODO: retrieve file code model

If Not bHasOpenWindow Then
End If

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