示例#1
0
        public CompositionHost Build()
        {
            var options        = _serviceProvider.GetRequiredService <IOptionsMonitor <OmniSharpOptions> >();
            var memoryCache    = _serviceProvider.GetRequiredService <IMemoryCache>();
            var loggerFactory  = _serviceProvider.GetRequiredService <ILoggerFactory>();
            var assemblyLoader = _serviceProvider.GetRequiredService <IAssemblyLoader>();
            var config         = new ContainerConfiguration();

            var assemblies = _assemblies
                             .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                             .Distinct();

            config = config.WithAssemblies(assemblies);

            var fileSystemWatcher = new ManualFileSystemWatcher();
            var metadataHelper    = new MetadataHelper(assemblyLoader);

            config = config
                     .WithProvider(MefValueProvider.From(_serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(_environment))
                     .WithProvider(MefValueProvider.From(_writer))
                     .WithProvider(MefValueProvider.From(options.CurrentValue))
                     .WithProvider(MefValueProvider.From(options.CurrentValue.FormattingOptions))
                     .WithProvider(MefValueProvider.From(assemblyLoader))
                     .WithProvider(MefValueProvider.From(metadataHelper))
                     .WithProvider(MefValueProvider.From(_eventEmitter ?? NullEventEmitter.Instance));

            return(config.CreateContainer());
        }
示例#2
0
        public CompositionHost Build()
        {
            var options                = _serviceProvider.GetRequiredService <IOptionsMonitor <OmniSharpOptions> >();
            var memoryCache            = _serviceProvider.GetRequiredService <IMemoryCache>();
            var loggerFactory          = _serviceProvider.GetRequiredService <ILoggerFactory>();
            var assemblyLoader         = _serviceProvider.GetRequiredService <IAssemblyLoader>();
            var analyzerAssemblyLoader = _serviceProvider.GetRequiredService <IAnalyzerAssemblyLoader>();
            var environment            = _serviceProvider.GetRequiredService <IOmniSharpEnvironment>();
            var eventEmitter           = _serviceProvider.GetRequiredService <IEventEmitter>();
            var dotNetCliService       = _serviceProvider.GetRequiredService <IDotNetCliService>();
            var config = new ContainerConfiguration();

            var fileSystemWatcher = new ManualFileSystemWatcher();
            var metadataHelper    = new MetadataHelper(assemblyLoader);

            var logger = loggerFactory.CreateLogger <CompositionHostBuilder>();

            // We must register an MSBuild instance before composing MEF to ensure that
            // our AssemblyResolve event is hooked up first.
            var msbuildLocator = _serviceProvider.GetRequiredService <IMSBuildLocator>();

            // Don't register the default instance if an instance is already registered!
            // This is for tests, where the MSBuild instance may be registered early.
            if (msbuildLocator.RegisteredInstance == null)
            {
                msbuildLocator.RegisterDefaultInstance(logger);
            }

            config = config
                     .WithProvider(MefValueProvider.From(_serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemNotifier>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(environment))
                     .WithProvider(MefValueProvider.From(options.CurrentValue))
                     .WithProvider(MefValueProvider.From(options.CurrentValue.FormattingOptions))
                     .WithProvider(MefValueProvider.From(assemblyLoader))
                     .WithProvider(MefValueProvider.From(analyzerAssemblyLoader))
                     .WithProvider(MefValueProvider.From(dotNetCliService))
                     .WithProvider(MefValueProvider.From(metadataHelper))
                     .WithProvider(MefValueProvider.From(msbuildLocator))
                     .WithProvider(MefValueProvider.From(eventEmitter));

            foreach (var exportDescriptorProvider in _exportDescriptorProviders)
            {
                config = config.WithProvider(exportDescriptorProvider);
            }

            var parts = _assemblies
                        .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly, typeof(FileSystemHelper).GetTypeInfo().Assembly })
                        .Distinct()
                        .SelectMany(a => SafeGetTypes(a))
                        .ToArray();

            config = config.WithParts(parts);

            return(config.CreateContainer());
        }
        public void HandleAggregatableResponsesForSingleLanguage()
        {
            var request = new TestRequestPacket()
            {
                Seq       = 99,
                Command   = OmniSharpEndpoints.FindSymbols,
                Arguments = JsonConvert.SerializeObject(new FindSymbolsRequest {
                    Language = LanguageNames.CSharp
                })
            };

            var writer = new TestTextWriter(
                value =>
            {
                var packet = JsonConvert.DeserializeObject <EventPacket>(value);
                Assert.Equal("started", packet.Event);
            },
                value =>
            {
                var packet = JsonConvert.DeserializeObject <ResponsePacket>(value);
                Assert.Equal(request.Seq, packet.Request_seq);
                Assert.Equal(request.Command, packet.Command);
                Assert.True(packet.Success);
                Assert.True(packet.Running);
                Assert.Null(packet.Message);
                var quickFixResponse = ((JObject)packet.Body).ToObject <QuickFixResponse>();
                Assert.Equal(3, quickFixResponse.QuickFixes.Count());
                Assert.Equal("AAAFakeFindSymbolsService", quickFixResponse.QuickFixes.ElementAt(0).Text);
                Assert.Equal("BBBFakeFindSymbolsService", quickFixResponse.QuickFixes.ElementAt(1).Text);
                Assert.Equal("CCCFakeFindSymbolsService", quickFixResponse.QuickFixes.ElementAt(2).Text);
            }
                );

            var exports = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IRequestHandler>(
                    new BBBFakeFindSymbolsService(),
                    new Dictionary <string, object> {
                    ["EndpointName"] = OmniSharpEndpoints.FindSymbols, ["Language"] = LanguageNames.CSharp
                }),
                MefValueProvider.From <IRequestHandler>(
                    new CCCFakeFindSymbolsService(),
                    new Dictionary <string, object> {
                    ["EndpointName"] = OmniSharpEndpoints.FindSymbols, ["Language"] = LanguageNames.CSharp
                }),
                MefValueProvider.From <IRequestHandler>(
                    new AAAFakeFindSymbolsService(),
                    new Dictionary <string, object> {
                    ["EndpointName"] = OmniSharpEndpoints.FindSymbols, ["Language"] = LanguageNames.CSharp
                }),
            };

            using (StdioServerFacts.BuildTestServerAndStart(new StringReader(JsonConvert.SerializeObject(request) + "\r\n"), writer, additionalExports: exports))
            {
                Assert.True(writer.Completion.WaitOne(TimeSpan.FromSeconds(60)), "Timeout");
                Assert.Null(writer.Exception);
            }
        }
