Exemplo n.º 1
0
        public void TestPreviewProjectChanges()
        {
            using (var previewWorkspace = new PreviewWorkspace())
            {
                var solution = previewWorkspace.CurrentSolution;
                var project  = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
                Assert.True(previewWorkspace.TryApplyChanges(project.Solution));

                var addedSolution = previewWorkspace.CurrentSolution.Projects.First()
                                    .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
                                    .AddDocument("document", "").Project.Solution;
                Assert.True(previewWorkspace.TryApplyChanges(addedSolution));
                Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
                Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);

                var text            = "class C {}";
                var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution;
                Assert.True(previewWorkspace.TryApplyChanges(changedSolution));
                Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text);

                var removedSolution = previewWorkspace.CurrentSolution.Projects.First()
                                      .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0])
                                      .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution;

                Assert.True(previewWorkspace.TryApplyChanges(removedSolution));
                Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
                Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
            }
        }
Exemplo n.º 2
0
        public void TestPreviewAddRemoveProject()
        {
            using var previewWorkspace = new PreviewWorkspace();
            var solution = previewWorkspace.CurrentSolution;
            var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
            Assert.True(previewWorkspace.TryApplyChanges(project.Solution));

            var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id);
            Assert.True(previewWorkspace.TryApplyChanges(newSolution));

            Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count);
        }
Exemplo n.º 3
0
        public void TestPreviewDiagnostic()
        {
            var diagnosticService = EditorServicesUtil.ExportProvider.GetExportedValue <IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;

            var taskSource = new TaskCompletionSource <DiagnosticsUpdatedArgs>();

            diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);

            using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider())))
            {
                var solution = previewWorkspace.CurrentSolution
                               .AddProject("project", "project.dll", LanguageNames.CSharp)
                               .AddDocument("document", "class { }")
                               .Project
                               .Solution;

                Assert.True(previewWorkspace.TryApplyChanges(solution));

                previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
                previewWorkspace.EnableDiagnostic();

                // wait 20 seconds
                taskSource.Task.Wait(20000);
                Assert.True(taskSource.Task.IsCompleted);

                var args = taskSource.Task.Result;
                Assert.True(args.Diagnostics.Length > 0);
            }
        }
Exemplo n.º 4
0
        public void TestPreviewDiagnostic()
        {
            var hostServices = EditorTestCompositions.EditorFeatures.GetHostServices();

            var diagnosticService = (IDiagnosticUpdateSource)((IMefHostExportProvider)hostServices).GetExportedValue <IDiagnosticAnalyzerService>();

            RoslynDebug.AssertNotNull(diagnosticService);

            var taskSource = new TaskCompletionSource <DiagnosticsUpdatedArgs>();

            diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);

            using var previewWorkspace = new PreviewWorkspace(hostServices);

            var solution = previewWorkspace.CurrentSolution
                           .WithAnalyzerReferences(new[] { DiagnosticExtensions.GetCompilerDiagnosticAnalyzerReference(LanguageNames.CSharp) })
                           .AddProject("project", "project.dll", LanguageNames.CSharp)
                           .AddDocument("document", "class { }")
                           .Project
                           .Solution;

            Assert.True(previewWorkspace.TryApplyChanges(solution));

            previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
            previewWorkspace.EnableDiagnostic();

            // wait 20 seconds
            taskSource.Task.Wait(20000);
            Assert.True(taskSource.Task.IsCompleted);

            var args = taskSource.Task.Result;

            Assert.True(args.Diagnostics.Length > 0);
        }
        public void UpdatePreview(string text)
        {
            const string start = "//[";
            const string end   = "//]";

            var service   = MefV1HostServices.Create(_componentModel.DefaultExportProvider);
            var workspace = new PreviewWorkspace(service);
            var fileName  = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj");
            var project   = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string[] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService>();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document  = project.AddDocument("document", SourceText.From(text, Encoding.UTF8));
            var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.GetTextAsync().Result.ToString(), _contentType);

            var container = textBuffer.AsTextContainer();
            var documentBackedByTextBuffer = document.WithText(container.CurrentText);

            var bufferText = textBuffer.CurrentSnapshot.GetText().ToString();
            var startIndex = bufferText.IndexOf(start, StringComparison.Ordinal);
            var endIndex   = bufferText.IndexOf(end, StringComparison.Ordinal);
            var startLine  = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(startIndex) + 1;
            var endLine    = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(endIndex);

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               "",
                                                                                               LineSpan.FromBounds(startLine, endLine));

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Analyzable));

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);

            workspace.TryApplyChanges(documentBackedByTextBuffer.Project.Solution);
            workspace.OpenDocument(document.Id);

            this.TextViewHost.Closed += (s, a) =>
            {
                workspace.Dispose();
                workspace = null;
            };
        }
        public void TestPreviewDiagnostic()
        {
            var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue <IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;

            var taskSource = new TaskCompletionSource <DiagnosticsUpdatedArgs>();

            diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);

            using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
            {
                var solution = previewWorkspace.CurrentSolution
                               .AddProject("project", "project.dll", LanguageNames.CSharp)
                               .AddDocument("document", "class { }")
                               .Project
                               .Solution;

                Assert.True(previewWorkspace.TryApplyChanges(solution));

                previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
                previewWorkspace.EnableDiagnostic();

                // wait 20 seconds
                taskSource.Task.Wait(20000);
                if (!taskSource.Task.IsCompleted)
                {
                    // something is wrong
                    FatalError.Report(new System.Exception("not finished after 20 seconds"));
                }

                var args = taskSource.Task.Result;
                Assert.True(args.Diagnostics.Length > 0);
            }
        }
