Example #1
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(VisualStudioMefHostServices.Create(EditorServicesUtil.ExportProvider));

            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);
        }
Example #2
0
        public RemoteLanguageServiceWorkspace(
            ExportProvider exportProvider,
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            IVsFolderWorkspaceService vsFolderWorkspaceService,
            SVsServiceProvider serviceProvider,
            IDiagnosticService diagnosticService,
            ITableManagerProvider tableManagerProvider,
            IGlobalOptionService globalOptions,
            IThreadingContext threadingContext)
            : base(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.CloudEnvironmentClientWorkspace)
        {
            _serviceProvider = serviceProvider;

            _remoteDiagnosticListTable = new RemoteDiagnosticListTable(serviceProvider, this, globalOptions, diagnosticService, tableManagerProvider);

            var runningDocumentTable = (IVsRunningDocumentTable)serviceProvider.GetService(typeof(SVsRunningDocumentTable));

            _runningDocumentTableEventTracker = new RunningDocumentTableEventTracker(threadingContext, editorAdaptersFactoryService, runningDocumentTable, this);
            _threadingContext = threadingContext;

            _vsFolderWorkspaceService = vsFolderWorkspaceService;

            _remoteWorkspaceRootPaths = ImmutableHashSet <string> .Empty;
            _registeredExternalPaths  = ImmutableHashSet <string> .Empty;
        }
Example #3
0
 private static HostServices GetHostServices(
     ExportProvider?exportProvider = null,
     TestComposition?composition   = null
     ) =>
 (exportProvider != null)
         ? VisualStudioMefHostServices.Create(exportProvider)
         : GetComposition(composition).GetHostServices();
        private static RemoteWorkspace CreatePrimaryWorkspace()
        {
            var catalog = CreateCatalog(RemoteHostAssemblies);
            var exportProviderFactory = CreateExportProviderFactory(catalog);
            var exportProvider        = exportProviderFactory.CreateExportProvider();

            return(new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace));
        }
Example #5
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;
            };
        }
Example #6
0
        internal void Test(
            Func <SyntaxGenerator, SyntaxNode> nodeCreator,
            string cs, string csSimple,
            string vb, string vbSimple)
        {
            Assert.True(cs != null || csSimple != null || vb != null || vbSimple != null,
                        $"At least one of {nameof(cs)}, {nameof(csSimple)}, {nameof(vb)}, {nameof(vbSimple)} must be provided");

            var hostServices = VisualStudioMefHostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic);
            var workspace    = new AdhocWorkspace(hostServices);

            if (cs != null || csSimple != null)
            {
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();

                if (cs != null)
                {
                    TokenUtilities.AssertTokensEqual(cs, node.ToFullString(), LanguageNames.CSharp);
                }

                if (csSimple != null)
                {
                    var simplifiedRootNode = Simplify(workspace, WrapExpressionInBoilerplate(node, codeDefFactory), LanguageNames.CSharp);
                    var expression         = simplifiedRootNode.DescendantNodes().OfType <EqualsValueClauseSyntax>().First().Value;

                    TokenUtilities.AssertTokensEqual(csSimple, expression.NormalizeWhitespace().ToFullString(), LanguageNames.CSharp);
                }
            }

            if (vb != null || vbSimple != null)
            {
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService <SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();

                if (vb != null)
                {
                    TokenUtilities.AssertTokensEqual(vb, node.ToFullString(), LanguageNames.VisualBasic);
                }

                if (vbSimple != null)
                {
                    var simplifiedRootNode = Simplify(workspace, WrapExpressionInBoilerplate(node, codeDefFactory), LanguageNames.VisualBasic);
                    var expression         = simplifiedRootNode.DescendantNodes().OfType <EqualsValueSyntax>().First().Value;

                    TokenUtilities.AssertTokensEqual(vbSimple, expression.NormalizeWhitespace().ToFullString(), LanguageNames.VisualBasic);
                }
            }
        }
Example #7
0
        public void TestPreviewServices()
        {
            using var previewWorkspace = new PreviewWorkspace(VisualStudioMefHostServices.Create(EditorServicesUtil.ExportProvider));
            var service = previewWorkspace.Services.GetService <ISolutionCrawlerRegistrationService>();

            Assert.True(service is PreviewSolutionCrawlerRegistrationServiceFactory.Service);

            var persistentService = previewWorkspace.Services.GetRequiredService <IPersistentStorageService>();

            using var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution);
            Assert.True(storage is NoOpPersistentStorage);
        }
Example #8
0
        public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true)
            : base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test)
        {
            this.TestHookPartialSolutionsDisabled = disablePartialSolutions;
            this.ExportProvider      = exportProvider;
            this.Projects            = new List <TestHostProject>();
            this.Documents           = new List <TestHostDocument>();
            this.AdditionalDocuments = new List <TestHostDocument>();
            this.ProjectionDocuments = new List <TestHostDocument>();

            this.CanApplyChangeDocument = true;

            _backgroundCompiler = new BackgroundCompiler(this);
            _backgroundParser   = new BackgroundParser(this);
            _backgroundParser.Start();

            _metadataAsSourceFileService = exportProvider.GetExportedValues <IMetadataAsSourceFileService>().FirstOrDefault();
        }
