Unable to cast DTE, project or solution to VCProject and VCCodeModel
Asked Answered
N

1

7

I am trying to get some information about c+= programs, through code. I have had some success with EnvDTE, now I need to use VCProject and VCCodeModel and I am running into casting problems (hope that is all...)

In the working class, I have a DTE "application" passed from the Connect.

I have:

EnvDTE.Project project = application.SelectedItems.Item(1).Project;
EnvDTE.Solution sol = (EnvDTE.Solution)application.Solution;

I would like to use "project", not the first project in the solution as the examples I have found on the web - as below - but mostly, I would like to have something that works first.

For VCProject, I have tried (off Microsoft's web site, and all other web examples):

VCProject vcProject = (VCProject)application.Solution.Projects.Item(1).Object;
MessageBox.Show(vcProject.ProjectDirectory);

or... just

VCProject vcProject = (VCProject)project.Object;

For VCCodeModel, I translated to c# http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vccodemodel.vccodeinclude.aspx:

public void GetAllIncludes()
{
  VCCodeModel vcCM = (VCCodeModel)application.Solution.Item(1).CodeModel;
  foreach (VCCodeInclude vcInclude in vcCM.Includes)
  {
    MessageBox.Show(vcInclude.DisplayName);
  }    
}

Both give exception:

"unable to cast com object of type 'system.__comobject' to interface type Microsoft.VisualStudio.VCCodeModel"
"unable to cast com object of type 'Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProjectShim' to type Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProject"

How can I set this up ? Preferably using the "project"... or application.SelectedItems... Is it possible ?

Can somebody please give me an idea? Thank you.

Nereen answered 12/12, 2012 at 23:13 Comment(1)
I know I'm quite late in here but you may want to have a look at my postChairborne
O
1

This problem arises when you try to cast CodeModel to a different VCCodeModel version. There is a VCCodeModel.dll for each VS version.

Orman answered 12/3, 2014 at 12:32 Comment(1)
I have this problem in a visual studio package which is targetet at visual studio 2010, 2012, 2013 and 2015. The only practical solution seems to be to define the types as object and rely on late binding.Coact

© 2022 - 2024 — McMap. All rights reserved.