示例#4
0
            public ExportDescriptorProvider[] AsExportDescriptionProvider(ILoggerFactory loggerFactory)
            {
                var listener = new ProjectLoadListener(loggerFactory, this);

                return(new ExportDescriptorProvider[]
                {
                    MefValueProvider.From <IMSBuildEventSink>(listener)
                });
            }
示例#5
0
        public static CompositionHost ConfigureMef(IServiceProvider serviceProvider,
                                                   OmniSharpOptions options,
                                                   IEnumerable <Assembly> assemblies,
                                                   Func <ContainerConfiguration, ContainerConfiguration> configure = null)
        {
            var config = new ContainerConfiguration();

            assemblies = assemblies
                         .Concat(new[] { typeof(OmnisharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                         .Distinct();

            foreach (var assembly in assemblies)
            {
                config = config.WithAssembly(assembly);
            }

            var memoryCache         = serviceProvider.GetService <IMemoryCache>();
            var loggerFactory       = serviceProvider.GetService <ILoggerFactory>();
            var env                 = serviceProvider.GetService <IOmnisharpEnvironment>();
            var writer              = serviceProvider.GetService <ISharedTextWriter>();
            var applicationLifetime = serviceProvider.GetService <IApplicationLifetime>();
            var loader              = serviceProvider.GetService <IOmnisharpAssemblyLoader>();

            config = config
                     .WithProvider(MefValueProvider.From(serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(new ManualFileSystemWatcher()))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(env))
                     .WithProvider(MefValueProvider.From(writer))
                     .WithProvider(MefValueProvider.From(applicationLifetime))
                     .WithProvider(MefValueProvider.From(options))
                     .WithProvider(MefValueProvider.From(options.FormattingOptions))
                     .WithProvider(MefValueProvider.From(loader))
                     .WithProvider(MefValueProvider.From(new MetadataHelper(loader))); // other way to do singleton and autowire?

            if (env.TransportType == TransportType.Stdio)
            {
                config = config
                         .WithProvider(MefValueProvider.From <IEventEmitter>(new StdioEventEmitter(writer)));
            }
            else
            {
                config = config
                         .WithProvider(MefValueProvider.From <IEventEmitter>(new NullEventEmitter()));
            }

            if (configure != null)
            {
                config = configure(config);
            }

            var container = config.CreateContainer();

            return(container);
        }
        public void HandleNonAggregatableResponses()
        {
            var request = new TestRequestPacket()
            {
                Seq       = 99,
                Command   = OmniSharpEndpoints.GotoDefinition,
                Arguments = JsonConvert.SerializeObject(new GotoDefinitionRequest {
                    FileName = "foo.cs"
                })
            };

            var writer = new TestTextWriter(
                value =>
            {
                var packet = JsonConvert.DeserializeObject <EventPacket>(value);
                Assert.Equal("started", packet.Event);
            },
                value =>
            {
                var packet = JsonConvert.DeserializeObject <ResponsePacket>(value);
                Assert.Equal(request.Seq, packet.Request_seq);
                Assert.Equal(request.Command, packet.Command);
                Assert.True(packet.Success);
                Assert.True(packet.Running);
                Assert.Null(packet.Message);
                var gotoDefinitionResponse = ((JObject)packet.Body).ToObject <GotoDefinitionResponse>();
                Assert.Equal("ZZZFake.cs", gotoDefinitionResponse.FileName);
            }
                );

            var exports = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IProjectSystem>(new FakeProjectSystem()),
                MefValueProvider.From <IRequestHandler>(
                    new FakeGotoDefinitionService("ZZZFake", false),
                    new Dictionary <string, object> {
                    ["EndpointName"] = OmniSharpEndpoints.GotoDefinition, ["Language"] = LanguageNames.CSharp
                }),
                MefValueProvider.From <IRequestHandler>(
                    new FakeGotoDefinitionService("AAAFake", true),
                    new Dictionary <string, object> {
                    ["EndpointName"] = OmniSharpEndpoints.GotoDefinition, ["Language"] = LanguageNames.CSharp
                }),
            };

            using (StdioServerFacts.BuildTestServerAndStart(new StringReader(JsonConvert.SerializeObject(request) + "\r\n"), writer, additionalExports: exports))
            {
                Assert.True(writer.Completion.WaitOne(TimeSpan.FromSeconds(60)), "Timeout");
                Assert.Null(writer.Exception);
            }
        }
示例#7
0
        public static CompositionHost CreateCompositionHost(IServiceProvider serviceProvider, OmniSharpOptions options, IEnumerable <Assembly> assemblies)
        {
            var config = new ContainerConfiguration();

            assemblies = assemblies
                         .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                         .Distinct();

            foreach (var assembly in assemblies)
            {
                config = config.WithAssembly(assembly);
            }

            var memoryCache   = serviceProvider.GetService <IMemoryCache>();
            var loggerFactory = serviceProvider.GetService <ILoggerFactory>();
            var env           = serviceProvider.GetService <IOmniSharpEnvironment>();
            var writer        = serviceProvider.GetService <ISharedTextWriter>();
            var loader        = serviceProvider.GetService <IAssemblyLoader>();

            var fileSystemWatcher = new ManualFileSystemWatcher();
            var metadataHelper    = new MetadataHelper(loader);

            config = config
                     .WithProvider(MefValueProvider.From(serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(env))
                     .WithProvider(MefValueProvider.From(writer))
                     .WithProvider(MefValueProvider.From(options))
                     .WithProvider(MefValueProvider.From(options.FormattingOptions))
                     .WithProvider(MefValueProvider.From(loader))
                     .WithProvider(MefValueProvider.From(metadataHelper));

            if (env.TransportType == TransportType.Stdio)
            {
                config = config
                         .WithProvider(MefValueProvider.From <IEventEmitter>(new StdioEventEmitter(writer)));
            }
            else
            {
                config = config
                         .WithProvider(MefValueProvider.From(NullEventEmitter.Instance));
            }

            return(config.CreateContainer());
        }
        public CompositionHost Build()
        {
            var options        = _serviceProvider.GetRequiredService <IOptionsMonitor <OmniSharpOptions> >();
            var memoryCache    = _serviceProvider.GetRequiredService <IMemoryCache>();
            var loggerFactory  = _serviceProvider.GetRequiredService <ILoggerFactory>();
            var assemblyLoader = _serviceProvider.GetRequiredService <IAssemblyLoader>();
            var config         = new ContainerConfiguration();

            var fileSystemWatcher = new ManualFileSystemWatcher();
            var metadataHelper    = new MetadataHelper(assemblyLoader);

            var logger = loggerFactory.CreateLogger <CompositionHostBuilder>();

            // We must register an MSBuild instance before composing MEF to ensure that
            // our AssemblyResolve event is hooked up first.
            var msbuildLocator = _serviceProvider.GetRequiredService <IMSBuildLocator>();

            RegisterMSBuildInstance(msbuildLocator, logger);

            config = config
                     .WithProvider(MefValueProvider.From(_serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemNotifier>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(_environment))
                     .WithProvider(MefValueProvider.From(_writer))
                     .WithProvider(MefValueProvider.From(options.CurrentValue))
                     .WithProvider(MefValueProvider.From(options.CurrentValue.FormattingOptions))
                     .WithProvider(MefValueProvider.From(assemblyLoader))
                     .WithProvider(MefValueProvider.From(metadataHelper))
                     .WithProvider(MefValueProvider.From(msbuildLocator))
                     .WithProvider(MefValueProvider.From(_eventEmitter ?? NullEventEmitter.Instance));

            var parts = _assemblies
                        .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                        .Distinct()
                        .SelectMany(a => SafeGetTypes(a))
                        .ToArray();

            config = config.WithParts(parts);

            return(config.CreateContainer());
        }
        public async Task The_target_framework_is_emitted()
        {
            // Arrange
            var expectedTFM = "netcoreapp2.1";
            var messages    = new List <ProjectConfigurationMessage>();
            var emitter     = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    Assert.Single(messages);
                    Assert.Equal(messages[0].TargetFrameworks.First(), expectedTFM);
                }
        }
        public async Task The_hashed_references_of_the_source_files_are_emitted()
        {
            // Arrange
            var messages = new List <ProjectConfigurationMessage>();
            var emitter  = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    Assert.Single(messages);
                    Assert.Single(messages[0].FileExtensions);
                    Assert.Equal(messages[0].FileExtensions.First(), GetHashedFileExtension(".cs"));
                }
        }
        public async Task If_there_is_a_solution_file_the_project_guid_present_in_it_is_emitted()
        {
            // Arrange
            var messages = new List <ProjectConfigurationMessage>();
            var emitter  = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectAndSolution"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    var expectedGuid = "A4C2694D-AEB4-4CB1-8951-5290424EF883".ToLower();
                    Assert.Single(messages);
                    Assert.Equal(messages[0].ProjectId, expectedGuid);
                }
        }
        public async Task If_there_is_no_solution_file_the_hash_of_project_file_content_and_name_is_emitted()
        {
            // Arrange
            var messages = new List <ProjectConfigurationMessage>();
            var emitter  = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    var projectFileContent = File.ReadAllText(Directory.GetFiles(testProject.Directory, "*.csproj").Single());
                    var expectedGuid       = GetHashedReference($"Filename: HelloWorld.csproj\n{projectFileContent}");
                    Assert.Single(messages);
                    Assert.Equal(messages[0].ProjectId, expectedGuid);
                }
        }
