コード例 #1
0
        /// <summary>
        /// Move to the next/prior spelling issue within the current document
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void SpellCheckNextPriorIssueExecuteHandler(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!(sender is OleMenuCommand command))
            {
                return;
            }

            if (!(this.GetService(typeof(SVsShellMonitorSelection)) is IVsMonitorSelection ms))
            {
                return;
            }

            int result = ms.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out object value);

            if (result == VSConstants.S_OK && value is IVsWindowFrame frame &&
                frame.GetProperty((int)__VSFPROPID.VSFPROPID_FrameMode, out value) == VSConstants.S_OK &&
                ((VSFRAMEMODE)value == VSFRAMEMODE.VSFM_MdiChild || (VSFRAMEMODE)value == VSFRAMEMODE.VSFM_Float))
            {
                var textView = VsShellUtilities.GetTextView(frame);

                if (textView != null)
                {
                    if (this.GetService(typeof(SComponentModel)) is IComponentModel componentModel)
                    {
                        var editorAdapterFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

                        if (editorAdapterFactoryService != null)
                        {
                            try
                            {
                                var wpfTextView = editorAdapterFactoryService.GetWpfTextView(textView);

                                if (wpfTextView.Properties.TryGetProperty(typeof(SpellingTagger), out SpellingTagger tagger) &&
                                    tagger.CurrentMisspellings.Any())
                                {
                                    var caretPoint = wpfTextView.Caret.Position.BufferPosition;
                                    var allIssues  = tagger.CurrentMisspellings.OrderBy(
                                        i => i.Span.GetSpan(i.Span.TextBuffer.CurrentSnapshot).Start.Position).ToList();
                                    var issue = allIssues.FirstOrDefault(i => i.Span.GetSpan(
                                                                             i.Span.TextBuffer.CurrentSnapshot).Contains(caretPoint));
                                    int offset = (command.CommandID.ID == PkgCmdIDList.SpellCheckNextIssue) ? 1 : -1;

                                    if (issue == null)
                                    {
                                        issue = allIssues.FirstOrDefault(i => i.Span.GetSpan(
                                                                             i.Span.TextBuffer.CurrentSnapshot).Start.Position > caretPoint.Position);

                                        if (issue == null)
                                        {
                                            issue  = tagger.CurrentMisspellings.Last();
                                            offset = (command.CommandID.ID == PkgCmdIDList.SpellCheckNextIssue) ? 1 : 0;
                                        }
                                        else
                                        {
                                            offset = (command.CommandID.ID == PkgCmdIDList.SpellCheckNextIssue) ? 0 : -1;
                                        }
                                    }

                                    if (issue != null)
                                    {
                                        int idx = allIssues.IndexOf(issue) + offset;

                                        if (idx < 0)
                                        {
                                            idx = allIssues.Count - 1;
                                        }
                                        else
                                        if (idx >= allIssues.Count)
                                        {
                                            idx = 0;
                                        }

                                        issue = allIssues[idx];

                                        var span = issue.Span.GetSpan(issue.Span.TextBuffer.CurrentSnapshot);

                                        // If in a collapsed region, expand the region
                                        var outliningManagerService = componentModel.GetService <IOutliningManagerService>();

                                        if (outliningManagerService != null)
                                        {
                                            var outliningManager = outliningManagerService.GetOutliningManager(wpfTextView);

                                            if (outliningManager != null)
                                            {
                                                foreach (var region in outliningManager.GetCollapsedRegions(span, false))
                                                {
                                                    if (region.IsCollapsed)
                                                    {
                                                        outliningManager.Expand(region);
                                                    }
                                                }
                                            }
                                        }

                                        wpfTextView.Caret.MoveTo(span.Start);
                                        wpfTextView.ViewScroller.EnsureSpanVisible(span, EnsureSpanVisibleOptions.AlwaysCenter);
                                        wpfTextView.Selection.Select(span, false);
                                    }
                                }
                            }
                            catch (ArgumentException)
                            {
                                // Not an IWpfTextView so ignore it
                            }
                        }
                    }
                }
            }
        }
コード例 #2
0
ファイル: ProjectConfig.cs プロジェクト: yangfan79/MPFProj10
        /// <summary>
        /// Called by the vs shell to start debugging (managed or unmanaged).
        /// Override this method to support other debug engines.
        /// </summary>
        /// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
        public virtual int DebugLaunch(uint grfLaunch)
        {
            CciTracing.TraceCall();

            try
            {
                VsDebugTargetInfo info = new VsDebugTargetInfo();
                info.cbSize = (uint)Marshal.SizeOf(info);
                info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

                // On first call, reset the cache, following calls will use the cached values
                string property = GetConfigurationProperty("StartProgram", _PersistStorageType.PST_USER_FILE, true);
                if (string.IsNullOrEmpty(property))
                {
                    info.bstrExe = this._project.GetOutputAssembly(this.ConfigName, this.Platform);
                }
                else
                {
                    info.bstrExe = property;
                }

                property = GetConfigurationProperty("WorkingDirectory", _PersistStorageType.PST_USER_FILE, false);
                if (string.IsNullOrEmpty(property))
                {
                    info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
                }
                else
                {
                    info.bstrCurDir = property;
                }

                property = GetConfigurationProperty("CmdArgs", _PersistStorageType.PST_USER_FILE, false);
                if (!string.IsNullOrEmpty(property))
                {
                    info.bstrArg = property;
                }

                property = GetConfigurationProperty("RemoteDebugMachine", _PersistStorageType.PST_USER_FILE, false);
                if (property != null && property.Length > 0)
                {
                    info.bstrRemoteMachine = property;
                }

                info.fSendStdoutToOutputWindow = 0;

                property = GetConfigurationProperty("EnableUnmanagedDebugging", _PersistStorageType.PST_USER_FILE, false);
                if (property != null && string.Equals(property, "true", StringComparison.OrdinalIgnoreCase))
                {
                    //Set the unmanged debugger
                    info.clsidCustom = VSConstants.DebugEnginesGuids.NativeOnly_guid;
                }
                else
                {
                    //Set the managed debugger
                    info.clsidCustom = VSConstants.DebugEnginesGuids.ManagedOnly_guid;
                }

                info.grfLaunch = grfLaunch;
                VsShellUtilities.LaunchDebugger(this._project.Site, info);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);

                return(Marshal.GetHRForException(e));
            }

            return(VSConstants.S_OK);
        }
