public void WriteLine(string format, params object[] args) { var message = string.Format(format, args); bool cancel; waitDialog.UpdateProgress(message, null, null, 0, 0, false, out cancel); }
public void Execute(SelectedItems selectedItems, CancellationTokenSource cts, IVsThreadedWaitDialog2 dialog, int totalCount, TextSelectionExecutor textSelectionExecutor, Func <string, string> projectItemApplyAttributing, string dialogAction = "Attributing") { ThreadHelper.ThrowIfNotOnUIThread(); if (selectedItems == null) { return; } var currentCount = 0; bool cancelProcessing = false; foreach (SelectedItem selectedItem in selectedItems) { dialog?.HasCanceled(out cancelProcessing); if (cancelProcessing) { cts.Cancel(); break; } if (selectedItem.ProjectItem == null) { continue; } Action <string> projectItemAttributingComplete = (fileName) => { ThreadHelper.ThrowIfNotOnUIThread(); currentCount++; dialog?.UpdateProgress($"{dialogAction}: {fileName}", $"{currentCount} of {totalCount} Processed", dialogAction, currentCount, totalCount, false, out cancelProcessing); if (cancelProcessing) { cts.Cancel(); } }; Action <string> projectItemAttributingStarted = (fileName) => { ThreadHelper.ThrowIfNotOnUIThread(); dialog?.UpdateProgress($"{dialogAction}: {fileName}", $"{currentCount} of {totalCount} Processed", dialogAction, currentCount, totalCount, false, out cancelProcessing); if (cancelProcessing) { cts.Cancel(); } }; ProcessProjectItem(selectedItem.ProjectItem, cts.Token, textSelectionExecutor, projectItemAttributingComplete, projectItemAttributingStarted, projectItemApplyAttributing); } }
/// <summary> /// This event could be raised from multiple threads. Only perform thread-safe operations /// </summary> private void PackageRestoreManager_PackageRestored(object sender, PackageRestoredEventArgs args) { PackageIdentity packageIdentity = args.Package; if (args.Restored && CancellationTokenSource != null && !CancellationTokenSource.IsCancellationRequested) { bool canceled = false; Interlocked.Increment(ref CurrentCount); // The rate at which the packages are restored is much higher than the rate at which a wait dialog can be updated // And, this event is raised by multiple threads // So, only try to update the wait dialog if an update is not already in progress. Use the int 'WaitDialogUpdateGate' for this purpose // Always, set it to 1 below and gets its old value. If the old value is 0, go and update, otherwise, bail if (Interlocked.Equals(Interlocked.Exchange(ref WaitDialogUpdateGate, 1), 0)) { _waitDialog.UpdateProgress( String.Format(CultureInfo.CurrentCulture, Resources.RestoredPackage, packageIdentity.ToString()), String.Empty, szStatusBarText: null, iCurrentStep: CurrentCount, iTotalSteps: TotalCount, fDisableCancel: false, pfCanceled: out canceled); Interlocked.Exchange(ref WaitDialogUpdateGate, 0); } } }
public void ShowWaitDialog(string item) { if (_waitDialog == null) { return; } lock (_waitDialog) { string message = String.Format(CultureInfo.CurrentCulture, _format, item); int hr; if (!_started) { hr = _waitDialog.StartWaitDialog( _caption, message, "", "", message, m_delayShowDialogTimeInSeconds, /*fIsCancelable*/ false, /*fShowMarqueeProgress*/ true ); } else { bool canceled; hr = _waitDialog.UpdateProgress(message, "", message, 0, 0, /*fDisableCancel*/ true, out canceled); } if (hr != VSConstants.S_OK) { return; } _started = true; } }
/// <summary> /// Restores packages listed in the <paramref name="packageReferenceFileFullPath"/> into the packages folder /// represented by <paramref name="fileSystem"/>. /// </summary> /// <param name="packageReferenceFileFullPath">The package reference file full path.</param> /// <param name="fileSystem">The file system that represents the packages folder.</param> private void RestorePackages(string packageReferenceFileFullPath, IFileSystem fileSystem) { if (packageReferenceFileFullPath == null) { return; } var packageReferenceFile = new PackageReferenceFile(packageReferenceFileFullPath); var packages = packageReferenceFile.GetPackageReferences().ToList(); int currentCount = 1; int totalCount = packages.Count; foreach (var package in packages) { if (IsPackageInstalled(fileSystem, package.Id, package.Version)) { WriteLine(VerbosityLevel.Normal, Resources.SkippingInstalledPackage, package); continue; } _hasMissingPackages = true; if (_outputOptOutMessage) { _waitDialog.StartWaitDialog( VsResources.DialogTitle, Resources.RestoringPackages, String.Empty, varStatusBmpAnim: null, szStatusBarText: null, iDelayToShowDialog: 0, fIsCancelable: true, fShowMarqueeProgress: true); WriteLine(VerbosityLevel.Quiet, Resources.PackageRestoreOptOutMessage); _outputOptOutMessage = false; } bool canceled; _waitDialog.UpdateProgress( String.Format(CultureInfo.CurrentCulture, Resources.RestoringPackagesListedInFile, packageReferenceFileFullPath), String.Format(CultureInfo.CurrentCulture, Resources.RestoringPackage, package.ToString()), szStatusBarText: null, iCurrentStep: currentCount, iTotalSteps: totalCount, fDisableCancel: false, pfCanceled: out canceled); if (canceled) { return; } RestorePackage(package); ++currentCount; } }
public void UpdateProgress(int currentSteps, int totalSteps) { bool canceled; _waitDialog.UpdateProgress( null, null, null, currentSteps, totalSteps, false, out canceled ); }
private bool UpdateProgressInternal(string message, bool disableCancelable, int currentStep, int totalSteps) { var hasCanceled = false; if (_dialogStarted) { ThrowOnFailure( _waitDialog.UpdateProgress( null, message, null, currentStep, totalSteps, disableCancelable, out hasCanceled)); } return(hasCanceled); }
private void OnUpdateProgress(object sender, DownloadProgressChangedEventArgs ea) { bool isCanceled = true; waitDialog?.UpdateProgress( dialogDesc?.WaitMessage, dialogDesc?.ProgressText, dialogDesc?.StatusBarText, ea.ProgressPercentage, 100, false, out isCanceled); if (isCanceled && !IsCanceledByUser) { IsCanceledByUser = isCanceled; webClient?.CancelAsync(); } }
private void OnUpdateProgress(object sender, DataReceivedEventArgs e) { bool isButtonClicked = false; waitDialog?.UpdateProgress(string.Empty, e.Data, e.Data, 0, 100, false, out isButtonClicked); isCanceled |= isButtonClicked; if (isCanceled) { Kill(); } else { OnProcessUpdated?.Invoke(sender, e); } }
public static void QueryLinkTypesCallback(object sender, EventArgs e) { //IntPtr hier; //uint itemid; //IVsMultiItemSelect dummy; //string canonicalName; bool bcanceled; int icanceled; string OperationCaption = "Change Work Items Link Types"; IVsThreadedWaitDialog2 dlg = null; var lkdlg = new EditLinkTypeDialog(Utilities.wistore); var dlgResult = lkdlg.ShowDialog(); if (dlgResult != DialogResult.OK) { return; } var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; try { dlg = Utilities.CreateThreadedWaitDialog(OperationCaption, "Parsing query...", "status", 100); dlg.UpdateProgress(OperationCaption, "Parsing query...", "status", 1, 100, true, out bcanceled); var WIQueriesPageExt = Utilities.teamExplorer.CurrentPage.GetService <IWorkItemQueriesExt>(); var qItem = WIQueriesPageExt.SelectedQueryItems.First(); int[] qdata; int changedlinks = 0; bcanceled = ExecuteQueryLinkTypes(qItem as QueryDefinition, qItem.Project.Name, out qdata); dlg.UpdateProgress(OperationCaption, "Changing Link Types...", "status", 1, 100, false, out bcanceled); if (!bcanceled) { changedlinks = ChangeLinkTypes(qdata, lkdlg.fromlink, lkdlg.tolink); } dlg.EndWaitDialog(out icanceled); if (!bcanceled) { MessageBox.Show(changedlinks + " links were changed.", Utilities.AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } dlg.EndWaitDialog(out icanceled); Cursor.Current = origCursor; } catch (Exception ex) { if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Cursor.Current = origCursor; Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } }
/// <summary> /// Tries to create stash staged (if operatiopn wasn't successful - shows Team Explorer notification). /// </summary> /// <param name="message">message that should be assigned to the Stash.</param> /// <returns>True if operation was successful, otherwise - false.</returns> public bool TryCreateStashStaged(string message) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); IVsThreadedWaitDialog2 dialog = null; if (_dialogFactory != null) { _dialogFactory.CreateInstance(out dialog); } // Step 1. git stash keep staged. if (dialog != null) { dialog.StartWaitDialogWithPercentageProgress("Stash staged", "Step 1: git stash --keep-index", "Waiting...", null, "Waiting", false, 0, 4, 1); } if (!_gitCommandExecuter.TryCreateStashKeepIndex(out var errorMessage)) { dialog?.EndWaitDialog(out _); _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid()); return(false); } // Step 2. git stash if (dialog != null) { dialog.UpdateProgress($"Step 2: git stash save '{message}'", "Waiting...", "Waiting", 2, 4, true, out _); } if (!_gitCommandExecuter.TryCreateStash(message, true, out errorMessage)) { dialog?.EndWaitDialog(out _); _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid()); return(false); } // Step 3. git stash apply if (dialog != null) { dialog.UpdateProgress("Step 3: git stash apply stash@{1}", "Waiting...", "Waiting", 3, 4, true, out _); } if (!_gitCommandExecuter.TryApplyStash(1, out errorMessage)) { dialog?.EndWaitDialog(out _); _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid()); return(false); } // Step 4. git stash drop if (dialog != null) { dialog.UpdateProgress("Step 4: git stash drop stash@{1}", "Waiting...", "Waiting", 4, 4, true, out _); } if (!_gitCommandExecuter.TryDeleteStash(1, out errorMessage)) { dialog?.EndWaitDialog(out _); _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid()); return(false); } dialog?.EndWaitDialog(out _); return(true); }
/// <summary> /// Menu callback event handler that activates the merge pane after selecting paths in Source Control Explorer. /// See <see cref="MergeWIControl"/> /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void MySCQuBuildIDCallback(object sender, EventArgs e) { var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; IVsThreadedWaitDialog2 dlg = null; bool nolinks = true; bool bcanceled = false; int icanceled; try { if (Utilities.vcext.Explorer.Workspace.Folders.Length == 0) { Cursor.Current = origCursor; MessageBox.Show("The workspace is not mapped to any local folder.", Utilities.AppTitle); return; } string folderPath = Utilities.vcext.Explorer.CurrentFolderItem.SourceServerPath; if (!MergeFactory.ServerItemExists(folderPath)) { Cursor.Current = origCursor; MessageBox.Show("Target server path is cloacked or doesn't exist.", Utilities.AppTitle); return; } if (Utilities.paneMerge == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Pane was null.", Utilities.AppTitle); return; } var mfrm = Utilities.paneMerge.control; mfrm.SuppressEvents = true; mfrm.defServerName = folderPath; mfrm.Initialize(); mfrm.ClearGrids(); IVsWindowFrame frame = Utilities.paneMerge.Frame as IVsWindowFrame; if (frame == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Frame was null.", Utilities.AppTitle); return; } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changests...", "status", 100); dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled); foreach (string sourcePath in Utilities.vcext.Explorer.SelectedItems.Select(x => x.SourceServerPath)) { int idx = 0; foreach (Changeset ch in Utilities.vcsrv.QueryHistory(sourcePath, VersionSpec.Latest, 0, RecursionType.Full, null, null, null, Int32.MaxValue, true, true, false, false)) { if (ch.Changes == null || ch.Changes.Length == 0) { continue; } string change = ch.Changes.Take(5).Select(x => x.ChangeType.ToString()).Aggregate((x, y) => x + "," + y); if (ch.Changes.Length > 5) { change += "..."; } string wrkitemstr = ""; int wrkitemid = 0; if (ch.WorkItems != null && ch.WorkItems.Length > 0) { wrkitemstr = ch.WorkItems.Select(x => x.Id.ToString()).Aggregate((x, y) => x + "," + y); wrkitemid = ch.WorkItems[0].Id; } ListViewItem itm = mfrm.AddNewGridItem(wrkitemstr, ch.ChangesetId.ToString(), ch.CreationDate.ToShortDateString(), ch.Owner, sourcePath, change, ch.Comment, new ListViewItemTag(ch.ChangesetId, wrkitemid, sourcePath, ch.CreationDate)); Utilities.OutputCommandString("Adding Changeset: " + itm.Name + " => " + sourcePath); nolinks = false; dlg.UpdateProgress("Collecting information about changesets", "Processing changeset: " + ch.ChangesetId, "status", idx++, 100, false, out bcanceled); if (bcanceled) { mfrm.SortItems(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; return; } if (idx == 100) { idx = 0; } } } mfrm.SortItems(); mfrm.UpdateRelatedBranchesCombo(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); if (nolinks) { MessageBox.Show("No Changesets where found in selected path.", Utilities.AppTitle); } } catch (Exception ex) { Cursor.Current = origCursor; if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } return; }
public static bool CreateWordDocParagraph(string qname, string[][] qdata, IVsThreadedWaitDialog2 dlg) { //InitializeVariables(); System.Net.WebClient webclient = new System.Net.WebClient(); webclient.Credentials = System.Net.CredentialCache.DefaultCredentials; var application = new MSWord.Application(); var document = new MSWord.Document(); object missing = System.Reflection.Missing.Value; int pagewidth = 800; bool bcanceled; int progress = 1; StringBuilder strbld = new StringBuilder(); MSWord.WdBuiltinStyle[] hstyles = new MSWord.WdBuiltinStyle[8]; hstyles[0] = MSWord.WdBuiltinStyle.wdStyleHeading1; hstyles[1] = MSWord.WdBuiltinStyle.wdStyleHeading2; hstyles[2] = MSWord.WdBuiltinStyle.wdStyleHeading3; hstyles[3] = MSWord.WdBuiltinStyle.wdStyleHeading4; hstyles[4] = MSWord.WdBuiltinStyle.wdStyleHeading5; hstyles[5] = MSWord.WdBuiltinStyle.wdStyleHeading6; hstyles[6] = MSWord.WdBuiltinStyle.wdStyleHeading7; hstyles[7] = MSWord.WdBuiltinStyle.wdStyleHeading8; application.Visible = true; application.WindowState = MSWord.WdWindowState.wdWindowStateMinimize; application.DisplayAlerts = MSWord.WdAlertLevel.wdAlertsNone; document = application.Documents.Add(); //document.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape; document.PageSetup.LeftMargin = 20; document.PageSetup.RightMargin = 20; document.PageSetup.TopMargin = 20; document.PageSetup.BottomMargin = 20; document.PageSetup.PageWidth = pagewidth + 40; MSWord.Paragraph prg = document.Paragraphs.Add(); prg.Range.Text = "Query results for " + qname + " [" + DateTime.Now + "]"; prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle); //prg.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; prg.SpaceAfter = 100; prg.SpaceBefore = 100; prg.Range.InsertParagraphAfter(); prg = document.Paragraphs.Add(); prg.Range.Text = "Table of Contents"; prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTocHeading); prg.Range.InsertParagraphAfter(); prg = document.Paragraphs.Add(); prg.Range.Text = "TOC"; prg.Range.InsertParagraphAfter(); prg.Range.InsertBreak(MSWord.WdBreakType.wdPageBreak); prg = document.Paragraphs.Add(); MSWord.Table qtable = document.Tables.Add(prg.Range, qdata.Length, 1); prg.Range.InsertParagraphAfter(); prg = document.Paragraphs.Add(); prg.Range.Text = "Appendix"; prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleTitle); prg.Range.InsertParagraphAfter(); object styleTypeTable = MSWord.WdStyleType.wdStyleTypeTable; MSWord.Style styl = document.Styles.Add("New Table Style", ref styleTypeTable); styl.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle; styl.ParagraphFormat.SpaceAfter = 0; styl.ParagraphFormat.SpaceBefore = 0; styl.Table.TopPadding = 0; styl.Table.BottomPadding = 0; styl.Table.LeftPadding = 0; styl.Table.RightPadding = 0; //styl.Table.Borders.Enable = 1; qtable.Range.set_Style(styl); MSWord.Cell cell = qtable.Cell(1, 1); int headerwidth = 85; int levelwidth = 100; object rows, cols; for (int i = 0; i < qdata.Length; i++) { int level = int.Parse(qdata[i][1]); if (level > 0) { rows = 1; cols = 2; cell.Split(ref rows, ref cols); cell.Range.Cells.SetWidth(level * levelwidth, MSWord.WdRulerStyle.wdAdjustSameWidth); cell = cell.Next; } rows = 1 + (string.IsNullOrWhiteSpace(qdata[i][0]) ? 0 : 1) + (string.IsNullOrWhiteSpace(qdata[i][6]) ? 0 : 1); cols = 2; cell.Split(ref rows, ref cols); cell.Merge(cell.Next); string title = String.Format("{0} {1} ({2})", qdata[i][2], (qdata[i][5].Length > 128 ? qdata[i][5].Remove(128) : qdata[i][5]).Replace("\n", "").Replace("\r", "").Replace("\t", ""), qdata[i][4]); cell.Range.Text = title; cell.Range.Font.Bold = 1; cell.Range.set_Style(hstyles[level < 8 ? level:7]); cell = cell.Next; dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to Word document " + qdata[i][3] + " #" + qdata[i][4], "status", progress++, 100, false, out bcanceled); if (progress == 100) { progress = 0; } if (bcanceled) { application.Visible = true; Marshal.ReleaseComObject(document); Marshal.ReleaseComObject(application); return(true); } /*cell.Range.Text = "Title"; * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth); * cell.Range.Font.Bold = 1; * cell = cell.Next; * * cell.Range.Text = qdata[i][4]; * cell = cell.Next;*/ /*cell.Range.Text = "Description"; * cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth); * cell.Range.Font.Bold = 1; * cell = cell.Next;*/ if (!string.IsNullOrWhiteSpace(qdata[i][6])) { cell.Merge(cell.Next); cell.Range.Text = qdata[i][6]; cell = cell.Next; } if (!string.IsNullOrWhiteSpace(qdata[i][0])) { cell.Range.Text = "Attachments"; cell.Range.Cells.SetWidth(headerwidth, MSWord.WdRulerStyle.wdAdjustSameWidth); cell.Range.Font.Bold = 1; cell = cell.Next; var query = qdata[i][0] .Split(';') .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => { string[] ch = x.Split('~'); return(new { name = ch[0], value = ch[1] }); }).ToArray(); cell.Split(query.Length, 1); foreach (var kvp in query) { string localpath = Path.GetTempFileName() + "." + kvp.name; //try { File.Delete(localpath); } //catch { } try { webclient.DownloadFile(kvp.value, localpath); } catch (Exception ex) { localpath = ""; Utilities.OutputCommandString(ex.ToString()); } prg = document.Paragraphs.Add(); prg.Range.Text = kvp.name; prg.Range.set_Style(MSWord.WdBuiltinStyle.wdStyleHeading3); cell.Range.Text = kvp.name; document.Hyperlinks.Add(cell.Range, missing, prg.Range); prg.Range.InsertParagraphAfter(); document.InlineShapes.AddHorizontalLineStandard(prg.Range); prg = document.Paragraphs.Add(); if (!string.IsNullOrEmpty(localpath)) { try { Image img = Image.FromFile(localpath); img.Dispose(); document.InlineShapes.AddPicture(localpath, false, true, prg.Range); } catch { if (Path.GetExtension(kvp.name).Equals(".sql", StringComparison.InvariantCultureIgnoreCase) || Path.GetExtension(kvp.name).Equals(".txt", StringComparison.InvariantCultureIgnoreCase)) { prg.Range.InsertFile(localpath);//, prg.Range, false, true, false); } else { MSWord.InlineShape shape = document.InlineShapes.AddOLEObject(missing, localpath, false, false, missing, missing, missing, prg.Range); if (shape.OLEFormat.ClassType.ToString() != "Package") { shape.Width = document.PageSetup.PageWidth - 40; } } } } cell = cell.Next; } if (query.Length == 0) { cell = cell.Next; } } } object styleTypePara = MSWord.WdStyleType.wdStyleTypeParagraph; MSWord.Style styl2 = document.Styles.Add("New Paragraph Style", ref styleTypePara); //styl2.ParagraphFormat.set_Style(MSWord.WdBuiltinStyle.wdStyleNormal); styl2.ParagraphFormat.LeftIndent = 100; styl2.ParagraphFormat.RightIndent = 100; styl2.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle; styl2.ParagraphFormat.SpaceAfter = 0; styl2.ParagraphFormat.SpaceBefore = 0; MSWord.Paragraph tocpara = document.Paragraphs[3]; MSWord.TableOfContents tblct = document.TablesOfContents.Add(tocpara.Range, missing, 1, 1); tblct.Update(); //tblct.Range.set_Style(styl2); //application.Visible = true; Marshal.ReleaseComObject(document); Marshal.ReleaseComObject(application); return(false); }
public static async Task <Report> ProcessAsync(IAsyncServiceProvider serviceProvider, bool addComment) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var report = new Report(); var dte = (DTE)await serviceProvider.GetServiceAsync(typeof(DTE)); if (dte == null || string.IsNullOrEmpty(dte.Solution.FullName)) { report.SolutionName = "N/A"; return(report); } report.SolutionName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileName(dte.Solution.FullName)); IVsStatusbar statusBar = (IVsStatusbar)await serviceProvider.GetServiceAsync(typeof(SVsStatusbar)); IVsThreadedWaitDialogFactory factory = (IVsThreadedWaitDialogFactory)await serviceProvider.GetServiceAsync( typeof(SVsThreadedWaitDialogFactory)); IVsThreadedWaitDialog2 dialog = null; factory?.CreateInstance(out dialog); dialog?.StartWaitDialog("PVSStudio Helper", (addComment) ? "Add comment" : "Remove comment", null, null, null, 0, false, true); IVsOutputWindow outWindow = (IVsOutputWindow)await serviceProvider.GetServiceAsync(typeof(SVsOutputWindow)); var generalPaneGuid = VSConstants.GUID_OutWindowGeneralPane; // P.S. There's also the GUID_OutWindowDebugPane available. IVsOutputWindowPane generalPane = null; outWindow?.GetPane(ref generalPaneGuid, out generalPane); if (generalPane == null) { outWindow?.CreatePane(ref generalPaneGuid, "General", 1, 0); outWindow?.GetPane(ref generalPaneGuid, out generalPane); } await ProjectProcess.ProcessAsync(dte, report, addComment, async (message) => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); dialog?.UpdateProgress(null, message, null, 0, 0, true, out var canceled); //messagePump.WaitText = message; if (statusBar != null) { statusBar.IsFrozen(out var isFrozen); if (isFrozen == 0) { statusBar.SetText(message); } } generalPane?.OutputString($"{message}{Environment.NewLine}"); }); var finalMessage = $"The solution {report.SolutionName} processed. Processed items: {report.ProcessedItems}, include opened items {report.ProcessedOpenedItems}"; if (statusBar != null) { statusBar.IsFrozen(out var isFrozen); if (isFrozen == 0) { statusBar.SetText(finalMessage); } } generalPane?.OutputStringThreadSafe($"{finalMessage}{Environment.NewLine}"); dialog.EndWaitDialog(); return(report); }
/// <summary> /// Menus the item callback. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void TeamExpQueryCallback(object sender, EventArgs e) { var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; //IntPtr hier; //uint itemid; //IVsMultiItemSelect dummy; //string canonicalName; bool bcanceled; int icanceled; string OperationCaption = "Exporting Work Item query to Microsoft Word document"; IVsThreadedWaitDialog2 dlg = null; try { dlg = Utilities.CreateThreadedWaitDialog(OperationCaption, "Parsing query...", "status", 100); dlg.UpdateProgress(OperationCaption, "Parsing query...", "status", 1, 100, false, out bcanceled); //Utilities.vsTeamExp.TeamExplorerWindow.GetCurrentSelection(out hier, out itemid, out dummy); //IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hier); //Marshal.Release(hier); //hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_ExtSelectedItem, out res); //MessageBox.Show(res.GetType().ToString()); //hierarchy.GetCanonicalName(itemid, out canonicalName); /* * string[] tokens = canonicalName.Split('/'); * string ProjectName = tokens[1]; * var proj = Utilities.wistore.Projects[ProjectName]; * * QueryItem qItem = proj.QueryHierarchy; * * int currentTokenIndex = 2; * while (currentTokenIndex < tokens.Length) * { * qItem = (qItem as QueryFolder)[tokens[currentTokenIndex]]; * currentTokenIndex++; * }*/ var WIQueriesPageExt = Utilities.teamExplorer.CurrentPage.GetService <IWorkItemQueriesExt>(); var qItem = WIQueriesPageExt.SelectedQueryItems.First(); //string[] qheader; string[][] qdata; bcanceled = ExecuteQueryLimitedFields(dlg, qItem as QueryDefinition, qItem.Project.Name, out qdata); dlg.UpdateProgress(OperationCaption, "Creating new Word document...", "status", 1, 100, false, out bcanceled); CreateWordDocParagraph((qItem as QueryDefinition).Name, qdata, dlg); Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); } catch (Exception ex) { Cursor.Current = origCursor; if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } }
static dynamic BuildBTree(ItemIdentifier root) { Cursor origCursor = Cursor.Current; IVsThreadedWaitDialog2 dlg = null; bool bcanceled; int icanceled, idx = 0; DateTime minDate = DateTime.MaxValue, maxDate = DateTime.MinValue; Cursor.Current = Cursors.WaitCursor; dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changesets...", "status", 100); dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled); var branches = new List <BTreeItem>(); foreach (var item in Utilities.vcsrv.QueryRootBranchObjects(RecursionType.Full)) { var itm = new BTreeItem { Path = item.Properties.RootItem.Item, CreationDate = item.DateCreated, parentPath = item.Properties.ParentBranch == null ? null : item.Properties.ParentBranch.Item, version = (item.Properties.RootItem.Version as ChangesetVersionSpec).ChangesetId, RelatedBranches = Utilities.vcsrv .QueryMergeRelationships(item.Properties.RootItem.Item) .Select(x => new Tuple <BTreeItem, Changeset[]>(new BTreeItem { Path = x.Item }, Utilities.vcsrv .GetMergeCandidates(item.Properties.RootItem.Item, x.Item, RecursionType.Full) .Select(z => z.Changeset).ToArray())) .ToList() }; if (itm.CreationDate < minDate) { minDate = itm.CreationDate; } if (itm.CreationDate > maxDate) { maxDate = itm.CreationDate; } branches.Add(itm); dlg.UpdateProgress("Collecting information about changesets", "Processing branch: " + itm.Path, "status", idx++, 100, false, out bcanceled); if (bcanceled) { break; } } var broot = new BTreeItem(); foreach (var itm in branches) { if (itm.parentPath == null) { broot.children.Add(itm); itm.parent = broot; } else { itm.parent = branches.FirstOrDefault(x => x.Path == itm.parentPath); if (itm.parent != null) { itm.parent.children.Add(itm); } else { broot.children.Add(itm); } } itm.RelatedBranches = itm.RelatedBranches .Select(x => new Tuple <BTreeItem, Changeset[]>(branches.FirstOrDefault(z => z.Path == x.Item1.Path), x.Item2)) .ToList(); itm.relY = (int)itm.CreationDate.Subtract(minDate).TotalDays; foreach (var ch in itm.RelatedBranches.SelectMany(x => x.Item2)) { if (ch.CreationDate > maxDate) { maxDate = ch.CreationDate; } } } idx = 0; var res = ShowRevHistPackage.TreeDescendants2(broot, ref idx).OrderBy(x => x.relX).ToList(); res.ForEach(x => Utilities.OutputCommandString(x.relX + " " + (x.parentPath ?? "") + "=" + x.DisplayText)); Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); return(new { ylines = (int)(maxDate.Subtract(minDate).TotalDays * 1.1) + 1, xlines = idx + 1, branches = res }); }
public static bool ExecuteQueryLimitedFields(IVsThreadedWaitDialog2 dlg, QueryDefinition qdef, string ProjectName, out string[][] qdata) { bool bcanceled; int progress = 1; int locidx = 1; int maxlevel = 32; WorkItemLinkInfo[] links = null; Hashtable context = new Hashtable(); List <Tag> qresults = new List <Tag>(); StringBuilder strb = new StringBuilder(); List <string[]> lqdata = new List <string[]>(); context.Add("project", ProjectName); //@me, @today are filled automatically var query = new Query(Utilities.wistore, qdef.QueryText, context); if (query.IsLinkQuery) { links = query.RunLinkQuery(); WorkItemLinkTypeEnd[] linkTypes = null; if (query.IsTreeQuery) { linkTypes = query.GetLinkTypes(); } else { maxlevel = 1; } int idx, flag, level = 0, origidx = 1; string origprefix = ""; foreach (var wilnk in links) { if (wilnk.SourceId == 0) { qresults.Add(new Tag() { tWorkItemID = wilnk.TargetId, tlevel = 0, tParentID = 0, tPrefix = (locidx++).ToString() }); } Utilities.OutputCommandString(string.Format("SourceId={0} TargetId={1} LinkTypeId={2}", wilnk.SourceId, wilnk.TargetId, wilnk.LinkTypeId)); } List <int> chldarr = new List <int>(); if (qresults.Count > 0) { while (level < maxlevel) { level++; flag = 0; locidx = 1; foreach (var wilnk in links.Where(x => x.SourceId > 0)) { string lnkname = query.IsTreeQuery ? linkTypes.First(x => x.Id == wilnk.LinkTypeId).ImmutableName : wilnk.LinkTypeId.ToString(); idx = -1; if ((idx = qresults.IndexOf(new Tag() { tWorkItemID = wilnk.SourceId, tlevel = level - 1 })) >= 0) { if (origprefix != qresults[idx].tPrefix) { if (locidx > 2) { var qrescopy = qresults.Skip(origidx + 1).Take(locidx - 1); Utilities.OutputCommandString("level=" + level + ", qrescopy=" + qrescopy.Select(x => x.tPrefix).Aggregate((x, y) => x + "," + y)); var orig = qrescopy.GetEnumerator(); var prefix = qrescopy.Select(x => x.tPrefix).Reverse().GetEnumerator(); while (orig.MoveNext() && prefix.MoveNext()) { orig.Current.tPrefix = prefix.Current; } } locidx = 1; origprefix = qresults[idx].tPrefix; origidx = idx; } qresults.Insert(idx + 1, new Tag() { tWorkItemID = wilnk.TargetId, tlevel = level, tLinkTypeID = lnkname, tParentID = wilnk.SourceId, tPrefix = origprefix + "." + (locidx++).ToString() }); flag = 1; dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Parsing Work Item #" + wilnk.TargetId.ToString(), "status", progress++, 100, false, out bcanceled); if (progress == 100) { progress = 0; } if (bcanceled) { flag = 0; break; } } } if (flag == 0) { break; } } } foreach (var tag in qresults) { strb.Clear(); WorkItem wi = Utilities.wistore.GetWorkItem(tag.tWorkItemID); strb.Clear(); string stratt; foreach (Attachment att in wi.Attachments) { strb.Append(att.Name + "~" + att.Uri.ToString() + ";"); } stratt = strb.ToString(); Utilities.OutputCommandString(stratt); lqdata.Add(new[] { stratt, tag.tlevel.ToString(), tag.tPrefix, wi[CoreFieldReferenceNames.WorkItemType].ToString(), wi[CoreFieldReferenceNames.Id].ToString(), wi[CoreFieldReferenceNames.Title].ToString(), wi[CoreFieldReferenceNames.Description].ToString() }); dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to collection Work Item #" + wi.Id.ToString(), "status", progress++, 100, false, out bcanceled); if (progress == 100) { progress = 0; } if (bcanceled) { break; } Utilities.OutputCommandString(string.Format("ParentID={0}, WorkItemID={1}, Level={2}", tag.tParentID, tag.tWorkItemID, tag.tlevel)); } } else { locidx = 1; foreach (WorkItem wi in query.RunQuery()) { strb.Clear(); string stratt; foreach (Attachment att in wi.Attachments) { strb.Append(att.Name + "~" + att.Uri.ToString() + ";"); } stratt = strb.ToString(); Utilities.OutputCommandString(stratt); string witype = wi[CoreFieldReferenceNames.WorkItemType].ToString(); string wiid = wi[CoreFieldReferenceNames.Id].ToString(); lqdata.Add(new[] { stratt, "0", (locidx++).ToString(), witype, wiid, wi[CoreFieldReferenceNames.Title].ToString(), wi[CoreFieldReferenceNames.Description].ToString() }); dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Parsing " + witype + " #" + wiid, "status", progress++, 100, false, out bcanceled); if (progress == 100) { progress = 0; } if (bcanceled) { break; } } } qdata = lqdata.ToArray(); return(false); }
private void TrialAndErrorRemovalThreadFunc(EnvDTE.Document document, TrialAndErrorRemovalOptionsPage settings, Formatter.IncludeLineInfo[] includeLines, IVsThreadedWaitDialog2 progressDialog, ITextBuffer textBuffer) { int numRemovedIncludes = 0; bool canceled = false; try { int currentProgressStep = 0; // For ever include line.. foreach (Formatter.IncludeLineInfo line in includeLines) { // If we are working from top to bottom, the line number may have changed! int currentLine = line.LineNumber; if (settings.RemovalOrder == TrialAndErrorRemovalOptionsPage.IncludeRemovalOrder.TopToBottom) { currentLine -= numRemovedIncludes; } // Update progress. string waitMessage = $"Removing #includes from '{document.Name}'"; string progressText = $"Trying to remove '{line.IncludeContent}' ..."; progressDialog.UpdateProgress( szUpdatedWaitMessage: waitMessage, szProgressText: progressText, szStatusBarText: "Running Trial & Error Removal - " + waitMessage + " - " + progressText, iCurrentStep: currentProgressStep + 1, iTotalSteps: includeLines.Length + 1, fDisableCancel: false, pfCanceled: out canceled); if (canceled) { break; } ++currentProgressStep; // Remove include - this needs to be done on the main thread. Application.Current.Dispatcher.Invoke(() => { using (var edit = textBuffer.CreateEdit()) { if (settings.KeepLineBreaks) { edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).Extent); } else { edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).ExtentIncludingLineBreak); } edit.Apply(); } outputWaitEvent.Set(); }); outputWaitEvent.WaitOne(); // Compile - In rare cases VS tells us that we are still building which should not be possible because we have received OnBuildFinished // As a workaround we just try again a few times. { const int maxNumCompileAttempts = 3; for (int numCompileFails = 0; numCompileFails < maxNumCompileAttempts; ++numCompileFails) { try { VSUtils.VCUtils.CompileSingleFile(document); } catch (Exception e) { Output.Instance.WriteLine("Compile Failed:\n{0}", e); if (numCompileFails == maxNumCompileAttempts - 1) { document.Undo(); throw e; } else { // Try again. System.Threading.Thread.Sleep(100); continue; } } break; } } // Wait till woken. bool noTimeout = outputWaitEvent.WaitOne(timeoutMS); // Undo removal if compilation failed. if (!noTimeout || !lastBuildSuccessful) { Output.Instance.WriteLine("Could not remove #include: '{0}'", line.IncludeContent); document.Undo(); if (!noTimeout) { Output.Instance.ErrorMsg("Compilation of {0} timeouted!", document.Name); break; } } else { Output.Instance.WriteLine("Successfully removed #include: '{0}'", line.IncludeContent); ++numRemovedIncludes; } } } catch (Exception ex) { Output.Instance.WriteLine("Unexpected error: {0}", ex); } finally { Application.Current.Dispatcher.Invoke(() => OnTrialAndErrorRemovalDone(progressDialog, document, numRemovedIncludes, canceled)); } }
/// <summary> /// Menu callback event handler that activates the merge pane after selecting work items in Work Item Query view. /// See <see cref="MergeWIControl"/> /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void MyWIExpMergeIDCallback(object sender, EventArgs e) { var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; IVsThreadedWaitDialog2 dlg = null; int icanceled; try { if (Utilities.paneMerge == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Pane was null.", Utilities.AppTitle); return; } var mfrm = Utilities.paneMerge.control; mfrm.SuppressEvents = true; mfrm.defServerName = "$/" + Utilities.vsTeamCtxMan.CurrentContext.TeamProjectName; mfrm.Initialize(); mfrm.ClearGrids(); IVsWindowFrame frame = Utilities.paneMerge.Frame as IVsWindowFrame; if (frame == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Frame was null.", Utilities.AppTitle); return; } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); int idx = 0; int iddx = 0; bool nolinks = true; bool bcanceled = false; object _lockToken1 = new object(); object _lockToken2 = new object(); string sourcePath; dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changesets...", "status", 100); dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled); IWorkItemTrackingDocument doc2 = Utilities.docsrv2.FindDocument(Utilities.dte.ActiveDocument.FullName, _lockToken2); if (doc2 == null) { Cursor.Current = origCursor; return; } foreach (int i in (doc2 as IResultsDocument).SelectedItemIds) { IWorkItemDocument widoc = Utilities.docsrv2.GetWorkItem(Utilities.tfscoll, i, _lockToken1); if (widoc == null) { continue; } if (!widoc.IsLoaded) { widoc.Load(); } iddx = 0; while (!widoc.IsLoaded && ++iddx < 10) { Thread.Sleep(1000); if (widoc.ItemState == WorkItemState.Error) { Utilities.OutputCommandString(widoc.Exception != null ? widoc.Exception.ToString() : "WorkItem cannot be loaded " + i); iddx = i; break; } } if (iddx == 10) { Utilities.OutputCommandString("WorkItem cannot be loaded " + i + ". Please open it manually and then try to load again."); iddx = i; break; } iddx = 0; foreach (Link lnk in widoc.Item.Links.Cast <Link>().Where(x => x.ArtifactLinkType.Name == "Fixed in Changeset")) { Changeset ch = Utilities.vcsrv.ArtifactProvider.GetChangeset(new Uri((lnk as ExternalLink).LinkedArtifactUri)); if (ch.Changes == null || ch.Changes.Length == 0) { continue; } string change = ch.Changes.Take(5).Select(x => x.ChangeType.ToString()).Aggregate((x, y) => x + "," + y); if (ch.Changes.Length > 5) { change += "..."; } string[] relbranches = MergeFactory.QueryBranchObjectOwnership(ch.ChangesetId); if (relbranches.Length == 0) { sourcePath = "$/" + Utilities.vsTeamCtxMan.CurrentContext.TeamProjectName; } else { sourcePath = relbranches[0]; } //} ListViewItem itm = mfrm.AddNewGridItem(widoc.Item.Id.ToString(), ch.ChangesetId.ToString(), ch.CreationDate.ToShortDateString(), ch.Owner, sourcePath, change, ch.Comment, new ListViewItemTag(ch.ChangesetId, widoc.Item.Id, sourcePath, ch.CreationDate)); Utilities.OutputCommandString("Adding Changeset: " + itm.Name + " => " + sourcePath); nolinks = false; dlg.UpdateProgress("Collecting information about changesets", "Processing changeset: " + ch.ChangesetId, "status", idx++, 100, false, out bcanceled); if (bcanceled) { widoc.Release(_lockToken1); doc2.Release(_lockToken2); mfrm.SortItems(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; return; } if (idx == 100) { idx = 0; } } widoc.Release(_lockToken1); } doc2.Release(_lockToken2); mfrm.SortItems(); mfrm.UpdateRelatedBranchesCombo(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); if (iddx > 0) { MessageBox.Show("WorkItem cannot be loaded " + iddx + ". Please open it manually and then try to load again.", Utilities.AppTitle); } else if (nolinks) { MessageBox.Show("No linked Changesets where found in selected Work Items.", Utilities.AppTitle); } } catch (Exception ex) { Cursor.Current = origCursor; if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } return; }