Frage

I'm trying to create a filter (one of the little folders which does nothing but separate files in a project) in a visual studio (C++) project template with a wizard, so I'm writing the following code in the RunStarted method:

public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
      try
      {
        // Add filters to the project
        EnvDTE.DTE dte = (EnvDTE.DTE)automationObject;

        Array activeProjects = (Array)dte.ActiveSolutionProjects;
        Project activeProj = (Project)activeProjects.GetValue(0);
        VCProject prj = (VCProject)activeProj.ProjectItems.Item(0);
        VCFilter filter = prj.AddFilter("Header_Files");
        filter.AddFile("header.h");
        prj.Save();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
    }

This is failing though. The error returned is:

System.IndexOutOfRangeException: Index was outside the bounds of the array.

at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)

at System.Array.GetValue(Int32 index)

at my_wizard.IMyWizard.RunStarted(Object automationObject, Dictionary`2 replacementsDictionary, WizardRunKind runKind, Object[] customParams)

Where am I getting wrong? How can I add a filter to a vs template?

War es hilfreich?

Lösung

You can find the answer here.
Some says that the issue occurs when Solution Explorer is not open.
Here is my solution based on upper link:

    private Project getActiveProject(DTE2 dte)
    {
        Array projects = dte.ActiveSolutionProjects as Array;
        if (projects == null || projects.Length == 0)
        {
            projects = dte.Solution.SolutionBuild.StartupProjects as Array;
            if (projects == null || projects.Length == 0)
            {
                Projects pro = dte.Solution.Projects;
                if (pro == null || pro.Count == 0)
                    return null;
                return pro.Item(0);
            }
        }
        return projects.GetValue(0) as Project;
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top