Exemplo n.º 7
0
        public void TestPreviewWorkspaceDoesNotLeakSolution()
        {
            // Verify that analyzer execution doesn't leak solution instances from the preview workspace.

            var previewWorkspace = new PreviewWorkspace();

            Assert.NotNull(previewWorkspace.CurrentSolution);
            var project = previewWorkspace.CurrentSolution.AddProject(
                "project",
                "project.dll",
                LanguageNames.CSharp
                );

            Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
            var solutionObjectReference = ObjectReference.Create(previewWorkspace.CurrentSolution);

            var analyzers = ImmutableArray.Create <DiagnosticAnalyzer>(
                new CommonDiagnosticAnalyzers.NotConfigurableDiagnosticAnalyzer()
                );

            ExecuteAnalyzers(previewWorkspace, analyzers);

            previewWorkspace.Dispose();
            solutionObjectReference.AssertReleased();
        }
Exemplo n.º 8
0
        public void UpdatePreview(string text)
        {
            var service   = VisualStudioMefHostServices.Create(_componentModel.GetService <ExportProvider>());
            var workspace = new PreviewWorkspace(service);
            var fileName  = "project." + (Language == "C#" ? "csproj" : "vbproj");
            var project   = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string[] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService>();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document = project.AddDocument("document", SourceText.From(text, Encoding.UTF8));
            var fallbackFormattingOptions = _globalOptions.GetSyntaxFormattingOptions(document.Project.LanguageServices);
            var optionService             = workspace.Services.GetRequiredService <IOptionService>();
            var configOptions             = OptionStore.GetOptions().AsAnalyzerConfigOptions(optionService, document.Project.Language);
            var formattingService         = document.GetRequiredLanguageService <ISyntaxFormattingService>();
            var formattingOptions         = formattingService.GetFormattingOptions(configOptions, fallbackFormattingOptions);
            var formatted = Formatter.FormatAsync(document, formattingOptions, CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.GetTextSynchronously(CancellationToken.None).ToString(), _contentType);

            var container = textBuffer.AsTextContainer();

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               separator: "",
                                                                                               exposedLineSpans: GetExposedLineSpans(textBuffer.CurrentSnapshot).ToArray());

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Interactive));

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);

            workspace.TryApplyChanges(document.Project.Solution);
            workspace.OpenDocument(document.Id, container);

            this.TextViewHost.Closed += (s, a) =>
            {
                workspace.Dispose();
                workspace = null;
            };
        }
        public async void UpdatePreview(string text)
        {
            var workspace = new PreviewWorkspace(Ide.Composition.CompositionManager.Instance.HostServices);
            var fileName  = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj");

            project = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string [] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService> ();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document  = project.AddDocument("document.cs", SourceText.From(text, Encoding.UTF8));
            var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None);

            workspace.TryApplyChanges(project.Solution);

            TextViewHost.MimeType        = "text/x-csharp";
            TextViewHost.Text            = (await document.GetTextAsync()).ToString();
            TextViewHost.DocumentContext = new MyDocumentContext(workspace, document);

            TextViewHost.IsReadOnly = false;
            for (int i = 1; i <= TextViewHost.LineCount; i++)
            {
                var txt = TextViewHost.GetLineText(i);
                if (txt == "//[" || txt == "//]")
                {
                    var line = TextViewHost.GetLine(i);
                    TextViewHost.RemoveText(line.Offset, line.LengthIncludingDelimiter);
                    i--;
                }
            }
            TextViewHost.IsReadOnly = true;
            if (curWorkspace != null)
            {
                curWorkspace.Dispose();
            }

            this.curWorkspace = workspace;
        }