示例#13
0
        public async Task TestPropertyProvider()
        {
            const string source           = @"
class ClassName
{
    void MethodName() { }
}
";
            var          propertyProvider = new NameLengthPropertyProvider();
            var          export           = MefValueProvider.From <ICodeElementPropertyProvider>(propertyProvider);

            using (var host = CreateOmniSharpHost(additionalExports: new[] { export }))
            {
                var response = await GetCodeStructureAsync(source, host);

                var elementC = Assert.Single(response.Elements);
                Assert.Contains(elementC.Properties, kvp => kvp.Key == "namelength" && (int)kvp.Value == 9);

                var elementM = Assert.Single(elementC.Children);
                Assert.Contains(elementM.Properties, kvp => kvp.Key == "namelength" && (int)kvp.Value == 10);
            }
        }
        public async Task If_there_are_multiple_target_frameworks_they_are_emitted()
        {
            // Arrange
            var messages = new List <ProjectConfigurationMessage>();
            var emitter  = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectWithMultiTFMLib/Lib"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    Assert.Single(messages);
                    var tfm = messages[0].TargetFrameworks.ToArray();
                    Assert.Equal(2, tfm.Count());
                    Assert.Equal("netstandard1.3", tfm[0]);
                    Assert.Equal("netstandard2.0", tfm[1]);
                }
        }
