#pragma warning disable VSTHRD100 // Avoid async void methods - ok as an event handler private async void Execute(object sender, EventArgs e) #pragma warning restore VSTHRD100 // Avoid async void methods { System.Windows.Forms.Cursor previousCursor = System.Windows.Forms.Cursor.Current; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Logger?.RecordFeatureUsage(nameof(AnalyzeCurrentDocumentCommand)); var dte = await Instance.AsyncPackage.GetServiceAsync <DTE, DTE>(); var vs = new VisualStudioAbstraction(this.Logger, this.AsyncPackage, dte); var filePath = vs.GetActiveDocumentFilePath(); // Ensure that the open document has been saved so get latest version var rdt = new RunningDocumentTable(Package); rdt.SaveFileIfDirty(filePath); RapidXamlDocumentCache.Invalidate(filePath); RapidXamlDocumentCache.TryUpdate(filePath); } catch (Exception exc) { this.Logger?.RecordException(exc); } finally { System.Windows.Forms.Cursor.Current = previousCursor; } }
public async Task <ParserOutput> GetXamlAsync(IAsyncServiceProvider serviceProvider) { ParserOutput result = null; if (CodeParserBase.GetSettings().Profiles.Any()) { if (!(await serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE)) is DTE dte)) { SharedRapidXamlPackage.Logger?.RecordError(StringRes.Error_FailedToGetDteInGetXamlAsync); } else { var activeDocument = dte.ActiveDocument; var textView = await GetTextViewAsync(serviceProvider); var selection = textView.Selection; bool isSelection = selection.Start.Position != selection.End.Position; var caretPosition = textView.Caret.Position.BufferPosition; var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var semanticModel = await document.GetSemanticModelAsync(); var vs = new VisualStudioAbstraction(this.Logger, this.AsyncPackage, dte); var xamlIndent = await vs.GetXamlIndentAsync(); var proj = dte.Solution.GetProjectContainingFile(document.FilePath); if (proj == null) { // Default to the "active project" if file is not part of a known project proj = ((Array)dte.ActiveSolutionProjects).GetValue(0) as Project; } var projType = vs.GetProjectType(proj); this.Logger?.RecordInfo(StringRes.Info_DetectedProjectType.WithParams(projType.GetDescription())); IDocumentParser parser = null; if (activeDocument.Language == "CSharp") { parser = new CSharpParser(this.Logger, projType, xamlIndent); } else if (activeDocument.Language == "Basic") { parser = new VisualBasicParser(this.Logger, projType, xamlIndent); } result = isSelection ? parser?.GetSelectionOutput(await document.GetSyntaxRootAsync(), semanticModel, selection.Start.Position, selection.End.Position) : parser?.GetSingleItemOutput(await document.GetSyntaxRootAsync(), semanticModel, caretPosition.Position); } }
public async Task <AnalyzerOutput> GetXamlAsync(IAsyncServiceProvider serviceProvider) { AnalyzerOutput result = null; if (AnalyzerBase.GetSettings().Profiles.Any()) { var dte = await serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE; var activeDocument = dte.ActiveDocument; var textView = await GetTextViewAsync(serviceProvider); var selection = textView.Selection; bool isSelection = selection.Start.Position != selection.End.Position; var caretPosition = textView.Caret.Position.BufferPosition; var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var semanticModel = await document.GetSemanticModelAsync(); var vs = new VisualStudioAbstraction(this.Logger, this.ServiceProvider, dte); var xamlIndent = await vs.GetXamlIndentAsync(); IDocumentAnalyzer analyzer = null; if (activeDocument.Language == "CSharp") { analyzer = new CSharpAnalyzer(this.Logger); } else if (activeDocument.Language == "Basic") { analyzer = new VisualBasicAnalyzer(this.Logger); } result = isSelection ? analyzer?.GetSelectionOutput(await document.GetSyntaxRootAsync(), semanticModel, selection.Start.Position, selection.End.Position, xamlIndent) : analyzer?.GetSingleItemOutput(await document.GetSyntaxRootAsync(), semanticModel, caretPosition.Position, xamlIndent); } else { await ShowStatusBarMessageAsync(serviceProvider, StringRes.UI_NoXamlCopiedNoProfilesConfigured); } return(result); }
public async Task <ParserOutput> GetXamlAsync(IAsyncServiceProvider serviceProvider) { ParserOutput result = null; if (CodeParserBase.GetSettings().Profiles.Any()) { if (!(await serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE)) is DTE dte)) { RapidXamlPackage.Logger?.RecordError("Failed to get DTE in GetXamlFromCodeWindowBaseCommand.GetXamlAsync"); } else { var activeDocument = dte.ActiveDocument; var textView = await GetTextViewAsync(serviceProvider); var selection = textView.Selection; bool isSelection = selection.Start.Position != selection.End.Position; var caretPosition = textView.Caret.Position.BufferPosition; var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var semanticModel = await document.GetSemanticModelAsync(); var vs = new VisualStudioAbstraction(this.Logger, this.ServiceProvider, dte); var xamlIndent = await vs.GetXamlIndentAsync(); IDocumentParser parser = null; if (activeDocument.Language == "CSharp") { parser = new CSharpParser(this.Logger, xamlIndent); } else if (activeDocument.Language == "Basic") { parser = new VisualBasicParser(this.Logger, xamlIndent); } result = isSelection ? parser?.GetSelectionOutput(await document.GetSyntaxRootAsync(), semanticModel, selection.Start.Position, selection.End.Position) : parser?.GetSingleItemOutput(await document.GetSyntaxRootAsync(), semanticModel, caretPosition.Position); } }
private async void Execute(object sender, EventArgs e) { try { ThreadHelper.ThrowIfNotOnUIThread(); this.Logger?.RecordFeatureUsage(nameof(InsertGridRowDefinitionCommand)); var dte = await Instance.ServiceProvider.GetServiceAsync(typeof(DTE)) as DTE; var vs = new VisualStudioAbstraction(this.Logger, this.ServiceProvider, dte); var activeDocText = vs.GetActiveDocumentText(); if (activeDocText.IsValidXml()) { var logic = new InsertGridRowDefinitionCommandLogic(this.Logger, vs); var replacements = logic.GetReplacements(); var(start, end, exclusions) = logic.GetGridBoundary(); var(newDefinition, newDefPos) = logic.GetDefinitionAtCursor(); vs.StartSingleUndoOperation(StringRes.Info_UndoContextIndertRowDef); try { vs.ReplaceInActiveDoc(replacements, start, end, exclusions); vs.InsertIntoActiveDocumentOnNextLine(newDefinition, newDefPos); } finally { vs.EndSingleUndoOperation(); } } else { this.Logger.RecordInfo(StringRes.Info_UnableToInsertRowDefinitionInvalidXaml); } } catch (Exception exc) { this.Logger?.RecordException(exc); throw; } }
private async void Execute(object sender, EventArgs e) { try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Logger?.RecordFeatureUsage(nameof(SetDatacontextCommand)); var settings = CodeParserBase.GetSettings(); var profile = settings.GetActiveProfile(); if (!(await Instance.ServiceProvider.GetServiceAsync(typeof(DTE)) is DTE dte)) { RapidXamlPackage.Logger?.RecordError("Failed to get DTE in SetDatacontextCommand.Execute"); } else { var vs = new VisualStudioAbstraction(this.Logger, this.ServiceProvider, dte); var logic = new SetDataContextCommandLogic(profile, this.Logger, vs); var inXamlDoc = dte.ActiveDocument.Name.EndsWith(".xaml", StringComparison.InvariantCultureIgnoreCase); var(viewName, viewModelName, vmNamespace) = logic.InferViewModelNameFromFileName(dte.ActiveDocument.Name); if (inXamlDoc) { if (profile.Datacontext.SetsXamlPageAttribute) { var(add, lineNo, content) = logic.GetPageAttributeToAdd(viewModelName, vmNamespace); if (add) { if (dte.ActiveDocument.Object("TextDocument") is TextDocument objectDoc) { objectDoc.Selection.GotoLine(lineNo); objectDoc.Selection.EndOfLine(); objectDoc.Selection.Insert(content); } } } if (profile.Datacontext.SetsAnyCodeBehindContent) { if (profile.Datacontext.SetsCodeBehindPageContent) { // TODO: ISSUE#22 - set the DC in the CB file (C# or VB) may be open and unsaved } if (profile.Datacontext.SetsCodeBehindConstructorContent) { // TODO: ISSUE#22 - set the DC in the CB file (C# or VB) may be open and unsaved } } } else { if (profile.Datacontext.SetsXamlPageAttribute) { // TODO: ISSUE#22 - set the DC in the XAML file (C# or VB) may be open and unsaved } if (profile.Datacontext.SetsAnyCodeBehindContent) { if (dte.ActiveDocument.Object("TextDocument") is TextDocument objectDoc) { var textView = await GetTextViewAsync(Instance.ServiceProvider); var caretPosition = textView.Caret.Position.BufferPosition; var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var documentTree = await document.GetSyntaxTreeAsync(); var documentRoot = documentTree.GetRoot(); var toAdd = logic.GetCodeBehindContentToAdd(viewName, viewModelName, vmNamespace, documentRoot); foreach (var(anything, lineNo, contentToAdd) in toAdd) { if (anything) { objectDoc.Selection.GotoLine(lineNo); objectDoc.Selection.EndOfLine(); objectDoc.Selection.Insert(contentToAdd); } } } } } this.SuppressAnyException(() => dte.FormatDocument(profile)); } }
#pragma warning disable VSTHRD100 // Avoid async void methods - Allowed as called from event handler. private async void Execute(object sender, EventArgs e) #pragma warning restore VSTHRD100 // Avoid async void methods { System.Windows.Forms.Cursor previousCursor = System.Windows.Forms.Cursor.Current; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Logger?.RecordFeatureUsage(nameof(MoveAllHardCodedStringsToResourceFileCommand)); var dte = await Instance.AsyncPackage.GetServiceAsync <DTE, DTE>(); var vs = new VisualStudioAbstraction(this.Logger, this.AsyncPackage, dte); var filePath = vs.GetActiveDocumentFilePath(); // Ensure that the open document has been saved or modifications may go wrong var rdt = new RunningDocumentTable(Package); rdt.SaveFileIfDirty(filePath); // Do this as don't have direct snapshot access and want any changes to be processed before making changes RapidXamlDocumentCache.TryUpdate(filePath); var tags = RapidXamlDocumentCache.ErrorListTags(filePath) .OfType <HardCodedStringTag>() .OrderByDescending(t => t.Span.Start); var referenceUids = new Dictionary <Guid, string>(); vs.StartSingleUndoOperation(StringRes.UI_UndoContextMoveStringsToResourceFile); try { foreach (var tag in tags) { if (!tag.UidExists && referenceUids.ContainsKey(tag.ElementGuid)) { tag.UidExists = true; tag.UidValue = referenceUids[tag.ElementGuid]; } // pass in vs so have the same reference for tracking undo actions var action = new HardCodedStringAction(filePath, null, tag, vs); action.Execute(new CancellationTokenSource().Token); if (tag.UidExists == false && tag.ElementGuid != Guid.Empty && !referenceUids.ContainsKey(tag.ElementGuid)) { referenceUids.Add(tag.ElementGuid, tag.UidValue); } } } finally { vs.EndSingleUndoOperation(); } // Update again to force reflecting the changes that were just made. RapidXamlDocumentCache.TryUpdate(filePath); } catch (Exception exc) { this.Logger?.RecordException(exc); throw; } finally { System.Windows.Forms.Cursor.Current = previousCursor; } }