Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect a list of user classes in a project using EnvDTE

Tags:

c#

t4

envdte

I am having a problem creating a way to list all the classes in my project using EnvDTE for templating interfaces using T4 (based on naming conventions), and none of the documentation out there seems to describe how to do it. I started out with:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ Assembly name="EnvDTE" #>
<#@ Assembly name="System.Core" #>
<#@ import namespace="EnvDTE" #>
<#@ Import Namespace="System.Linq" #>
<#@ Import Namespace="System.Collections.Generic" #>
<#
    var env = (DTE)((IServiceProvider)this.Host)
        .GetService(typeof(EnvDTE.DTE));

... and then I started going sideways. I am able to identify my project, but I am not able to collect the classes in the project that I want to filter into a flat list for creating interfaces for.

How can I do this? I just want the classes in my project.

like image 547
Jeremy Holovacs Avatar asked Jan 15 '13 20:01

Jeremy Holovacs


1 Answers

Since you are using T4 i would suggest you check out the tangible T4 Editor. In their gallery is a free reusable Template "tangible Visual Studio Automation Helper". With this template you can easily find Code Classes etc. (See my answer to this post Design Time Reflection).

If you want to do it on your own you should continue like this:

    var project = env.ActiveDocument.ProjectItem.ContainingProject;
foreach(EnvDTE.CodeElement element in project.CodeModel.CodeElements)
{
    if (element.Kind == EnvDTE.vsCMElement.vsCMElementClass)
    {
        var myClass = (EnvDTE.CodeClass)element;
        // do stuff with that class here
    }
}

I removed the recursion that would be necessary. A CodeElement can contain other CodeElements. But this way it's easier to read.

like image 100
Nico Avatar answered Nov 01 '22 21:11

Nico