コード例 #3
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            // 二次确认弹窗
            var confirm = VsShellUtilities.ShowMessageBox(
                this.package,
                "所有包含DbTable特性的类都将根据数据库结构自动生成代码" + Environment.NewLine + "请确保现有代码已全部提交,避免生成失败带来损失。",
                "生成DbModel",
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            if (confirm != 1)
            {
                return;
            }
            // 获得dte
            var dteT = Instance.ServiceProvider.GetServiceAsync(typeof(DTE));
            var dte  = (DTE2)dteT.Result;

            // 获得解决方案资源管理器的选中项目
            var selectedItems = dte.ToolWindows.SolutionExplorer.SelectedItems as UIHierarchyItem[];

            if (selectedItems == null || selectedItems.Length == 0)
            {
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    "未找到选中项目",
                    "生成失败",
                    OLEMSGICON.OLEMSGICON_INFO,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                return;
            }
            string projectName = selectedItems[0].Name;

            // 获得项目路径
            string projPath = "";

            {
                var sln   = File.ReadAllText(dte.Solution.FullName).ToUpper().Replace(" ", "").Replace("\r", "").Replace("\n", "");
                var projs = Regex.Matches(sln, @"PROJECT[\s\S,\n]*?ENDPROJECT");
                foreach (var proj in projs)
                {
                    var projName = Regex.Match(proj.ToString(), @"=[\s\S]*?\" + "\"" + @"[\s\S]*?" + "\"");
                    if (projName == null)
                    {
                        continue;
                    }
                    string projNameStr = projName.ToString().Replace("=", "").Replace("\"", "");
                    var    attrs       = Regex.Matches(proj.ToString(), "\"" + @"[\s\S]*?" + "\"");
                    foreach (var attr in attrs)
                    {
                        if (attr.ToString().Contains(".CSPROJ"))
                        {
                            string path = attr.ToString();
                            if (projNameStr == projectName.ToUpper())
                            {
                                FileInfo slnFile = new FileInfo(dte.Solution.FullName);
                                projPath = Path.Combine(slnFile.Directory.FullName, path.ToString().Replace("\"", ""));
                                break;
                            }
                        }
                    }
                }
                if (string.IsNullOrWhiteSpace(projPath))
                {
                    VsShellUtilities.ShowMessageBox(
                        this.package,
                        "未找到项目路径",
                        "生成失败",
                        OLEMSGICON.OLEMSGICON_INFO,
                        OLEMSGBUTTON.OLEMSGBUTTON_OK,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    return;
                }
            }

            // 调用进程生成DbModel
            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            FileInfo cur = new FileInfo(this.GetType().Assembly.Location);

            myProcess.StartInfo.FileName               = Path.Combine(cur.Directory.FullName, "GenerateCode.exe");
            myProcess.StartInfo.UseShellExecute        = false;
            myProcess.StartInfo.RedirectStandardInput  = true;
            myProcess.StartInfo.RedirectStandardOutput = true;
            myProcess.StartInfo.RedirectStandardError  = true;
            myProcess.StartInfo.CreateNoWindow         = true;
            myProcess.StartInfo.Arguments              = projPath;
            myProcess.Start();
            var str = myProcess.StandardOutput.ReadToEnd();

            myProcess.WaitForExit();

            VsShellUtilities.ShowMessageBox(
                this.package,
                str,
                "代码生成",
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            return;
        }
コード例 #4
0
        private static bool GetTextViewFromFrame(IVsWindowFrame frame, out IVsTextView textView)
        {
            textView = VsShellUtilities.GetTextView(frame);

            return(textView != null);
        }
コード例 #5
0
 public static void StartBrowser(string uri)
 => VsShellUtilities.OpenSystemBrowser(uri);
コード例 #6
0
        /// <summary>
        /// Starts the debugger with the provided info.
        /// </summary>
        /// <exception cref="FileNotFoundException">
        /// The provided executable was not found.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        /// The provided working directory was not found.
        /// </exception>
        public void Launch()
        {
            Validate();

            VsShellUtilities.LaunchDebugger(_provider, Info);
        }
コード例 #7
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            //mCommandsController.Running = true;
            var task = System.Threading.Tasks.Task.Run(() =>
            {
                GeneralOptions generalOptions = (GeneralOptions)mPackage.GetDialogPage(typeof(GeneralOptions));

                ScriptBuiler scriptBuilder = new ScriptBuiler();
                scriptBuilder.ConstructParameters(generalOptions, null, mVsEdition, mVsVersion);

                ItemsCollector mItemsCollector = new ItemsCollector(mPackage);
                mItemsCollector.CollectSelectedFiles(mDte);

                mOutputManager = new OutputManager(mDte);
                PowerShellWrapper powerShell = new PowerShellWrapper();
                powerShell.DataHandler      += mOutputManager.OutputDataReceived;
                powerShell.DataErrorHandler += mOutputManager.OutputDataErrorReceived;

                try
                {
                    mDte.Documents.SaveAll();
                    if (kVs15Version == mVsVersion)
                    {
                        Vs15SolutionLoader solutionLoader = new Vs15SolutionLoader(mPackage);
                        solutionLoader.EnsureSolutionProjectsAreLoaded();
                    }

                    mOutputManager.Clear();
                    mOutputManager.Show();
                    mOutputManager.AddMessage($"\n{OutputWindowConstants.kStart} {OutputWindowConstants.kComplileCommand}\n");
                    foreach (var item in mItemsCollector.GetItems)
                    {
                        string script = scriptBuilder.GetScript(item.Item1, item.Item1.GetName());
                        powerShell.Invoke(script);
                        if (mOutputManager.MissingLlvm)
                        {
                            mOutputManager.AddMessage(ErrorParserConstants.kMissingLlvmMessage);
                            break;
                        }
                    }
                    if (!mOutputManager.EmptyBuffer)
                    {
                        mOutputManager.AddMessage(String.Join("\n", mOutputManager.Buffer));
                    }
                    if (!mOutputManager.MissingLlvm)
                    {
                        mOutputManager.Show();
                        mOutputManager.AddMessage($"\n{OutputWindowConstants.kDone} {OutputWindowConstants.kComplileCommand}\n");
                    }
                    if (mOutputManager.HasErrors)
                    {
                        mErrorsManager.AddErrors(mOutputManager.Errors);
                    }
                }
                catch (Exception exception)
                {
                    VsShellUtilities.ShowMessageBox(mPackage, exception.Message, "Error",
                                                    OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            });//.ContinueWith(tsk => mCommandsController.AfterExecute());
        }
コード例 #8
0
        /// <summary>
        /// Handles "apply" messages from the Visual Studio environment.
        /// </summary>
        /// <devdoc>
        /// This method is called when VS wants to save the user's
        /// changes (for example, when the user clicks OK in the dialog).
        /// </devdoc>
        protected override void OnApply(PageApplyEventArgs e)
        {
            IWhereAmISettings storedValues = settings;

            IWhereAmISettings currentValues = new WhereAmISettings()
            {
                FilenameColor = FilenameColor,
                FoldersColor  = FoldersColor,
                ProjectColor  = ProjectColor,

                FilenameSize = FilenameSize,
                FoldersSize  = FoldersSize,
                ProjectSize  = ProjectSize,

                ViewFilename = ViewFilename,
                ViewFolders  = ViewFolders,
                ViewProject  = ViewProject,

                Position = Position,
                Opacity  = Opacity
            };

            int result = (int)VSConstants.MessageBoxResult.IDOK;

            if (!storedValues.Equals(currentValues))
            {
                result = VsShellUtilities.ShowMessageBox(Site, Resources.MessageOnApplyEntered, Resources.Confirm, OLEMSGICON.OLEMSGICON_QUERY, OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }

            if (result == (int)VSConstants.MessageBoxResult.IDCANCEL)
            {
                e.ApplyBehavior = ApplyKind.Cancel;
            }
            else if (e.ApplyBehavior == ApplyKind.Apply)
            {
                settings.FilenameColor = currentValues.FilenameColor;
                settings.FoldersColor  = currentValues.FoldersColor;
                settings.ProjectColor  = currentValues.ProjectColor;

                settings.FilenameSize = currentValues.FilenameSize;
                settings.FoldersSize  = currentValues.FoldersSize;
                settings.ProjectSize  = currentValues.ProjectSize;

                settings.ViewFilename = currentValues.ViewFilename;
                settings.ViewFolders  = currentValues.ViewFolders;
                settings.ViewProject  = currentValues.ViewProject;

                settings.Position = currentValues.Position;
                settings.Opacity  = currentValues.Opacity;

                if (WhereAmISettings.DarkThemeDefaults().Equals(currentValues))
                {
                    settings.Theme = Theme.Dark;
                }
                else if (WhereAmISettings.LightThemeDefaults().Equals(currentValues))
                {
                    settings.Theme = Theme.Light;
                }
                else
                {
                    settings.Theme = Theme.Custom;
                }

                settings.Store();

                base.OnApply(e);
            }
        }
コード例 #9
0
        internal void OnBeforeQueryStatus(object sender, EventArgs e)
        {
            OleMenuCommand command = sender as OleMenuCommand;

            if (command != null)
            {
                //System.Diagnostics.Trace.WriteLine("OnBeforeQueryStatus: " + command.ToString());
                command.Enabled = (_commandRunner.IsBusy != 1 && _applicationObject.Solution.IsOpen && !VsShellUtilities.IsSolutionBuilding(_pkg));
            }
        }
コード例 #10
0
ファイル: OpenInXExplorer.cs プロジェクト: windygu/AnkhSVN
        public override void OnExecute(CommandEventArgs e)
        {
            SvnItem node = EnumTools.GetFirst(e.Selection.GetSelectedSvnItems(false));

            IAnkhCommandService cmd = e.GetService <IAnkhCommandService>();

            switch (e.Command)
            {
            case AnkhCommand.ItemSelectInRepositoryExplorer:
                if (node == null || node.Uri == null)
                {
                    return;
                }

                if (cmd != null)
                {
                    cmd.DirectlyExecCommand(AnkhCommand.RepositoryBrowse, node.FullPath);
                }
                break;

            case AnkhCommand.ItemSelectInWorkingCopyExplorer:
                if (node == null || !node.Exists)
                {
                    return;
                }

                if (cmd != null)
                {
                    cmd.DirectlyExecCommand(AnkhCommand.WorkingCopyBrowse, node.FullPath);
                }
                break;

            case AnkhCommand.ItemSelectInFileExplorer:
                if (node == null || !node.Exists)
                {
                    return;
                }

                SelectInFileExplorer(node.FullPath);
                break;

            case AnkhCommand.ItemSelectInSolutionExplorer:
                if (node == null)
                {
                    return;
                }

                IVsUIHierarchyWindow hierWindow = VsShellUtilities.GetUIHierarchyWindow(e.Context, new Guid(ToolWindowGuids80.SolutionExplorer));

                IVsProject project = VsShellUtilities.GetProject(e.Context, node.FullPath) as IVsProject;

                if (hierWindow != null)
                {
                    int  found;
                    uint id;
                    VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                    if (project != null && VSErr.Succeeded(project.IsDocumentInProject(node.FullPath, out found, prio, out id)) && found != 0)
                    {
                        hierWindow.ExpandItem(project as IVsUIHierarchy, id, EXPANDFLAGS.EXPF_SelectItem);
                    }
                    else if (string.Equals(node.FullPath, e.Selection.SolutionFilename, StringComparison.OrdinalIgnoreCase))
                    {
                        hierWindow.ExpandItem(e.GetService <IVsUIHierarchy>(typeof(SVsSolution)), VSItemId.Root, EXPANDFLAGS.EXPF_SelectItem);
                    }

                    // Now try to activate the solution explorer
                    IVsWindowFrame solutionExplorer;
                    Guid           solutionExplorerGuid = new Guid(ToolWindowGuids80.SolutionExplorer);
                    IVsUIShell     shell = e.GetService <IVsUIShell>(typeof(SVsUIShell));

                    if (shell != null)
                    {
                        shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorerGuid, out solutionExplorer);

                        if (solutionExplorer != null)
                        {
                            solutionExplorer.Show();
                        }
                    }
                }
                break;
            }
        }
コード例 #11
0
        static void getVSData(double x, double y)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            //Var to print
            String lineHeight = "", fontHeight = "", lineBaseX = "", lineBaseY = "";
            int    line = -1, col = -1;
            String fileName = "", type = "", path = "";

            foreach (EnvDTE.Window window in dte.Windows)
            {
                if (!window.Visible)
                {
                    continue;
                }

                // only look at text editor windows
                if (window.Type == vsWindowType.vsWindowTypeDocument || window.Type == vsWindowType.vsWindowTypeCodeWindow)
                {
                    var             openWindowPath = Path.Combine(window.Document.Path, window.Document.Name);
                    ServiceProvider sp             = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte);
                    IVsUIHierarchy  uiHierarchy;
                    uint            itemID;
                    IVsWindowFrame  windowFrame;
                    if (VsShellUtilities.IsDocumentOpen(sp, openWindowPath, Guid.Empty, out uiHierarchy, out itemID, out windowFrame))
                    {
                        IVsTextView textView = VsShellUtilities.GetTextView(windowFrame);
                        object      holder;
                        Guid        guidViewHost = Microsoft.VisualStudio.Editor.DefGuidList.guidIWpfTextViewHost;
                        IVsUserData userData     = textView as IVsUserData;
                        userData.GetData(ref guidViewHost, out holder);
                        IWpfTextViewHost viewHost    = (IWpfTextViewHost)holder;
                        IWpfTextView     wpfTextView = viewHost.TextView;
                        Point            localPoint  = new Point(-1, -1);
                        try {
                            localPoint = wpfTextView.VisualElement.PointFromScreen(new Point(x, y));
                        }
                        catch {  }

                        bufferPos = ConvertToPosition(wpfTextView, localPoint);
                        if (bufferPos != null)
                        {
                            fileName = window.Document.Name;
                            type     = fileName.Split('.')[1];
                            path     = openWindowPath;
                            line     = bufferPos.Value.GetContainingLine().LineNumber + 1;
                            col      = bufferPos.Value.Position - bufferPos.Value.GetContainingLine().Start.Position + 1;

                            var textLine = wpfTextView.TextViewLines.GetTextViewLineContainingYCoordinate(localPoint.Y + wpfTextView.ViewportTop);
                            lineBaseY  = (textLine.Bottom + wpfTextView.ViewportTop).ToString(); //still needs refining to
                            lineBaseX  = (textLine.Left + wpfTextView.ViewportLeft).ToString();  //ensure correct values
                            lineHeight = textLine.Height.ToString();
                            fontHeight = textLine.TextHeight.ToString();
                        }
                    }
                }
            }

            writer.WriteAttributeString("gaze_target", fileName);
            writer.WriteAttributeString("gaze_target_type", type);

            writer.WriteAttributeString("source_file_path", path);
            writer.WriteAttributeString("source_file_line", line.ToString());
            writer.WriteAttributeString("source_file_col", col.ToString());

            writer.WriteAttributeString("editor_line_height", lineHeight);
            writer.WriteAttributeString("editor_font_height", fontHeight);
            writer.WriteAttributeString("editor_line_base_x", lineBaseX);
            writer.WriteAttributeString("editor_line_base_y", lineBaseY);
        }
コード例 #12
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Execute(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            //ThreadHelper.ThrowIfNotOnUIThread();
            var generalPane = GetVsOutputWindow();

            var selectedProject = GetFormsProjects().FirstOrDefault();

            if (selectedProject == null)
            {
                generalPane.OutputString($"Solution doesn't contain a valid ReactorUI hot reload project{Environment.NewLine}");
                generalPane.OutputString($"1) Ensure it references XamarinReactorUI.HotReload package and call WithHotReload() on RxApplication{Environment.NewLine}");
                generalPane.OutputString($"2) Ensure that Visual Studio has finished loading the solution{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            string projectPath = selectedProject.FullName;

            var outputFilePath = Path.Combine(Path.GetDirectoryName(projectPath),
                                              selectedProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(),
                                              selectedProject.Properties.Item("OutputFileName").Value.ToString());

            if (Path.GetExtension(outputFilePath) != ".dll")
            {
                return;
            }

            var now = DateTime.Now;

            generalPane.Activate(); // Brings this pane into view
            generalPane.OutputString($"Building {outputFilePath}...{Environment.NewLine}");
            generalPane.Activate(); // Brings this pane into view

            //_dte.Solution.SolutionBuild.BuildProject(selectedProject.ConfigurationManager.ActiveConfiguration.ConfigurationName, selectedProject.UniqueName, true);

            _dte.Documents.SaveAll();

            if (!RunMsBuild(selectedProject, generalPane))
            {
                // Show a message box to inform user that build was completed with errors
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    "Build FAILED with errors: please review them in the output window and try again",
                    "ReactorUI Hot Reload",
                    OLEMSGICON.OLEMSGICON_WARNING,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                generalPane.OutputString($"Unable to build Xamarin Forms project, it may contains errors{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            if (!ExecutePortForwardCommmand(generalPane))
            {
                generalPane.OutputString($"Unable to setup connection with the device or emulator using adb: plese ensure it's correctly installed (please note that only Android platform is supported so for under Windows){Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            if (await SendAssemblyToEmulatorAsync(outputFilePath, generalPane, _dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode))
            {
                generalPane.OutputString($"Hot reload completed in {(DateTime.Now - now).TotalMilliseconds}ms{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
            }


            // Show a message box to prove we were here
            //VsShellUtilities.ShowMessageBox(
            //    package,
            //    message,
            //    outputFilePath,
            //    OLEMSGICON.OLEMSGICON_INFO,
            //    OLEMSGBUTTON.OLEMSGBUTTON_OK,
            //    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            //string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            //string title = "ReloadCommand";

            //IVsHierarchy hierarchy = null;
            //uint itemid = VSConstants.VSITEMID_NIL;

            //if (!IsSingleProjectItemSelection(out hierarchy, out itemid)) return;

            //var currentProject = ((IVsProject)hierarchy);

            //// Show a message box to prove we were here
            //VsShellUtilities.ShowMessageBox(
            //    this.package,
            //    message,
            //    title,
            //    OLEMSGICON.OLEMSGICON_INFO,
            //    OLEMSGBUTTON.OLEMSGBUTTON_OK,
            //    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }
コード例 #13
0
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (VsShellUtilities.IsInAutomationFunction(_provider.ServiceProvider))
            {
                return(_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
            }

            uint commandID = nCmdID;
            char typedChar = char.MinValue;

            if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
            {
                typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
            }

            if (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)
            {
                if (session != null && !session.IsDismissed)
                {
                    if (session.SelectedCompletionSet.SelectionStatus.IsSelected)
                    {
                        session.Commit();
                        MoveCaret();
                        return(VSConstants.S_OK);
                    }
                    else
                    {
                        session.Dismiss();
                    }
                }
            }

            int retVal = _nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

            bool handled = false;

            if ((!typedChar.Equals(char.MinValue) && char.IsLetterOrDigit(typedChar)) || typedChar.Equals('<'))
            {
                if (session == null || session.IsDismissed)
                {
                    this.TriggerCompletion();
                    session.Filter();
                }
                else
                {
                    session.Filter();
                }
                handled = true;
            }
            else if (commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE ||
                     commandID == (uint)VSConstants.VSStd2KCmdID.DELETE)
            {
                if (session != null && !session.IsDismissed)
                {
                    session.Filter();
                }
                handled = true;
            }

            if (handled)
            {
                return(VSConstants.S_OK);
            }

            return(retVal);
        }
コード例 #14
0
        /// <summary>
        /// Add a spell checker configuration file based on the currently selected solution/project item
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void AddSpellCheckerConfigExecuteHandler(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                if (DetermineContainingProjectAndSettingsFile(out Project containingProject, out string settingsFilename))
                {
                    if (this.GetService(typeof(SDTE)) is DTE2 dte2)
                    {
                        // Don't add it again if it's already there, just open it
                        var existingItem = dte2.Solution.FindProjectItemForFile(settingsFilename);

                        if (existingItem == null)
                        {
                            var newConfigFile = new SpellingConfigurationFile(settingsFilename, null);
                            newConfigFile.Save();

                            if (containingProject != null)
                            {
                                // If file settings, add them as a dependency if possible
                                if (!settingsFilename.StartsWith(containingProject.FullName, StringComparison.OrdinalIgnoreCase))
                                {
                                    existingItem = dte2.Solution.FindProjectItemForFile(
                                        Path.GetFileNameWithoutExtension(settingsFilename));

                                    if (existingItem != null && existingItem.ProjectItems != null)
                                    {
                                        existingItem = existingItem.ProjectItems.AddFromFile(settingsFilename);
                                    }
                                    else
                                    {
                                        existingItem = containingProject.ProjectItems.AddFromFile(settingsFilename);
                                    }
                                }
                                else
                                {
                                    existingItem = containingProject.ProjectItems.AddFromFile(settingsFilename);
                                }
                            }
                            else
                            {
#pragma warning disable VSTHRD010
                                // Add solution settings file.  Don't enumerate projects to find an existing copy
                                // of the folder.  It's not a project so it won't be found that way.  Just search
                                // the project collection.  It'll be at the root level if it exists.
                                var siProject = dte2.Solution.Projects.Cast <Project>().FirstOrDefault(
                                    p => p.Name == "Solution Items");
#pragma warning restore VSTHRD010

                                if (siProject == null)
                                {
                                    siProject = ((Solution2)dte2.Solution).AddSolutionFolder("Solution Items");
                                }

                                existingItem = siProject.ProjectItems.AddFromFile(settingsFilename);
                            }
                        }

                        if (existingItem != null)
                        {
                            try
                            {
                                var window = existingItem.Open();

                                if (window != null)
                                {
                                    window.Activate();
                                }
                            }
                            catch (Exception ex)
                            {
                                // Sometimes this isn't implemented for some reason.  The file does get added and
                                // can be opened manually.
                                if (ex.HResult != VSConstants.E_NOTIMPL)
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Ignore on error but report it
                System.Diagnostics.Debug.WriteLine(ex);

                VsShellUtilities.ShowMessageBox(this, $"Unable to add spell checker configuration file: {ex.Message}",
                                                Resources.PackageTitle, OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
        }
コード例 #15
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void RunClangFormat(object sender, EventArgs e)
        {
            try
            {
                if (null == mClangFormatView)
                {
                    FormatAllSelectedDocuments();
                    return;
                }

                var view = Vsix.GetDocumentView(mDocument);
                if (view == null)
                {
                    return;
                }

                System.Diagnostics.Process process;
                var dirPath  = string.Empty;
                var filePath = Vsix.GetDocumentPath(view);
                var text     = view.TextBuffer.CurrentSnapshot.GetText();

                var startPosition = 0;
                var length        = text.Length;

                if (false == view.Selection.StreamSelectionSpan.IsEmpty)
                {
                    // get the necessary elements for format selection
                    FindStartPositionAndLengthOfSelectedText(view, text, out startPosition, out length);
                    dirPath          = Vsix.GetDocumentParent(view);
                    mClangFormatView = GetUserOptions();
                }
                else
                {
                    // format the end of the file for format document
                    text = FormatEndOfFile(view, filePath, out dirPath);
                }

                process = CreateProcess(text, startPosition, length, dirPath, filePath, mClangFormatView);

                try
                {
                    process.Start();
                }
                catch (Exception exception)
                {
                    throw new Exception(
                              $"Cannot execute {process.StartInfo.FileName}.\n{exception.Message}.");
                }

                process.StandardInput.Write(text);
                process.StandardInput.Close();

                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                if (0 != process.ExitCode)
                {
                    throw new Exception(process.StandardError.ReadToEnd());
                }

                ApplyClangFormat(output, view);
            }
            catch (Exception exception)
            {
                VsShellUtilities.ShowMessageBox(Package, exception.Message, "Error while running clang-format",
                                                OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
            finally
            {
                mDocument        = null;
                mClangFormatView = null;
            }
        }
コード例 #16
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                var sql = GetQuery();

                var scriptFactory          = new ScriptFactoryWrapper(ServiceCache.ScriptFactory);
                var sqlScriptEditorControl = scriptFactory.GetCurrentlyActiveFrameDocView(ServiceCache.VSMonitorSelection, false, out _);

                var options  = new QueryExecutionOptions(sqlScriptEditorControl, Package.Settings);
                var metadata = GetMetadataCache();
                var org      = ConnectCDS();

                var converter = new ExecutionPlanBuilder(metadata, new TableSizeCache(org, metadata), options)
                {
                    TDSEndpointAvailable = false,
                    QuotedIdentifiers    = sqlScriptEditorControl.QuotedIdentifiers
                };

                try
                {
                    var queries = converter.Build(sql);

                    foreach (var query in queries)
                    {
                        _ai.TrackEvent("Convert", new Dictionary <string, string> {
                            ["QueryType"] = query.GetType().Name, ["Source"] = "SSMS"
                        });

                        var window = Dte.ItemOperations.NewFile("General\\XML File");

                        var editPoint = ActiveDocument.EndPoint.CreateEditPoint();
                        editPoint.Insert("<!--\r\nCreated from query:\r\n\r\n");
                        editPoint.Insert(query.Sql);

                        var nodes = GetAllNodes(query).ToList();

                        if (nodes.Any(node => !(node is IFetchXmlExecutionPlanNode)))
                        {
                            editPoint.Insert("\r\n‼ WARNING ‼\r\n");
                            editPoint.Insert("This query requires additional processing. This FetchXML gives the required data, but needs additional processing to format it in the same way as returned by the TDS Endpoint or SQL 4 CDS.\r\n\r\n");
                            editPoint.Insert("Learn more at https://markcarrington.dev/sql-4-cds/additional-processing/\r\n\r\n");
                        }

                        editPoint.Insert("\r\n\r\n-->");

                        foreach (var fetchXml in nodes.OfType <IFetchXmlExecutionPlanNode>())
                        {
                            editPoint.Insert("\r\n\r\n");
                            editPoint.Insert(fetchXml.FetchXmlString);
                        }
                    }
                }
                catch (NotSupportedQueryFragmentException ex)
                {
                    VsShellUtilities.LogError("SQL 4 CDS", ex.ToString());
                    VsShellUtilities.ShowMessageBox(Package, "The query could not be converted to FetchXML: " + ex.Message, "Query Not Supported", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
                catch (QueryParseException ex)
                {
                    VsShellUtilities.LogError("SQL 4 CDS", ex.ToString());
                    VsShellUtilities.ShowMessageBox(Package, "The query could not be parsed: " + ex.Message, "Query Parsing Error", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            }
            catch (Exception ex)
            {
                VsShellUtilities.LogError("SQL 4 CDS", ex.ToString());
            }
        }
コード例 #17
0
        /// <summary>
        /// Reloads a nested project node by deleting it and readding it.
        /// </summary>
        /// <param name="node">The node to reload.</param>
        protected virtual void ReloadNestedProjectNode(NestedProjectNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;

            if (solution == null)
            {
                throw new InvalidOperationException();
            }

            NestedProjectNode newNode = null;

            try
            {
                // (VS 2005 UPDATE) When deleting and re-adding the nested project,
                // we do not want SCC to see this as a delete and add operation.
                this.EventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;

                // notify SolutionEvents listeners that we are about to add children
                IVsFireSolutionEvents fireSolutionEvents = solution as IVsFireSolutionEvents;

                if (fireSolutionEvents == null)
                {
                    throw new InvalidOperationException();
                }

                ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnBeforeUnloadProject(node.NestedHierarchy));

                int isDirtyAsInt = 0;
                this.IsDirty(out isDirtyAsInt);

                bool isDirty = (isDirtyAsInt == 0) ? false : true;

                ProjectElement element = node.ItemNode;
                node.CloseNestedProjectNode();

                // Remove from the solution
                this.RemoveChild(node);

                // Now readd it
                try
                {
                    __VSCREATEPROJFLAGS flags = __VSCREATEPROJFLAGS.CPF_NOTINSLNEXPLR | __VSCREATEPROJFLAGS.CPF_SILENT | __VSCREATEPROJFLAGS.CPF_OPENFILE;
                    newNode = this.AddExistingNestedProject(element, flags);
                    newNode.AddVirtualProject();
                }
                catch (Exception e)
                {
                    // We get a System.Exception if anything failed, thus we have no choice but catch it.
                    // Exceptions are digested by VS. Show the error if not in automation.
                    if (!Utilities.IsInAutomationFunction(this.Site))
                    {
                        string          message       = (String.IsNullOrEmpty(e.Message)) ? SR.GetString(SR.NestedProjectFailedToReload, CultureInfo.CurrentUICulture) : e.Message;
                        string          title         = string.Empty;
                        OLEMSGICON      icon          = OLEMSGICON.OLEMSGICON_CRITICAL;
                        OLEMSGBUTTON    buttons       = OLEMSGBUTTON.OLEMSGBUTTON_OK;
                        OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
                        VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
                    }

                    // Do not digest exception. let the caller handle it. If in a later stage this exception is not digested then the above messagebox is not needed.
                    throw;
                }

#if DEBUG
                IVsHierarchy nestedHierarchy;
                ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(newNode.GetMkDocument(), out nestedHierarchy));
                Debug.Assert(nestedHierarchy != null && Utilities.IsSameComObject(nestedHierarchy, newNode.NestedHierarchy), "The nested hierrachy was not reloaded correctly.");
#endif
                this.SetProjectFileDirty(isDirty);

                ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnAfterLoadProject(newNode.NestedHierarchy));
            }
            finally
            {
                // In this scenario the nested project failed to unload or reload the nested project. We will unload the whole project, otherwise the nested project is lost.
                // This is similar to the scenario when one wants to open a project and the nested project cannot be loaded because for example the project file has xml errors.
                // We should note that we rely here that if the unload fails then exceptions are not digested and are shown to the user.
                if (newNode == null || newNode.NestedHierarchy == null)
                {
                    ErrorHandler.ThrowOnFailure(solution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject | (uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, this, 0));
                }
                else
                {
                    this.EventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll;
                }
            }
        }
コード例 #18
0
ファイル: QtHelp.cs プロジェクト: qt-labs/vstools
        public static bool QueryEditorContextHelp(bool defaultTryOnline = false)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try {
                var dte             = VsServiceProvider.GetService <SDTE, DTE>();
                var objTextDocument = dte?.ActiveDocument?.Object() as TextDocument;
                if (objTextDocument == null)
                {
                    return(false);
                }

                var keyword   = string.Empty;
                var selection = objTextDocument.Selection;
                if (selection.IsEmpty)                                 // no selection inside the document
                {
                    var line   = selection.ActivePoint.Line;           // current line
                    var offset = selection.ActivePoint.LineCharOffset; // current char offset

                    selection.CharLeft(true);                          // try the character before the cursor
                    if (!selection.IsEmpty)
                    {
                        keyword = selection.Text;  // something in front of the cursor
                        selection.CharRight(true); // reset to origin
                        if (!IsSuperfluousCharacter(keyword))
                        {
                            // move the selection to the start of the word
                            selection.WordLeft(true);
                            selection.MoveToPoint(selection.TopPoint);
                        }
                    }
                    selection.WordRight(true);                   // select the word
                    keyword = selection.Text;                    // get the selected text
                    selection.MoveToLineAndOffset(line, offset); // reset
                }
                else
                {
                    keyword = selection.Text;
                }

                keyword = keyword.Trim();
                if (keyword.Length <= 1 || IsSuperfluousCharacter(keyword))
                {
                    return(false); // suppress single character, operators etc...
                }
                var qtVersion = "$(DefaultQtVersion)";
                var project   = HelperFunctions.GetSelectedQtProject(dte);
                if (project == null)
                {
                    project = HelperFunctions.GetSelectedProject(dte);
                    if (project != null && HelperFunctions.IsQMakeProject(project))
                    {
                        var qmakeQtDir = HelperFunctions.GetQtDirFromQMakeProject(project);
                        qtVersion = QtVersionManager.The().GetQtVersionFromInstallDir(qmakeQtDir);
                    }
                }
                else
                {
                    qtVersion = QtVersionManager.The().GetProjectQtVersion(project);
                }

                var info    = QtVersionManager.The().GetVersionInfo(qtVersion);
                var docPath = info?.QtInstallDocs;
                if (string.IsNullOrEmpty(docPath) || !Directory.Exists(docPath))
                {
                    return(false);
                }

                var qchFiles = Directory.GetFiles(docPath, "*?.qch");
                if (qchFiles.Length == 0)
                {
                    return(false);
                }

                var offline = QtVsToolsPackage.Instance.Options.HelpPreference == SourcePreference.Offline;

                var linksForKeyword = string.Format("SELECT d.Title, f.Name, e.Name, "
                                                    + "d.Name, a.Anchor FROM IndexTable a, FileNameTable d, FolderTable e, "
                                                    + "NamespaceTable f WHERE a.FileId=d.FileId AND d.FolderId=e.Id AND "
                                                    + "a.NamespaceId=f.Id AND a.Name='{0}'", keyword);

                var links   = new Dictionary <string, string>();
                var builder = new SQLiteConnectionStringBuilder
                {
                    ReadOnly = true
                };
                foreach (var file in qchFiles)
                {
                    builder.DataSource = file;
                    using (var connection = new SQLiteConnection(builder.ToString())) {
                        connection.Open();
                        using (var command = new SQLiteCommand(linksForKeyword, connection)) {
                            var reader = QtVsToolsPackage.Instance.JoinableTaskFactory
                                         .Run(async() => await command.ExecuteReaderAsync());
                            using (reader) {
                                while (reader.Read())
                                {
                                    var title = GetString(reader, 0);
                                    if (string.IsNullOrWhiteSpace(title))
                                    {
                                        title = keyword + ':' + GetString(reader, 3);
                                    }
                                    var path = string.Empty;
                                    if (offline)
                                    {
                                        path = "file:///" + Path.Combine(docPath,
                                                                         GetString(reader, 2), GetString(reader, 3));
                                    }
                                    else
                                    {
                                        path = "https://" + Path.Combine("doc.qt.io",
                                                                         $"qt-{info.qtMajor}", GetString(reader, 3));
                                    }
                                    if (!string.IsNullOrWhiteSpace(GetString(reader, 4)))
                                    {
                                        path += "#" + GetString(reader, 4);
                                    }
                                    links.Add(title, path);
                                }
                            }
                        }
                    }
                }

                var uri = string.Empty;
                switch (links.Values.Count)
                {
                case 0:
                    if (!offline && defaultTryOnline)
                    {
                        uri = new UriBuilder($"https://doc.qt.io/qt-{info.qtMajor}/search-results.html")
                        {
                            Query = "q=" + keyword
                        }.ToString();
                    }
                    else
                    {
                        return(false);
                    }
                    break;

                case 1:
                    uri = links.First().Value;
                    break;

                default:
                    var dialog = new QtHelpLinkChooser
                    {
                        Links         = links,
                        Keyword       = keyword,
                        ShowInTaskbar = false
                    };
                    if (!dialog.ShowModal().GetValueOrDefault())
                    {
                        return(false);
                    }
                    uri = dialog.Link
                          .Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    break;
                }

                if (string.IsNullOrEmpty(uri))   // offline mode without a single search hit
                {
                    VsShellUtilities.ShowMessageBox(QtVsToolsPackage.Instance,
                                                    "Your search - " + keyword + " - did not match any documents.",
                                                    string.Empty, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
                else
                {
                    var helpUri = new Uri(uri.Replace('\\', '/'));
                    if (helpUri.IsFile && !File.Exists(helpUri.LocalPath))
                    {
                        VsShellUtilities.ShowMessageBox(QtVsToolsPackage.Instance,
                                                        "Your search - " + keyword + " - did match a document, but it could "
                                                        + "not be found on disk. To use the online help, select: "
                                                        + "Help | Set Qt Help Preference | Use Online Documentation",
                                                        string.Empty, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    }
                    else
                    {
                        VsShellUtilities.OpenSystemBrowser(HelperFunctions.ChangePathFormat(uri));
                    }
                }
            } catch (Exception e) {
                Messages.Print(
                    e.Message + "\r\n\r\nStacktrace:\r\n" + e.StackTrace);
            }
            return(true);
        }
コード例 #19
0
 public string DocumentGetText( )
 {
     return(VsShellUtilities.GetRunningDocumentContents(this.ProjectMgr.Site, this.Url));
 }
コード例 #20
0
ファイル: SelfCommand4.cs プロジェクト: liuSheng0/SelfVSIX
 public void ShowMsgBox(string msg)
 {
     VsShellUtilities.ShowMessageBox(this.package, msg, "", OLEMSGICON.OLEMSGICON_NOICON, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
 }
コード例 #21
0
        public static void ProcessLogFile(string filePath, Solution solution, string toolFormat = ToolFormat.None)
        {
            SarifLog log = null;

            JsonSerializerSettings settingsV2 = new JsonSerializerSettings()
            {
                ContractResolver = SarifContractResolver.Instance,
            };

            string logText;

            if (toolFormat.MatchesToolFormat(ToolFormat.None))
            {
                logText = File.ReadAllText(filePath);
                string pattern = @"""version""\s*:\s*""1.0.0""";
                Match  match   = Regex.Match(logText, pattern, RegexOptions.Compiled | RegexOptions.Multiline);

                if (match.Success)
                {
                    // They're opening a v1 log, so we need to transform it.
                    // Ask if they'd like to save the v2 log.
                    int result = VsShellUtilities.ShowMessageBox(SarifViewerPackage.ServiceProvider,
                                                                 Resources.TransformV1_DialogMessage,
                                                                 null, // title
                                                                 OLEMSGICON.OLEMSGICON_QUERY,
                                                                 OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL,
                                                                 OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    MessageDialogCommand response = (MessageDialogCommand)Enum.Parse(typeof(MessageDialogCommand), result.ToString());

                    if (response == MessageDialogCommand.Cancel)
                    {
                        return;
                    }

                    JsonSerializerSettings settingsV1 = new JsonSerializerSettings()
                    {
                        ContractResolver = SarifContractResolverVersionOne.Instance,
                    };

                    SarifLogVersionOne v1Log = JsonConvert.DeserializeObject <SarifLogVersionOne>(logText, settingsV1);
                    var transformer          = new SarifVersionOneToCurrentVisitor();
                    transformer.VisitSarifLogVersionOne(v1Log);
                    log = transformer.SarifLog;

                    if (response == MessageDialogCommand.Yes)
                    {
                        // Prompt for a location to save the transformed log.
                        var saveFileDialog = new SaveFileDialog();

                        saveFileDialog.Title            = Resources.SaveTransformedV1Log_DialogTitle;
                        saveFileDialog.Filter           = "SARIF log files (*.sarif)|*.sarif";
                        saveFileDialog.RestoreDirectory = true;

                        filePath = Path.GetFileNameWithoutExtension(filePath) + ".v2.sarif";
                        saveFileDialog.FileName         = Path.GetFileName(filePath);
                        saveFileDialog.InitialDirectory = Path.GetDirectoryName(filePath);

                        if (saveFileDialog.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }

                        filePath = saveFileDialog.FileName;
                        string error = null;

                        try
                        {
                            File.WriteAllText(filePath, JsonConvert.SerializeObject(log, settingsV2));
                        }
                        catch (UnauthorizedAccessException)
                        {
                            error = string.Format(Resources.SaveTransformedV1LogFail_Access_DialogMessage, filePath);
                        }
                        catch (SecurityException)
                        {
                            error = string.Format(Resources.SaveTransformedV1LogFail_Access_DialogMessage, filePath);
                        }
                        catch (Exception ex)
                        {
                            error = string.Format(Resources.SaveTransformedV1LogFail_General_Dialog, ex.Message);
                        }

                        if (error != null)
                        {
                            VsShellUtilities.ShowMessageBox(SarifViewerPackage.ServiceProvider,
                                                            error,
                                                            null, // title
                                                            OLEMSGICON.OLEMSGICON_CRITICAL,
                                                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        }
                    }
                }
            }
            else
            {
                // We have conversion to do
                var converter = new ToolFormatConverter();
                var sb        = new StringBuilder();

                using (var input = new MemoryStream(File.ReadAllBytes(filePath)))
                {
                    var outputTextWriter = new StringWriter(sb);
                    var outputJson       = new JsonTextWriter(outputTextWriter);
                    var output           = new ResultLogJsonWriter(outputJson);

                    input.Seek(0, SeekOrigin.Begin);
                    converter.ConvertToStandardFormat(toolFormat, input, output);

                    // This is serving as a flush mechanism
                    output.Dispose();

                    logText = sb.ToString();
                }
            }

            if (log == null)
            {
                log = JsonConvert.DeserializeObject <SarifLog>(logText, settingsV2);
            }

            ProcessSarifLog(log, filePath, solution);

            SarifTableDataSource.Instance.BringToFront();
        }
コード例 #22
0
 VSConstants.MessageBoxResult ShowInfoMessage(string message)
 {
     return((VSConstants.MessageBoxResult)VsShellUtilities.ShowMessageBox(serviceProvider, message, null,
                                                                          OLEMSGICON.OLEMSGICON_QUERY, OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST));
 }
コード例 #23
0
 public static void StartBrowser(Uri uri)
 => VsShellUtilities.OpenSystemBrowser(uri.AbsoluteUri);
コード例 #24
0
        public bool TryRebaselineAllSarifErrors(int runId, string uriBaseId, string originalFilename)
        {
            if (!SarifViewerPackage.IsUnitTesting)
            {
#pragma warning disable VSTHRD108 // Assert thread affinity unconditionally
                ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning restore VSTHRD108 // Assert thread affinity unconditionally
            }

            if (CurrentSarifResult == null)
            {
                return(false);
            }

            RunDataCache dataCache           = RunDataCaches[runId];
            string       rebaselinedFileName = null;

            if (dataCache.FileDetails.ContainsKey(originalFilename))
            {
                // File contents embedded in SARIF.
                rebaselinedFileName = CreateFileFromContents(dataCache.FileDetails, originalFilename);
            }
            else
            {
                if (uriBaseId != null &&
                    dataCache.OriginalUriBasePaths.TryGetValue(uriBaseId, out Uri baseUri) &&
                    Uri.TryCreate(baseUri, originalFilename, out Uri uri) &&
                    uri.IsHttpScheme())
                {
                    bool allow = _allowedDownloadHosts.Contains(uri.Host);

                    // File needs to be downloaded, prompt for confirmation if host is not already allowed
                    if (!allow)
                    {
                        MessageDialogCommand result = MessageDialog.Show(Resources.ConfirmDownloadDialog_Title,
                                                                         string.Format(Resources.ConfirmDownloadDialog_Message, uri),
                                                                         MessageDialogCommandSet.YesNo,
                                                                         string.Format(Resources.ConfirmDownloadDialog_CheckboxLabel, uri.Host),
                                                                         out bool alwaysAllow);

                        if (result != MessageDialogCommand.No)
                        {
                            allow = true;

                            if (alwaysAllow)
                            {
                                AddAllowedDownloadHost(uri.Host);
                            }
                        }
                    }

                    if (allow)
                    {
                        try
                        {
                            rebaselinedFileName = DownloadFile(uri.ToString());
                        }
                        catch (WebException wex)
                        {
                            VsShellUtilities.ShowMessageBox(SarifViewerPackage.ServiceProvider,
                                                            Resources.DownloadFail_DialogMessage + Environment.NewLine + wex.Message,
                                                            null, // title
                                                            OLEMSGICON.OLEMSGICON_CRITICAL,
                                                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                            return(false);
                        }
                    }
                }
                else
                {
                    // User needs to locate file.
                    rebaselinedFileName = GetRebaselinedFileName(uriBaseId, originalFilename, dataCache);
                }

                if (String.IsNullOrEmpty(rebaselinedFileName) || originalFilename.Equals(rebaselinedFileName, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            // Update all the paths in this run
            RemapFileNames(dataCache.SarifErrors, originalFilename, rebaselinedFileName);
            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Called by the vs shell to start debugging (managed or unmanaged).
        /// Override this method to support other debug engines.
        /// </summary>
        /// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
        public virtual int DebugLaunch(uint grfLaunch)
        {
            CCITracing.TraceCall();

            try
            {
                VsDebugTargetInfo info = new VsDebugTargetInfo();
                info.cbSize = (uint)Marshal.SizeOf(info);
                info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

                // On first call, reset the cache, following calls will use the cached values
                string property = GetConfigurationProperty("StartProgram", true);
                if (string.IsNullOrEmpty(property))
                {
                    info.bstrExe = this.project.GetOutputAssembly(this.ConfigKey);
                }
                else
                {
                    info.bstrExe = property;
                }

                property = GetConfigurationProperty("WorkingDirectory", false);
                if (string.IsNullOrEmpty(property))
                {
                    info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
                }
                else
                {
                    info.bstrCurDir = property;
                }

                property = GetConfigurationProperty("CmdArgs", false);
                if (!string.IsNullOrEmpty(property))
                {
                    info.bstrArg = property;
                }

                property = GetConfigurationProperty("RemoteDebugMachine", false);
                if (property != null && property.Length > 0)
                {
                    info.bstrRemoteMachine = property;
                }

                info.fSendStdoutToOutputWindow = 0;

                property = GetConfigurationProperty("EnableUnmanagedDebugging", false);
                if (property != null && string.Compare(property, "true", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    //Set the unmanged debugger
                    //TODO change to vsconstant when it is available in VsConstants (guidNativeOnlyEng was the old name, maybe it has got a new name)
                    info.clsidCustom = new Guid("{3B476D35-A401-11D2-AAD4-00C04F990171}");
                }
                else
                {
                    //Set the managed debugger
                    info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
                }
                info.grfLaunch = grfLaunch;
                VsShellUtilities.LaunchDebugger(this.project.Site, info);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);

                return(Marshal.GetHRForException(e));
            }

            return(VSConstants.S_OK);
        }
コード例 #26
0
ファイル: PythonWebProject.cs プロジェクト: xiaomailong/PTVS
        int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (pguidCmdGroup == GuidList.guidWebPackgeCmdId)
            {
                if (nCmdID == 0x101 /*  EnablePublishToWindowsAzureMenuItem*/)
                {
                    var        shell = (IVsShell)((IServiceProvider)this).GetService(typeof(SVsShell));
                    var        webPublishPackageGuid = GuidList.guidWebPackageGuid;
                    IVsPackage package;

                    int res = shell.LoadPackage(ref webPublishPackageGuid, out package);
                    if (!ErrorHandler.Succeeded(res))
                    {
                        return(res);
                    }

                    var cmdTarget = package as IOleCommandTarget;
                    if (cmdTarget != null)
                    {
                        res = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                        if (ErrorHandler.Succeeded(res))
                        {
                            // TODO: Check flag to see if we were notified
                            // about being added as a web role.
                            if (!AddWebRoleSupportFiles())
                            {
                                VsShellUtilities.ShowMessageBox(
                                    this,
                                    Strings.AddWebRoleSupportFiles,
                                    null,
                                    OLEMSGICON.OLEMSGICON_INFO,
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                                    );
                            }
                        }
                        return(res);
                    }
                }
            }
            else if (pguidCmdGroup == PublishCmdGuid)
            {
                if (nCmdID == PublishCmdid)
                {
                    // Approximately duplicated in DjangoProject
                    var opts = _site.GetPythonToolsService().SuppressDialogOptions;
                    if (string.IsNullOrEmpty(opts.PublishToAzure30))
                    {
                        var td = new TaskDialog(_site)
                        {
                            Title             = Strings.ProductTitle,
                            MainInstruction   = Strings.PublishToAzure30,
                            Content           = Strings.PublishToAzure30Message,
                            VerificationText  = Strings.DontShowAgain,
                            SelectedVerified  = false,
                            AllowCancellation = true,
                            EnableHyperlinks  = true
                        };
                        td.Buttons.Add(TaskDialogButton.OK);
                        td.Buttons.Add(TaskDialogButton.Cancel);
                        if (td.ShowModal() == TaskDialogButton.Cancel)
                        {
                            return(VSConstants.S_OK);
                        }

                        if (td.SelectedVerified)
                        {
                            opts.PublishToAzure30 = "true";
                            opts.Save();
                        }
                    }
                }
            }

            return(_menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
        }
コード例 #27
0
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider))
                {
                    return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                // make a copy of this so we can look at it after forwarding some commands
                uint commandID = nCmdID;
                char typedChar = char.MinValue;

                // make sure the input is a char before getting it
                if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                {
                    typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                }

                // Check if it is a commit character, to generate a multiline comment
                bool isCommitChar = nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN ||
                                    nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB;

                bool showCompletion = nCmdID == (uint)VSConstants.VSStd2KCmdID.COMPLETEWORD;

                // Handle only typed characters or in case of an active completion also deletions
                if (typedChar == '\0' && !isCommitChar && !showCompletion)
                {
                    return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                // check if the last character of one of the supported shortcuts is typed
                if (!m_provider.CompletionBroker.IsCompletionActive(m_textView) &&
                    m_dte != null &&
                    (typedChar == m_header_char || isCommitChar || typedChar == '!'))
                {
                    var currentILine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position);
                    int    len             = m_textView.Caret.Position.BufferPosition.Position - currentILine.Start.Position;
                    string currentLine     = m_textView.TextSnapshot.GetText(currentILine.Start.Position, len);
                    string currentLineFull = currentILine.GetText();

                    string typed_shortcut = (currentLine + typedChar).Trim();

                    if (typed_shortcut.Trim().Length >= 3)
                    {
                        // Get the current text properties
                        TextSelection ts         = m_dte.ActiveDocument.Selection as TextSelection;
                        int           oldLine    = ts.ActivePoint.Line;
                        int           oldOffset  = ts.ActivePoint.LineCharOffset;
                        string        lineEnding = GetLineEnding();

                        // First use only single line comment
                        // Single line comments are not supported in the first line, because of the header comment
                        if (typedChar == '*' && typed_shortcut == "/**" && oldLine > 1)
                        {
                            ts.Insert(typedChar + "  ");
                            if (!currentLineFull.Contains("*/"))
                            {
                                ts.Insert("*/");
                            }
                            ts.MoveToLineAndOffset(oldLine, oldOffset + 2);
                            return(VSConstants.S_OK);
                        }

                        // If it is a commit character check if there is a comment to expand
                        if (isCommitChar &&
                            ShouldExpand(ts, currentLineFull, oldLine, oldOffset, out var commentFormat, out var codeElement, out var shortcut))
                        {
                            // Replace all possible comment characters to get the raw brief
                            string currentText = Regex.Replace(currentLineFull.Replace(shortcut, ""), @"\/\*+|\*+\/|\/\/+", "").Trim();

                            // Delete current comment
                            int lenToDelete = Regex.Replace(currentLineFull, @".*\/\*|^[^\/]*\/\/", "").Length;
                            ts.MoveToLineAndOffset(oldLine, oldOffset);
                            ts.EndOfLine();
                            ts.DeleteLeft(lenToDelete);

                            // Create new multiline comment
                            currentLine     = currentLineFull.Substring(0, currentLineFull.Length - lenToDelete);
                            currentLineFull = currentLine;
                            oldOffset       = ts.ActivePoint.LineCharOffset;
                            return(InsertMultilineComment(commentFormat, codeElement, ts, currentLine, lineEnding,
                                                          oldLine, oldOffset, currentText));
                        }

                        // The header can be used without single line format
                        else if (oldLine == 1)
                        {
                            var headerShortcut = m_settings.HeaderFormat.Substring(0, 3);

                            if (typed_shortcut == headerShortcut || typed_shortcut == "/**" || typed_shortcut == "/*!" || typed_shortcut == "///")
                            {
                                // Delete current end comment chars
                                ts.EndOfLine();
                                int lenToDelete = ts.ActivePoint.LineCharOffset - oldOffset;
                                ts.DeleteLeft(lenToDelete);

                                return(InsertMultilineComment(CommentFormat.header, null, ts, currentLine, lineEnding,
                                                              oldLine, oldOffset, ""));
                            }
                        }
                        // '/*!' is a always active shortcut without single line
                        // This is for an eseaier beginning and for the same workflow as older versions
                        else if (typed_shortcut == "/*!")
                        {
                            var _commentFormat = GetCommentFormat(ts, oldLine, oldOffset, out var _codeElement);

                            // Delete current end comment chars
                            ts.EndOfLine();
                            int lenToDelete = ts.ActivePoint.LineCharOffset - oldOffset;
                            ts.DeleteLeft(lenToDelete);

                            return(InsertMultilineComment(_commentFormat, _codeElement, ts, currentLine, lineEnding,
                                                          oldLine, oldOffset, ""));
                        }
                    }
                }

                if (m_session != null && !m_session.IsDismissed)
                {
                    // check for a commit character
                    if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN ||
                        nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)
                    {
                        // check for a selection
                        // if the selection is fully selected, commit the current session
                        if (m_session.SelectedCompletionSet.SelectionStatus.IsSelected)
                        {
                            m_session.Commit();

                            // also, don't add the character to the buffer
                            return(VSConstants.S_OK);
                        }
                        else
                        {
                            // if there is no selection, dismiss the session
                            m_session.Dismiss();
                        }
                    }
                }
                else if (!m_provider.CompletionBroker.IsCompletionActive(m_textView))
                {
                    if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN)
                    {
                        ITextSnapshotLine currentILine = m_textView.TextSnapshot.GetLineFromPosition(
                            m_textView.Caret.Position.BufferPosition.Position);
                        string currentLine = currentILine.GetText();

                        // TODO: check for being inside a comment block
                        // Insert a '*' when creating a new line in a mutline comment
                        if (currentLine.TrimStart().StartsWith("*") && !currentLine.Contains("*/"))
                        {
                            TextSelection ts         = m_dte.ActiveDocument.Selection as TextSelection;
                            string        spaces     = currentLine.Replace(currentLine.TrimStart(), "");
                            string        lineEnding = GetLineEnding();
                            ts.Insert(lineEnding + spaces + "* ");
                            return(VSConstants.S_OK);
                        }

                        // Insert a '///' when creating a new line in a mutline comment
                        if (currentLine.TrimStart().StartsWith("///"))
                        {
                            TextSelection ts         = m_dte.ActiveDocument.Selection as TextSelection;
                            string        spaces     = currentLine.Replace(currentLine.TrimStart(), "");
                            string        lineEnding = GetLineEnding();
                            ts.Insert(lineEnding + spaces + "/// ");
                            return(VSConstants.S_OK);
                        }
                    }
                }

                // pass along the command so the char is added to the buffer
                int retVal = m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                if (typedChar == '\\' || typedChar == '@' || showCompletion)
                {
                    string currentLine = m_textView.TextSnapshot.GetLineFromPosition(
                        m_textView.Caret.Position.BufferPosition.Position).GetText();
                    if (currentLine.TrimStart().StartsWith("*") || currentLine.TrimStart().StartsWith("///"))
                    {
                        if (m_session == null || m_session.IsDismissed) // If there is no active session, bring up completion
                        {
                            if (this.TriggerCompletion())
                            {
                                m_session.SelectedCompletionSet.SelectBestMatch();
                                m_session.SelectedCompletionSet.Recalculate();
                                return(VSConstants.S_OK);
                            }
                        }
                    }
                }
                else if (
                    commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE ||
                    commandID == (uint)VSConstants.VSStd2KCmdID.DELETE ||
                    char.IsLetter(typedChar))
                {
                    if (m_session != null && !m_session.IsDismissed) // the completion session is already active, so just filter
                    {
                        m_session.SelectedCompletionSet.SelectBestMatch();
                        m_session.SelectedCompletionSet.Recalculate();
                        return(VSConstants.S_OK);
                    }
                }

                return(retVal);
            }
コード例 #28
0
 /// <summary>
 /// Handles "close" messages from the Visual Studio environment.
 /// </summary>
 /// <devdoc>
 /// This event is raised when the page is closed.
 /// </devdoc>
 protected override void OnClosed(EventArgs e)
 {
     VsShellUtilities.ShowMessageBox(Site, Resources.MessageOnClosed, null /*title*/, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
 }
コード例 #29
0
        /// <summary>
        /// Renames a file node.
        /// </summary>
        /// <param name="label">The new name.</param>
        /// <returns>An errorcode for failure or S_OK.</returns>
        /// <exception cref="InvalidOperationException" if the file cannot be validated>
        /// <devremark>
        /// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
        /// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
        /// Also the automation methods are also calling SetEditLabel
        /// </devremark>

        public override int SetEditLabel(string label)
        {
            // IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
            //                 expected that we can be called with a label which is the same as the current
            //                 label and this should not be considered a NO-OP.
            if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
            {
                return(VSConstants.E_FAIL);
            }

            // Validate the filename.
            if (string.IsNullOrEmpty(label))
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
            }
            else if (label.Length > NativeMethods.MAX_PATH)
            {
                throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
            }
            else if (Utilities.IsFileNameInvalid(label))
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
            }

            for (var n = this.Parent.FirstChild; n != null; n = n.NextSibling)
            {
                // TODO: Distinguish between real Urls and fake ones (eg. "References")
                if (n != this && StringComparer.OrdinalIgnoreCase.Equals(n.GetItemName(), label))
                {
                    //A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
                    //If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
                    throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label));
                }
            }

            var fileName = Path.GetFileNameWithoutExtension(label);

            // Verify that the file extension is unchanged
            var strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));

            if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) &&
                !StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label)))
            {
                // Prompt to confirm that they really want to change the extension of the file
                var message = SR.GetString(SR.ConfirmExtensionChange, label);
                var shell   = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;

                Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");

                if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
                {
                    // The user cancelled the confirmation for changing the extension.
                    // Return S_OK in order not to show any extra dialog box
                    return(VSConstants.S_OK);
                }
            }

            // Build the relative path by looking at folder names above us as one scenarios
            // where we get called is when a folder above us gets renamed (in which case our path is invalid)
            var parent = this.Parent;

            while (parent != null && (parent is FolderNode))
            {
                strRelPath = Path.Combine(parent.GetItemName(), strRelPath);
                parent     = parent.Parent;
            }

            return(SetEditLabel(label, strRelPath));
        }
コード例 #30
0
        private void ExecuteFormatCommand()
        {
            try
            {
                if (ScriptConstants.kCMakeConfigFile == mDocument.Name.ToLower())
                {
                    return;
                }

                var view = Vsix.GetDocumentView(mDocument);
                if (view == null)
                {
                    return;
                }

                var dirPath  = string.Empty;
                var filePath = Vsix.GetDocumentPath(view);
                var text     = view.TextBuffer.CurrentSnapshot.GetText();

                var startPosition = 0;
                var length        = text.Length;

                if (false == view.Selection.StreamSelectionSpan.IsEmpty)
                {
                    // get the necessary elements for format selection
                    FindStartPositionAndLengthOfSelectedText(view, text, out startPosition, out length);
                    dirPath = Vsix.GetDocumentParent(view);
                }
                else
                {
                    // format the end of the file for format document
                    text = FormatEndOfFile(view, filePath, out dirPath);
                }

                var process = CreateProcess(text, startPosition, length, dirPath, filePath);

                try
                {
                    process.Start();
                }
                catch (Exception exception)
                {
                    throw new Exception(
                              $"Cannot execute {process.StartInfo.FileName}.\n{exception.Message}.");
                }

                process.StandardInput.Write(text);
                process.StandardInput.Close();

                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                if (0 != process.ExitCode)
                {
                    throw new Exception(process.StandardError.ReadToEnd());
                }

                ApplyClangFormat(output, view);
            }
            catch (Exception exception)
            {
                VsShellUtilities.ShowMessageBox(AsyncPackage, exception.Message, "Error while running clang-format",
                                                OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
        }