Example #9
0
        public TestWorkspace(ExportProvider exportProvider, string?workspaceKind = null, bool disablePartialSolutions = true, bool ignoreUnchangeableDocumentsWhenApplyingChanges = true)
            : base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test)
        {
            this.TestHookPartialSolutionsDisabled = disablePartialSolutions;
            this.ExportProvider          = exportProvider;
            this.Projects                = new List <TestHostProject>();
            this.Documents               = new List <TestHostDocument>();
            this.AdditionalDocuments     = new List <TestHostDocument>();
            this.AnalyzerConfigDocuments = new List <TestHostDocument>();
            this.ProjectionDocuments     = new List <TestHostDocument>();

            this.CanApplyChangeDocument = true;
            this.IgnoreUnchangeableDocumentsWhenApplyingChanges = ignoreUnchangeableDocumentsWhenApplyingChanges;

            if (Services.GetService <INotificationService>() is INotificationServiceCallback callback)
            {
                // Avoid showing dialogs in tests by default
                callback.NotificationCallback = (message, title, severity) =>
                {
                    var severityText = severity switch
                    {
                        NotificationSeverity.Information => "💡",
                        NotificationSeverity.Warning => "⚠",
                        _ => "❌"
                    };

                    var fullMessage = string.IsNullOrEmpty(title)
                        ? message
                        : $"{title}:{Environment.NewLine}{Environment.NewLine}{message}";

                    throw new InvalidOperationException($"{severityText} {fullMessage}");
                };
            }

            _backgroundCompiler = new BackgroundCompiler(this);
            _backgroundParser   = new BackgroundParser(this);
            _backgroundParser.Start();

            _metadataAsSourceFileService = exportProvider.GetExportedValues <IMetadataAsSourceFileService>().FirstOrDefault();

            RegisterDocumentOptionProviders(exportProvider.GetExports <IDocumentOptionsProviderFactory, OrderableMetadata>());
        }
Example #10
0
        public TestWorkspace(ExportProvider exportProvider, string?workspaceKind = null, bool disablePartialSolutions = true, bool ignoreUnchangeableDocumentsWhenApplyingChanges = true)
            : base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test)
        {
            this.TestHookPartialSolutionsDisabled = disablePartialSolutions;
            this.ExportProvider          = exportProvider;
            this.Projects                = new List <TestHostProject>();
            this.Documents               = new List <TestHostDocument>();
            this.AdditionalDocuments     = new List <TestHostDocument>();
            this.AnalyzerConfigDocuments = new List <TestHostDocument>();
            this.ProjectionDocuments     = new List <TestHostDocument>();

            this.CanApplyChangeDocument = true;
            this.IgnoreUnchangeableDocumentsWhenApplyingChanges = ignoreUnchangeableDocumentsWhenApplyingChanges;

            _backgroundCompiler = new BackgroundCompiler(this);
            _backgroundParser   = new BackgroundParser(this);
            _backgroundParser.Start();

            _metadataAsSourceFileService = exportProvider.GetExportedValues <IMetadataAsSourceFileService>().FirstOrDefault();

            RegisterDocumentOptionProviders(exportProvider.GetExports <IDocumentOptionsProviderFactory, OrderableMetadata>());
        }
        public RemoteLanguageServiceWorkspace(ExportProvider exportProvider,
                                              IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
                                              SVsServiceProvider serviceProvider,
                                              IDiagnosticService diagnosticService,
                                              ITableManagerProvider tableManagerProvider,
                                              IThreadingContext threadingContext)
            : base(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.AnyCodeRoslynWorkspace)

        {
            _serviceProvider = serviceProvider;

            _remoteDiagnosticListTable = new RemoteDiagnosticListTable(serviceProvider, this, diagnosticService, tableManagerProvider);

            var componentModel = _serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;

            Assumes.Present(componentModel);

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            var runningDocumentTable = (IVsRunningDocumentTable)serviceProvider.GetService(typeof(SVsRunningDocumentTable));

            _runningDocumentTableEventTracker = new RunningDocumentTableEventTracker(threadingContext, editorAdaptersFactoryService, runningDocumentTable, this);
            _threadingContext = threadingContext;
        }
 public ExportProviderMefHostServices(ExportProvider exportProvider)
     : base(new ContainerConfiguration().CreateContainer())
 {
     _vsHostServices = VisualStudioMefHostServices.Create(exportProvider);
 }
Example #13
0
 public HostServices GetHostServices()
 => VisualStudioMefHostServices.Create(ExportProviderFactory.CreateExportProvider());
Example #14
0
 public static HostServices CreateHostServices(ExportProvider exportProvider = null)
 {
     return(VisualStudioMefHostServices.Create(exportProvider ?? CreateMinimalExportProvider()));
 }