示例#15
0
        public async Task ProjectLoadedFires()
        {
            var allEventArgs = new List <ProjectLoadedEventArgs>();

            var eventSink = new FakeMSBuildEventSink(e =>
            {
                allEventArgs.Add(e);
            });

            var exports = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(eventSink)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectAndSolution"))
                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    var eventArgs = Assert.Single(allEventArgs);
                    Assert.Equal(
                        $"{testProject.Directory}/{testProject.Name}.csproj".EnsureForwardSlashes(),
                        eventArgs.ProjectInstance.FullPath.EnsureForwardSlashes());
                }
        }
        public async Task Given_a_restored_project_the_references_are_emitted()
        {
            var messages = new List <ProjectConfigurationMessage>();
            var emitter  = new ProjectLoadTestEventEmitter(messages);

            var listener = new ProjectLoadListener(LoggerFactory, emitter);
            var exports  = new ExportDescriptorProvider[]
            {
                MefValueProvider.From <IMSBuildEventSink>(listener)
            };

            using (var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"))
            {
                var dotnetCliService = new DotNetCliService(LoggerFactory, emitter);
                await dotnetCliService.RestoreAsync(testProject.Directory);

                using (var host = CreateMSBuildTestHost(testProject.Directory, exports))
                {
                    Assert.Single(messages);
                    Assert.NotEmpty(messages[0].References.Where(reference => reference == GetHashedReference("system.core")));
                }
            }
        }