Exemplo n.º 10
0
        public void TestPreviewOpenCloseFile()
        {
            using var previewWorkspace = new PreviewWorkspace();
            var solution = previewWorkspace.CurrentSolution;
            var project  = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
            var document = project.AddDocument("document", "");

            Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution));

            previewWorkspace.OpenDocument(document.Id);
            Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count());
            Assert.True(previewWorkspace.IsDocumentOpen(document.Id));

            previewWorkspace.CloseDocument(document.Id);
            Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count());
            Assert.False(previewWorkspace.IsDocumentOpen(document.Id));
        }
Exemplo n.º 11
0
        public async Task TestPreviewDiagnosticTagger()
        {
            using var workspace = TestWorkspace.CreateCSharp("class { }", composition: EditorTestCompositions.EditorFeatures);
            using var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution);

            // preview workspace and owner of the solution now share solution and its underlying text buffer
            var hostDocument = workspace.Projects.First().Documents.First();

            previewWorkspace.TryApplyChanges(previewWorkspace.CurrentSolution.WithAnalyzerReferences(new[] { DiagnosticExtensions.GetCompilerDiagnosticAnalyzerReference(LanguageNames.CSharp) }));

            // enable preview diagnostics
            previewWorkspace.EnableDiagnostic();

            var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpansAsync<DiagnosticsSquiggleTaggerProvider>(workspace);
            const string AnalyzerCount = "Analyzer Count: ";
            Assert.Equal(AnalyzerCount + 1, AnalyzerCount + diagnosticsAndErrorsSpans.Item1.Length);

            const string SquigglesCount = "Squiggles Count: ";
            Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Length);
        }
Exemplo n.º 12
0
        public async Task TestPreviewDiagnostic()
        {
            var hostServices   = EditorTestCompositions.EditorFeatures.GetHostServices();
            var exportProvider = (IMefHostExportProvider)hostServices;

            var diagnosticService = (IDiagnosticUpdateSource)exportProvider.GetExportedValue <IDiagnosticAnalyzerService>();

            RoslynDebug.AssertNotNull(diagnosticService);
            var globalOptions = exportProvider.GetExportedValue <IGlobalOptionService>();

            var taskSource = new TaskCompletionSource <DiagnosticsUpdatedArgs>();

            diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);

            using var previewWorkspace = new PreviewWorkspace(hostServices);

            var solution = previewWorkspace.CurrentSolution
                           .WithAnalyzerReferences(new[] { DiagnosticExtensions.GetCompilerDiagnosticAnalyzerReference(LanguageNames.CSharp) })
                           .AddProject("project", "project.dll", LanguageNames.CSharp)
                           .AddDocument("document", "class { }")
                           .Project
                           .Solution;

            Assert.True(previewWorkspace.TryApplyChanges(solution));

            var document = previewWorkspace.CurrentSolution.Projects.First().Documents.Single();

            previewWorkspace.OpenDocument(document.Id, (await document.GetTextAsync()).Container);
            previewWorkspace.EnableSolutionCrawler();

            // wait 20 seconds
            taskSource.Task.Wait(20000);
            Assert.True(taskSource.Task.IsCompleted);

            var args = taskSource.Task.Result;

            Assert.True(args.GetPushDiagnostics(globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode).Length > 0);
        }