4

I want to save/run custom tools on a handful of .tt files from my extension. I don't want to loop over all the files in the solution/project, rather I want to be able to use a relative (or full) path of the file to execute a save/run custom tool.

Is there a way to get a ProjectItem object given a path of the file ($(SolutionDir)/MyProject/MyFile.tt) so I can execute methods on it?

Omar
  • 39,496
  • 45
  • 145
  • 213

1 Answers1

5

You can use the FindProjectItem method of the EnvDTE.Solution type to find a file within the current solution by its name. The ExecuteCommand method is dependent on the current UI context; so the item must be selected, otherwise, the call fails.

private bool TryExecuteTextTemplate(string filename)
{
    var dte = (DTE2)this.GetService(typeof(SDTE));
    Solution solution = dte.Solution;
    if ((solution != null) && solution.IsOpen)
    {
        VSProjectItem projectItem;
        ProjectItem item = solution.FindProjectItem(filename);
        if (item != null && ((projectItem = item.Object as VSProjectItem) != null))
        {
            // TODO: track the item in the Solution Explorer

            try
            {
                projectItem.RunCustomTool();
                return true;
            }
            catch (COMException) 
            { 
            }
        }
    }

    return false;
}
Matze
  • 5,100
  • 6
  • 46
  • 69
  • 6
    Instead of `item.DTE.ExecuteCommand("Project.RunCustomTool");`, I had to use the `(item.Object as VSProjectItem).RunCustomTool();` – Omar Jul 12 '13 at 18:26
  • 1
    as Omar said (dte.Solution.FindProjectItem(path).Object as VSProjectItem).RunCustomTool() worked for me too. Reference to VSLangProj.dll was also needed. – Prabu Jul 31 '15 at 10:22