Программно получая текущую Visual Studio каталог решения IDE от дополнений

У меня есть некоторые инструменты, которые выполняют обновления на решениях.NET, но они должны знать каталог, где решение расположено.

Я добавил эти инструменты как Внешние Инструменты, где они появляются в меню IDE Tools и предоставлении $(SolutionDir) как аргумент. Это хорошо работает.

Однако я хочу, чтобы эти инструменты были легче к доступу в IDE для пользователя через пользовательское меню верхнего уровня (для которого я создал проект пакета интеграции Visual Studio), и через контекстное меню на узлах решения (для которого я создал дополнительный проект Visual Studio). Я ищу способ получить текущий каталог решения через эти контексты.

Я пытался получить информацию решения от VisualStudio.DTE объект:

EnvDTE.DTE dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);

Но, это возвращает каталог решения для добавления ins, не текущее решение.

Я пытался отозваться эхом $(SolutionDir) и чтение его назад:

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "echo $(SolutionDir)");

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();

Но, это возвратило каталог для IDE, не текущее решение.

Я не видел релевантной информации в узле решения CommandBar.

С другой стороны, если был способ программно получить доступ к определенной Visual Studio внешние инструменты и запустить их (использование уже определенных макро-аргументов), который будет работать.

Каково решение?

21
задан Dave Clemmer 22 December 2012 в 18:28
поделиться

2 ответа

EnvDTE.DTE dte = (EnvDTE.DTE) Система. Время выполнения. InteropServices. Маршал. GetActiveObject ("VisualStudio. DTE"); представить solutionDir в виде строки = Система. IO.Path. GetDirectoryName (dte. Решение. FullName);

, Но, это возвращает решение каталог для добавления ins, не текущее решение.

Ваш подход для получения каталога хорош. Что случилось способ, которым вы добираетесь VisualStudio. Объект DTE. Где этот код называют? Я предполагаю, что это находится в вашем дополнении. Вы выполняетесь (отлаживают) ваше дополнение в Visual Studio, которая открывает другой экземпляр Visual Studio, где вы открываете свое решение? Таким образом, у вас есть два экземпляра Visual Studio.

GetActiveObject ("VisualStudio. DTE") получает случайный экземпляр Visual Studio. В вашем случае это - по-видимому Visual Studio с дополнительным проектом, так как вы получаете путь к своему дополнению. Это для объяснения, какова была бы причина вашей проблемы.

корректный способ добраться DTE очень прост. На самом деле ваше дополнение уже имеет ссылку на DTE, в котором это работает (то есть, в котором решение открыто). Это хранится в глобальной переменной _applicationObject в вашем дополнительном классе подключения. Это установлено, когда ваше дополнение запускается в обработчик событий OnConnection . Таким образом, все, в чем вы нуждаетесь, должно звонить:

string solutionDir = System.IO.Path.GetDirectoryName(_applicationObject.Solution.FullName);
18
ответ дан 29 November 2019 в 21:44
поделиться

