void ProcessOpenConApp(object sender, EventArgs e) { Debug.WriteLine("Open Console App"); DTE dte = (DTE)GetService(typeof(EnvDTE.DTE)); var prjs = dte.Solution.Projects; if (prjs.Count > 0) { string s = prjs.Item(1).FullName; s = s.Replace(".vcxproj", ".cpp"); dte.ItemOperations.OpenFile(s); dte.ActiveDocument.Activate(); dte.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr; dte.Find.FindWhat = "int main\\(.*\\n\\{.*\\n"; dte.Find.Target = vsFindTarget.vsFindTargetCurrentDocument; dte.Find.MatchCase = false; dte.Find.MatchWholeWord = false; dte.Find.Backwards = false; dte.Find.MatchInHiddenText = false; dte.Find.Action = vsFindAction.vsFindActionFind; if (dte.Find.Execute() == vsFindResult.vsFindResultNotFound) { throw new System.Exception("vsFindResultNotFound"); } dte.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close(); TextSelection ts = (TextSelection)dte.ActiveDocument.Selection; ts.CharRight(); ts.Indent(); dte.ExecuteCommand("File.SaveAll", string.Empty); dte.ExecuteCommand("Build.BuildSolution"); dte.ActiveDocument.Activate(); } }
/// <summary> /// Reloads the given project file in the given solution /// </summary> /// <param name="dte">Current development environment</param> /// <param name="solutionName">Solution name which project belongs</param> /// <param name="projectName">Project file which needs reload</param> private void Reload(Project project) { try { DTE dte = GetService(typeof(DTE)) as DTE; string projectName = ((dte.ActiveSolutionProjects as Array).GetValue(0) as Project).Name; // Select References folder // This is very strange because after reload i guess hierarchy is changing. // Because of that we cant get a reference of selected hierarchy, we have to retrieve it again. string path = GetSelectionPath(dte as EnvDTE80.DTE2, projectName); ((EnvDTE80.DTE2)dte).ToolWindows.SolutionExplorer.GetItem(GetSelectionPath(dte as EnvDTE80.DTE2, projectName)).Select(vsUISelectionType.vsUISelectionTypeSelect); dte.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate(); dte.ExecuteCommand(ProxyMgrConstants.ProjectUnloadCommand); dte.ExecuteCommand(ProxyMgrConstants.ProjectReloadCommand); ((EnvDTE80.DTE2)dte).ToolWindows.SolutionExplorer.GetItem(GetSelectionPath(dte as EnvDTE80.DTE2, projectName)).UIHierarchyItems.GetHierarchyItem("Service References").Select(vsUISelectionType.vsUISelectionTypeSelect); LogWriter.WriteLine("[ OK ] Project reloaded."); } catch (Exception ex) { LogWriter.WriteLine("[ FAIL ] Project reload failed! Exception: " + ex.ToString()); } }
public override void Execute() { SetProjectTypeGuids(project); //add import statement //<Import Project="$(MSBuildToolsPath)\Workflow.Targets" /> DTE service = (DTE)this.GetService(typeof(DTE)); string fileName = project.FullName; Helpers.SelectProject(project); if (service.SuppressUI || MessageBox.Show("The project file of project " + project.Name + " must be updated. Can SPSF save and unload the project?", "Unloading project", MessageBoxButtons.YesNo) == DialogResult.Yes) { service.Documents.CloseAll(vsSaveChanges.vsSaveChangesPrompt); try { Helpers.LogMessage(project.DTE, this, "Updating csproj file"); service.ExecuteCommand("File.SaveAll", string.Empty); service.ExecuteCommand("Project.UnloadProject", string.Empty); MigrateFile(fileName); service.ExecuteCommand("Project.ReloadProject", string.Empty); } catch { Helpers.LogMessage(project.DTE, this, "Could not update project file. Add following statement manually:"); Helpers.LogMessage(project.DTE, this, "<Import Project=\"$(MSBuildToolsPath)\\Workflow.Targets\" />"); } } }
public static Project ReloadProject(this DTE dte, Project project) { var projectUniqueName = project.UniqueName; var projectName = project.Name; SelectProject(dte, project); try { dte.ExecuteCommand("Project.UnloadProject"); Thread.Sleep(200); dte.ExecuteCommand("Project.ReloadProject"); Thread.Sleep(200); return GetProjectByName(dte, projectName); } catch { try { SleepAndCycleMessagePump(dte); dte.ExecuteCommand("Project.UnloadProject"); SleepAndCycleMessagePump(dte); dte.ExecuteCommand("Project.ReloadProject"); SleepAndCycleMessagePump(dte); return GetProjectByUniqueName(dte, projectUniqueName) ?? GetProjectByName(dte, projectName); } catch { return ReloadSolutionAndReturnProject(dte, project); } } }
public void ProjectFinishedGenerating(Project project) { var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); if (componentModel == null) { return; } var installer = componentModel.GetService <IVsPackageInstaller>(); switch (_crmProjectType) { case ProjectType.UnitTest: PostHandleUnitTestProjects(project, installer); break; case ProjectType.Console: case ProjectType.Plugin: case ProjectType.Workflow: PostHandleCrmAssemblyProjects(project, installer); break; case ProjectType.TypeScript: PostHandleTypeScriptProject(project); break; case ProjectType.SolutionPackage: PostHandleSolutionPackagerProject(project); break; } _dte.ExecuteCommand("File.SaveAll"); }
private async Task ResetInteractiveAsync( IVsInteractiveWindow vsInteractiveWindow, ImmutableArray <string> referencePaths, ImmutableArray <string> referenceSearchPaths, ImmutableArray <string> sourceSearchPaths, ImmutableArray <string> namespacesToImport, string projectDirectory, IWaitContext waitContext) { // First, open the repl window. var engine = (InteractiveEvaluator)vsInteractiveWindow.InteractiveWindow.Evaluator; // If the user hits the cancel button on the wait indicator, then we want to stop the // build. waitContext.CancellationToken.Register(() => _dte.ExecuteCommand("Build.Cancel"), useSynchronizationContext: true); // First, start a build await BuildProject().ConfigureAwait(true); // Then reset the REPL waitContext.Message = ServicesVSResources.ResettingInteractive; await vsInteractiveWindow.InteractiveWindow.Operations.ResetAsync(initialize : false).ConfigureAwait(true); // Now send the reference paths we've collected to the repl. await engine.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory).ConfigureAwait(true); await vsInteractiveWindow.InteractiveWindow.SubmitAsync(new[] { referencePaths.Select(_createReference).Join("\r\n"), namespacesToImport.Select(_createImport).Join("\r\n") }).ConfigureAwait(true); }
private void OpenSyncToDocument(string file) { VsShellUtilities.OpenDocument(ServiceProvider, file); _dte.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); _dte.ExecuteCommand("Edit.FormatDocument"); }
private void UpdateCommand(object sender, EventArgs e) { _solutionDir = CommandHelper.GetRepositoryRoot(); if (string.IsNullOrEmpty(_solutionDir)) { return; } Dte.ExecuteCommand("File.SaveAll", string.Empty); CommandHelper.StartProcess(_tortoiseProc, $"/command:update /path:\"{_solutionDir}\" /closeonend:0"); }
protected override Task <bool> BuildProject() { var taskSource = new TaskCompletionSource <bool>(); var updateSolutionEvents = new VsUpdateSolutionEvents(_buildManager, taskSource); // Build the project. When project build is done, set the task source as being done. // (Either succeeded, cancelled, or failed). _dte.ExecuteCommand("Build.BuildSelection"); return(taskSource.Task); }
private void StartRemoteIntegrationService(DTE dte) { // We use DTE over RPC to start the integration service. All other DTE calls should happen in the host process. if (dte.Commands.Item(WellKnownCommandNames.Test_IntegrationTestService_Start).IsAvailable) { dte.ExecuteCommand(WellKnownCommandNames.Test_IntegrationTestService_Start); } if (AsyncCompletionCondition.Instance.ShouldSkip && dte.Commands.Item(WellKnownCommandNames.Test_IntegrationTestService_DisableAsyncCompletion).IsAvailable) { dte.ExecuteCommand(WellKnownCommandNames.Test_IntegrationTestService_DisableAsyncCompletion); } }
private void RunAndAttachCallback() { ProjectInfo pi; if (!IsValidForDebug(out pi)) { return; } _commands.DisableUpload(); // Start a build / upload the program, start the debugger and reset the target, 4 steps to debug :| _output.Activate(VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid); _dte.Events.BuildEvents.OnBuildDone += BuildEventsOnOnBuildDone; _dte.ExecuteCommand("Build.RebuildSolution"); }
void ProcessOpenWPFApp(object sender, EventArgs e) { Debug.WriteLine("Open WPF App"); DTE dte = (DTE)GetService(typeof(EnvDTE.DTE)); var prjs = dte.Solution.Projects; if (prjs.Count > 0) { // get full path of solution (including name of solution file): string solutionFullPathname = dte.Solution.FullName; // extract the directory of the solution: string dir = System.IO.Path.GetDirectoryName(solutionFullPathname); // get the name of the first project string projectName = dte.Solution.Projects.Item(1).Name; // combine the solution dir with the project dir and "program.cs": string programfname = System.IO.Path.Combine(dir, projectName, "mainwindow.xaml"); //System.Windows.Forms.MessageBox.Show("hello: " + programfname); dte.ItemOperations.OpenFile(programfname, EnvDTE.Constants.vsViewKindCode); //var findString = @"static void Main\(string\[\] args\)\r?\n +{"; //dte.ActiveDocument.Activate(); //dte.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr; //dte.Find.FindWhat = findString; //dte.Find.Target = vsFindTarget.vsFindTargetCurrentDocument; //dte.Find.MatchCase = false; //dte.Find.MatchWholeWord = false; //dte.Find.Backwards = false; //dte.Find.MatchInHiddenText = false; //dte.Find.Action = vsFindAction.vsFindActionFind; //if (dte.Find.Execute() == vsFindResult.vsFindResultNotFound) //{ // throw new System.Exception("vsFindResultNotFound"); //} //dte.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close(); //TextSelection ts = (TextSelection)dte.ActiveDocument.Selection; //ts.CharRight(); //ts.Indent(); dte.ExecuteCommand("File.SaveAll", string.Empty); dte.ExecuteCommand("Build.BuildSolution"); dte.ActiveDocument.Activate(); } }
private void DocEventsOnDocumentSaved(Document document) { try { bool IsMiscDoc(Document doc) => (doc.ProjectItem.ContainingProject?.Name ?? "Miscellaneous Files") == "Miscellaneous Files"; if ( _solutionClosing || _building || !(_cleanupCommand?.IsAvailable ?? false) || document.ReadOnly || IsMiscDoc(document) || !AllowedFileExtensions.Contains(Path.GetExtension(document.FullName)?.ToLower()) ) { return; } _activeDocument = _dte.ActiveDocument; document.Activate(); _dte.ExecuteCommand(_cleanupCommand.Name); _activeDocument.Activate(); } catch (Exception e) { ShowDebugError(e.ToString()); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Start the build. This involves activating the output window, saving all files /// and printing a message. /// </summary> /// <param name="msg"></param> /// ------------------------------------------------------------------------------------ private void StartBuild(string msg) { OutputBuild.Clear(); DTE.Windows.Item(Constants.vsWindowKindOutput).Activate(); DTE.ExecuteCommand("File.SaveAll", string.Empty); OutputBuild.Write(msg); }
private string GetTaskNameFromTechnology(string techName) { string configFile = System.IO.Path.GetDirectoryName(_dte.Solution.FullName) + TechnologicatorDefines.ConfigFile; _dte.ExecuteCommand("File.OpenFile", configFile); _dte.Find.MatchWholeWord = false; _dte.Find.Action = vsFindAction.vsFindActionFind; _dte.Find.Target = vsFindTarget.vsFindTargetCurrentDocument; _dte.Find.MatchCase = false; _dte.Find.Backwards = false; _dte.Find.MatchInHiddenText = true; _dte.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral; _dte.Find.FindWhat = "#define " + techName; if (_dte.Find.Execute() != vsFindResult.vsFindResultFound) { return(""); } EnvDTE.TextSelection ts = _dte.ActiveWindow.Selection as EnvDTE.TextSelection; ts.SelectLine(); string defLine = ts.Text; string taskRegexPattern = TechnologicatorDefines.TaskRegex; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(defLine, taskRegexPattern); if (m.Success) { return(m.Value); } else { return(""); } }
private bool InvokeZenCoding(DTE dte) { Span zenSpan = GetSyntaxSpan(out string syntax); if (zenSpan.IsEmpty || _view.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer()) { return(false); } var parser = new Parser(); string result = parser.Parse(syntax, ZenType.HTML); if (!string.IsNullOrEmpty(result)) { Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { using (var undo = _undoManager.TextBufferUndoHistory.CreateTransaction("ZenCoding")) { ITextSelection selection = UpdateTextBuffer(zenSpan, result); Span newSpan = new Span(zenSpan.Start, selection.SelectedSpans[0].Length); dte.ExecuteCommand("Edit.FormatSelection"); SetCaret(newSpan, false); selection.Clear(); undo.Complete(); } }), DispatcherPriority.ApplicationIdle, null); return(true); } return(false); }
/// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void MenuItemCallback_PreviewParameterization(object sender, EventArgs e) { var myCommand = sender as OleMenuCommand; DTE dte = (DTE)GetService(typeof(SDTE)); if (dte.SelectedItems.Count > 0) { var items = dte.SelectedItems as SelectedItems; foreach (SelectedItem item in items) { if (item.Name.StartsWith("SetParameters.", StringComparison.OrdinalIgnoreCase)) { var configFile = GetProjectFile(item.ProjectItem, "web.config"); configFile = GetProjectFile(item.ProjectItem, "app.config") ?? configFile; var result = GenerateParameterizationResult(item, configFile); if (item.DTE.SourceControl.IsItemUnderSCC(configFile)) { item.DTE.SourceControl.CheckOutItem(configFile); } PrettifyXml(configFile); dte.ExecuteCommand("Tools.DiffFiles", string.Format("\"{0}\" \"{1}\"", configFile, result)); } } } }
public void AttachTo(string target) { if (target == OpenDialogTarget) { dte.ExecuteCommand("Tools.AttachtoProcess"); return; } var found = false; foreach (Process process in dte.Debugger.LocalProcesses) { var fileName = Path.GetFileName(process.Name); if (fileName.Equals(target, StringComparison.InvariantCultureIgnoreCase)) { found = true; process.Attach(); } } if (!found) { MessageBox.Show("Failed to find " + target + ".", "Attach To Anything", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private bool InvokeZenCoding() { ThreadHelper.ThrowIfNotOnUIThread(); Span zenSpan = GetSyntaxSpan(out string syntax); if (zenSpan.IsEmpty || _view.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer()) { return(false); } var parser = new Parser(); string result = parser.Parse(syntax, ZenType.HTML); if (!string.IsNullOrEmpty(result)) { using (ITextUndoTransaction undo = _undoManager.TextBufferUndoHistory.CreateTransaction("ZenCoding")) { ITextSelection selection = UpdateTextBuffer(zenSpan, result); var newSpan = new Span(zenSpan.Start, selection.SelectedSpans[0].Length); _dte.ExecuteCommand("Edit.FormatSelection"); SetCaret(newSpan, false); selection.Clear(); undo.Complete(); } return(true); } return(false); }
private async Task ExecFetchAsync() { try { while (!DisposeGit) { DTE dte = await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(false) as DTE; if (dte != null && dte.Solution.IsOpen) { try { dte.ExecuteCommand("Team.Git.Fetch"); } catch (Exception) { break; } } Thread.Sleep(TimeSpan.FromMinutes(Config.Instance.TimeValue())); } } catch (Exception ex) { throw ex; } }
/// <summary> /// See <see cref="M:Microsoft.Practices.RecipeFramework.IAction.Execute"/>. /// </summary> public override void Execute() { DTE vs = (DTE)GetService(typeof(DTE)); //This assumes that the project to debug is selected vs.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance", ""); }
private void MenuItemCallback_CompareParameterizationToTransform(object sender, EventArgs e) { var myCommand = sender as OleMenuCommand; DTE dte = (DTE)GetService(typeof(SDTE)); if (dte.SelectedItems.Count > 0) { var items = dte.SelectedItems as SelectedItems; foreach (SelectedItem item in items) { if (item.Name.StartsWith("SetParameters.", StringComparison.OrdinalIgnoreCase)) { var configFile = GetProjectFile(item.ProjectItem, "web.config"); configFile = GetProjectFile(item.ProjectItem, "app.config") ?? configFile; var parameterizedResult = GenerateParameterizationResult(item, configFile); PrettifyXml(parameterizedResult); var transformedResult = GenerateConfigTransformResult(item, configFile); dte.ExecuteCommand("Tools.DiffFiles", string.Format("\"{0}\" \"{1}\"", transformedResult, parameterizedResult)); } } } }
public void TestIndexComboBox() { UIThreadInvoker.Invoke((ThreadInvoker) delegate() { //Get the global service provider and the dte IServiceProvider sp = VsIdeTestHostContext.ServiceProvider; DTE dte = (DTE)sp.GetService(typeof(DTE)); //Show toolbar CommandBars commandBars = (CommandBars)dte.CommandBars; commandBars["ComboBoxSample"].Visible = true; // Create the messageBoxListener Thread. string expectedDialogBoxText = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}\n\n{1}", "My Index Combo", "1"); DialogBoxPurger purger = new DialogBoxPurger(NativeMethods.IDOK, expectedDialogBoxText); try { purger.Start(); dte.ExecuteCommand("Tools.IndexCombo", "Tigers"); } finally { Assert.IsTrue(purger.WaitForDialogThreadToTerminate(), "The Index Combo dialog box has not shown"); } }); }
public static bool ExtractPackage(DTE dte, string toolPath, string unmanagedZipPath, string managedZipPath, Project project, CrmDevExSolutionPackage crmDevExSolutionPackage, DirectoryInfo extractedFolder, string commandArgs) { string solutionProjectFolder = GetProjectSolutionFolder(project, crmDevExSolutionPackage.ProjectFolder); dte.ExecuteCommand($"shell {toolPath}", commandArgs); //Need this. Extend to allow bigger solutions to unpack //TODO: Better way? System.Threading.Thread.Sleep(10000); bool solutionFileDelete = RemoveDeletedItems(extractedFolder.FullName, project.ProjectItems, crmDevExSolutionPackage.ProjectFolder); bool solutionFileAddChange = ProcessDownloadedSolution(extractedFolder, Path.GetDirectoryName(project.FullName), project.ProjectItems); Directory.Delete(extractedFolder.FullName, true); if (!crmDevExSolutionPackage.SaveSolutions) { return(true); } //Solution change or file not present bool solutionChange = solutionFileDelete || solutionFileAddChange; bool solutionStored = StoreSolutionFile(unmanagedZipPath, project, solutionProjectFolder, solutionChange); if (crmDevExSolutionPackage.DownloadManaged && !string.IsNullOrEmpty(managedZipPath)) { solutionStored = StoreSolutionFile(managedZipPath, project, solutionProjectFolder, solutionChange); } return(solutionStored); }
private void OptionsButton_Click(object sender, RoutedEventArgs e) { if (_optionPageGuid != default(Guid)) { _dte.ExecuteCommand("Tools.Options", _optionPageGuid.ToString()); } }
private void timer_Jump(object sender, System.Timers.ElapsedEventArgs e) { m_timer.Stop(); if (m_activeDocumentFileName != null) { s_dte.ExecuteCommand("Window.ActivateDocumentWindow"); // s_dte.ExecuteCommand("File.OpenFile", m_activeDocumentFileName); s_dte.ItemOperations.OpenFile(m_activeDocumentFileName, EnvDTE.Constants.vsViewKindTextView); Document document = GetActiveDocument(); if (document != null) { EnvDTE.TextSelection textSelection = (EnvDTE.TextSelection)(document.Selection); textSelection.GotoLine(m_activeDocumentLineNo, false); document.Activate(); if (document.Windows.Count > 0) { document.Windows.Item(1).Activate(); } textSelection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn); } m_activeDocumentFileName = null; } }
internal void ReloadProject(int n) { ThreadHelper.ThrowIfNotOnUIThread(); DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE)); Project proj = dte.Solution.Projects.Item(1); string uniqueName = proj.UniqueName; string name = proj.Name; IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution)); IVsHierarchy hier; Marshal.ThrowExceptionForHR(solutionService.GetProjectOfUniqueName(uniqueName, out hier)); solutionService.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, hier, 0); Window solutionExplorer = dte.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer) as Window; solutionExplorer.Activate(); UIHierarchy uiHier = solutionExplorer.Object as UIHierarchy; UIHierarchyItem item = uiHier.GetItem(Path.GetFileNameWithoutExtension(dte.Solution.FileName) + "\\" + name); item.Select(vsUISelectionType.vsUISelectionTypeSelect); dte.ExecuteCommand("Project.ReloadProject", ""); }
// Expands all regions in the current document public static void ExpandAllRegions(DTE dte, Language language) { if (IsSupportedLanguage(language)) { bool suppressedUI = false; if (!dte.SuppressUI) { dte.SuppressUI = true; // Disable UI while we do this suppressedUI = true; } try { if (language == Language.Python) { // The Python Tools language provider outlines a #region as "#region Test[...]". // Using FindText(...) to force a region expansion won't work for Python because // the "#region" part is still in the visible, non-hidden, non-collapsed text. // So we'll use the ExpandAllOutlining command instead. It will also expand // non-region collapses (e.g., if someone has collapsed a function definition), // so it's not really just an "ExpandAllRegions" command like we want. :-( // Note: This command is only available if outlining is enabled and something // in the document is collapsed. const string ExpandAllCommand = "Edit.ExpandAllOutlining"; EnvDTE.Command command = dte.Commands.Item(ExpandAllCommand, 0); if (command.IsAvailable) { dte.ExecuteCommand(ExpandAllCommand); } } else { TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; // Hook up to the ActiveDocument's selection selection.StartOfDocument(); // Shoot to the start of the document string regionBeginRegex = GetRegionBeginRegex(language); // Loop through the document finding all instances of #region. This action has the side benefit // of actually zooming us to the text in question when it is found and ALSO expanding it since it // is an outline. const int FindOptions = (int)vsFindOptions.vsFindOptionsMatchInHiddenText + (int)vsFindOptions.vsFindOptionsMatchCase + (int)vsFindOptions.vsFindOptionsRegularExpression; while (selection.FindText(regionBeginRegex, FindOptions)) { // The FindText command will expand the #region block if "#region" is hidden. } selection.StartOfDocument(); // Shoot us back to the start of the document } } finally { if (suppressedUI) { dte.SuppressUI = false; // Reenable the UI } } } }
private void OnShowChangesetItems(object sender, ShowChangesetItemsEventArgs e) { var outWindow = (IVsOutputWindow)Package.GetGlobalService(typeof(SVsOutputWindow)); Guid id = Identifiers.ReviewOutputWindowId; outWindow.CreatePane(ref id, "Review", 1, 0); IVsOutputWindowPane generalPane; outWindow.GetPane(ref id, out generalPane); generalPane.Clear(); var sortedServerItems = e.Paths.OrderBy(si => si).ToList(); foreach (string serverItem in sortedServerItems) { generalPane.OutputString(serverItem + Environment.NewLine); } generalPane.OutputString(string.Format("{0} unique items." + Environment.NewLine, e.Paths.Count())); generalPane.Activate(); dte.ExecuteCommand("View.Output", string.Empty); }
public string AddItemTemplateToProjectNew(CodeInfo codeInfo, string packagePath, bool openAfterCreation, int cursorIndex = -1) { string codeFilePath = !Path.HasExtension(codeInfo.Path) ? codeInfo.Path + GlobalConsts.CSExtension : codeInfo.Path; codeFilePath = Path.Combine(packagePath, codeFilePath); var folder = GetProjectFolder(codeFilePath); var fullPathToFolder = folder.Properties.Item("FullPath").Value.ToString(); var codefileName = Path.GetFileName(codeFilePath); var fileFullPath = Path.Combine(fullPathToFolder, codefileName); Encoding witoutBom = new UTF8Encoding(true); this.iOWrapper.WriteAllTextIntoFile(fileFullPath, codeInfo.Code, witoutBom); folder.ProjectItems.AddFromFile(fileFullPath); if (openAfterCreation) { var window = folder.ProjectItems.Item(codefileName).Open(EnvDTE.Constants.vsViewKindCode); window.Visible = true; DTE dte = (DTE)this.vsPackageWrapper.GetGlobalService(typeof(DTE)); try { dte.ExecuteCommand("Edit.Goto", cursorIndex.ToString()); } catch { } } return(fileFullPath); }
internal void Restart(DTE dte, bool elevated) { var currentProcess = Process.GetCurrentProcess(); var parser = new ArgumentParser(dte.CommandLineArguments); var builder = new RestartProcessBuilder() .WithDevenv(currentProcess.MainModule.FileName) .WithArguments(parser.GetArguments()); var openedItem = GetOpenedItem(dte); if (openedItem != OpenedItem.None) { if (openedItem.IsSolution) { builder.WithSolution(openedItem.Name); } else { builder.WithProject(openedItem.Name); } } if (elevated) { builder.WithElevatedPermission(); } const string commandName = "File.Exit"; var closeCommand = dte.Commands.Item(commandName); CommandEvents closeCommandEvents = null; if (closeCommand != null) { closeCommandEvents = dte.Events.CommandEvents[closeCommand.Guid, closeCommand.ID]; } // Install the handler var handler = new VisualStudioEventHandler(dte.Events.DTEEvents, closeCommandEvents, builder.Build()); if (closeCommand != null && closeCommand.IsAvailable) { // if the Exit commad is present, execute it with all gracefulls dialogs by VS dte.ExecuteCommand(commandName); } else { // Close brutally dte.Quit(); } }
public void GoToDisassembly(DTE dte, String method, int offset) { Initialize(dte); if (s_treeview == null) { return; } // Make sure the windows are inti.alized DTE dteX5 = dte.Windows.Item(GuidBreakpoints).DTE; dte.Windows.Item(GuidDisassembly).Visible = dte.Windows.Item(GuidDisassembly).Visible; String address = GetAddress(method, offset); int countBefore = s_treeview.Count; Breakpoints bps = dte.Debugger.Breakpoints.Add("", "", 0, 0, "", dbgBreakpointConditionType.dbgBreakpointConditionTypeWhenTrue, "C#", "", 0, address, 0, dbgHitCountType.dbgHitCountTypeNone); int countAfter = s_treeview.Count; IntPtr selected; IntPtr foundItem; if(!FindBreakpoint(address, method, offset, out foundItem, out selected)) { return; } s_treeview.Select(foundItem); dte.ExecuteCommand(MenuGoToDisassembly, ""); if (countAfter > countBefore) { bps.Item(1).Delete(); } s_treeview.Select(selected); dte.Windows.Item(GuidThreadStack).Activate(); dte.Windows.Item(GuidDisassembly).Activate(); }
public static void SaveAllFiles(DTE dte) { dte.ExecuteCommand("File.SaveAll"); }
private void MigrateCustomizationProject(DTE service, Project project) { Helpers.EnsureCheckout(service, project); Helpers.LogMessage(service, this, "*** Migrating project '" + project.Name + "' ****"); if (Helpers2.IsSharePointVSTemplate(service, project)) { try { ProjectItem packageGeneratorTT = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.Generator.tt"); if (packageGeneratorTT != null) { Helpers.LogMessage(service, this, "Deleting Package/Package.Generator.tt"); Helpers.EnsureCheckout(service, packageGeneratorTT); packageGeneratorTT.Delete(); } } catch { Helpers.LogMessage(service, this, "Warning: Could not delete Package/Package.Generator.tt"); } try { ProjectItem packageGeneratorTMP = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.Generator.tmp"); if (packageGeneratorTMP != null) { Helpers.LogMessage(service, this, "Deleting Package/Package.Generator.tmp"); Helpers.EnsureCheckout(service, packageGeneratorTMP); packageGeneratorTMP.Delete(); } } catch { Helpers.LogMessage(service, this, "Warning: Could not delete Package/Package.Generator.tmp"); } Helpers.LogMessage(service, this, "Settings IncludeAssemblyInPackge to True"); try { Helpers.SetProjectPropertyGroupValue(project, "IncludeAssemblyInPackage", "True"); } catch { } } //4. add property Sandboxedsolution if property is not available try { string testvalue = Helpers.GetProjectPropertyGroupValue(project, "Sandboxedsolution", "NOTFOUND").ToString(); if (testvalue == "NOTFOUND") { Helpers.LogMessage(service, this, "Updated project property 'Sandboxedsolution'"); Helpers.SetProjectPropertyGroupValue(project, "Sandboxedsolution", "False"); } } catch { } try { string nameOfProject = project.Name; //Helpers2.MoveProjectToSolutionFolder(service, project.Name, "Solutions"); //after moving we need to get the moved project again from the name project = Helpers.GetProjectByName(service, nameOfProject); } catch { } //5. Add import to SharePoint.targets (e.g. for WSP projects) string fileName = project.FullName; Helpers.SelectProject(project); if (service.SuppressUI || MessageBox.Show("The project file of project " + project.Name + " must be updated. Can SPSF save and unload the project?", "Unloading project", MessageBoxButtons.YesNo) == DialogResult.Yes) { service.Documents.CloseAll(vsSaveChanges.vsSaveChangesPrompt); try { Helpers.LogMessage(project.DTE, this, "Updating csproj file"); service.ExecuteCommand("File.SaveAll", string.Empty); service.ExecuteCommand("Project.UnloadProject", string.Empty); MigrateFile(fileName); //project.Imports.AddNewImport(@"C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.CSharp.targets", null); //project.Save(fileName); service.ExecuteCommand("Project.ReloadProject", string.Empty); } catch { } } }
/// <summary> /// Invoke menu action for the given menu item using specified operation type /// </summary> /// <param name="dte">The DTE object</param> /// <param name="menuItem">The menu item</param> /// <param name="operationType">The type of the operation, i.e., via menu command or keyboard</param> public static void Invoke(DTE dte, MenuItem menuItem, OperationType operationType) { switch (operationType) { case OperationType.MenuCommand: dte.ExecuteCommand(CommandStrings[menuItem], string.Empty); break; case OperationType.Keyboard: // TODO: This is not stable right now and might cause rolling build failure. // So it is just a placeholder for now. // SendKeys.SendWait(KeyStrokes[menuItem]); // TODO: throwing an exception if not used should be removed // otherwise fix verify and remove the other TODO throw new NotSupportedException("OperationType"); default: throw new NotSupportedException("OperationType"); } }