С petr's push в правильном направлении я настроил контекстное меню Addin для запуска внешнего инструмента с каталогом решения и выводит результаты на панель вывода. В некоторых примерках от добавления:

    ///--------------------------------------------------------------------------------
    /// <summary>This method implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
    ///
    /// <param term='application'>Root object of the host application.</param>
    /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
    /// <param term='addInInst'>Object representing this Add-in.</param>
    /// <seealso class='IDTExtensibility2' />
    ///--------------------------------------------------------------------------------
    public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;

        // Get the solution command bar
        CommandBar solutionCommandBar = ((CommandBars)_applicationObject.CommandBars)["Solution"];

        // Set up the main InCode
        CommandBarPopup solutionPopup = (CommandBarPopup)solutionCommandBar.Controls.Add(MsoControlType.msoControlPopup, System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, true);
        solutionPopup.Caption = "InCode";

        // Add solution updater submenu
        CommandBarControl solutionUpdaterControl = solutionPopup.Controls.Add(MsoControlType.msoControlButton, System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, true);
        solutionUpdaterControl.Caption = "Update Solution";
        updateSolutionMenuItemHandler = (CommandBarEvents)_applicationObject.Events.get_CommandBarEvents(solutionUpdaterControl);
        updateSolutionMenuItemHandler.Click += new _dispCommandBarControlEvents_ClickEventHandler(updateSolution_Click);
    }

    // The event handlers for the solution submenu items
    CommandBarEvents updateSolutionMenuItemHandler;

    ///--------------------------------------------------------------------------------
    /// <summary>This property gets the solution updater output pane.</summary>
    ///--------------------------------------------------------------------------------
    protected OutputWindowPane _solutionUpdaterPane = null;
    protected OutputWindowPane SolutionUpdaterPane
    {
        get
        {
            if (_solutionUpdaterPane == null)
            {
                OutputWindow outputWindow = _applicationObject.ToolWindows.OutputWindow;
                foreach (OutputWindowPane loopPane in outputWindow.OutputWindowPanes)
                {
                    if (loopPane.Name == "Solution Updater")
                    {
                        _solutionUpdaterPane = loopPane;
                        return _solutionUpdaterPane;
                    }
                }
                _solutionUpdaterPane = outputWindow.OutputWindowPanes.Add("Solution Updater");
            }
            return _solutionUpdaterPane;
        }
    }

    ///--------------------------------------------------------------------------------
    /// <summary>This method handles clicking on the Update Solution submenu.</summary>
    ///
    /// <param term='inputCommandBarControl'>The control that is source of the click.</param>
    /// <param term='handled'>Handled flag.</param>
    /// <param term='cancelDefault'>Cancel default flag.</param>
    ///--------------------------------------------------------------------------------
    protected void updateSolution_Click(object inputCommandBarControl, ref bool handled, ref bool cancelDefault)
    {
        try
        {
            // set up and execute solution updater thread
            UpdateSolutionDelegate updateSolutionDelegate = UpdateSolution;
            updateSolutionDelegate.BeginInvoke(UpdateSolutionCompleted, updateSolutionDelegate);
        }
        catch (System.Exception ex)
        {
            // put exception message in output pane
            SolutionUpdaterPane.OutputString(ex.Message);
        }
    }

    protected delegate void UpdateSolutionDelegate();

    ///--------------------------------------------------------------------------------
    /// <summary>This method launches the solution updater to update the solution.</summary>
    ///--------------------------------------------------------------------------------
    protected void UpdateSolution()
    {
        try
        {
            // set up solution updater process
            string solutionDir = System.IO.Path.GetDirectoryName(_applicationObject.Solution.FullName);
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(@"SolutionUpdater.exe", solutionDir);
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;

            // execute the solution updater
            proc.Start();

            // put solution updater output to output pane
            SolutionUpdaterPane.OutputString(proc.StandardOutput.ReadToEnd());
            SolutionUpdaterPane.OutputString("Solution update complete.");
        }
        catch (System.Exception ex)
        {
            // put exception message in output pane
            SolutionUpdaterPane.OutputString(ex.Message);
        }
    }

    ///--------------------------------------------------------------------------------
    /// <summary>This method completing the update solution thread.</summary>
    ///
    /// <param name="ar">IAsyncResult.</param>
    ///--------------------------------------------------------------------------------
    protected void UpdateSolutionCompleted(IAsyncResult ar)
    {
        try
        {
            if (ar == null) throw new ArgumentNullException("ar");

            UpdateSolutionDelegate updateSolutionDelegate = ar.AsyncState as UpdateSolutionDelegate;
            Trace.Assert(updateSolutionDelegate != null, "Invalid object type");

            updateSolutionDelegate.EndInvoke(ar);
        }
        catch (System.Exception ex)
        {
            // put exception message in output pane
            SolutionUpdaterPane.OutputString(ex.Message);
        }
    }
6
ответ дан 29 November 2019 в 21:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: