public async Task Start()
        {
            var server = Server = await LanguageServer.From(_options);

            server.Exit.Subscribe(Observer.Create <int>(i => _cancellationTokenSource.Cancel()));

            WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost);

            var environment = _compositionHost.GetExport <IOmniSharpEnvironment>();
            var logger      = _compositionHost.GetExport <ILoggerFactory>().CreateLogger <LanguageServerHost>();

            logger.LogInformation($"Omnisharp server running using Lsp at location '{environment.TargetDirectory}' on host {environment.HostProcessId}.");

            Console.CancelKeyPress += (sender, e) =>
            {
                _cancellationTokenSource.Cancel();
                e.Cancel = true;
            };

            if (environment.HostProcessId != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(environment.HostProcessId);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => _cancellationTokenSource.Cancel());
                }
                catch
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    _cancellationTokenSource.Cancel();
                }
            }
        }
        public static OmniSharpTestHost Create(
            string path = null,
            ITestOutputHelper testOutput = null,
            IEnumerable <KeyValuePair <string, string> > configurationData = null,
            DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current,
            IEnumerable <ExportDescriptorProvider> additionalExports = null)
        {
            var environment      = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace);
            var loggerFactory    = new LoggerFactory().AddXunit(testOutput);
            var logger           = loggerFactory.CreateLogger <OmniSharpTestHost>();
            var sharedTextWriter = new TestSharedTextWriter(testOutput);

            var dotNetCliService = CreateTestDotNetCliService(dotNetCliVersion, loggerFactory);

            var info = dotNetCliService.GetInfo();

            logger.LogInformation($"Using .NET CLI: {info.Version}");

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);

            // We need to set the "UseLegacySdkResolver" for tests because
            // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs
            // that we install locally in the ".dotnet" and ".dotnet-legacy" directories.
            // This property will cause the MSBuild project loader to set the
            // MSBuildSDKsPath environment variable to the correct path "Sdks" folder
            // within the appropriate .NET Core SDK.
            var msbuildProperties = new Dictionary <string, string>()
            {
                [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true",
                [$"MSBuild:{nameof(MSBuildOptions.MSBuildSDKsPath)}"]      = Path.Combine(info.BasePath, "Sdks")
            };

            builder.AddInMemoryCollection(msbuildProperties);

            var configuration = builder.Build();

            var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration, NullEventEmitter.Instance, dotNetCliService);

            var compositionHost = new CompositionHostBuilder(serviceProvider, s_lazyAssemblies.Value, additionalExports)
                                  .Build();

            var workspace = compositionHost.GetExport <OmniSharpWorkspace>();

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger);

            var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
        public static OmniSharpTestHost Create(string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current)
        {
            var dotNetPath = Path.Combine(
                TestAssets.Instance.RootFolder,
                GetDotNetCliFolderName(dotNetCliVersion),
                "dotnet");

            if (!File.Exists(dotNetPath))
            {
                dotNetPath = Path.ChangeExtension(dotNetPath, ".exe");
            }

            if (!File.Exists(dotNetPath))
            {
                throw new InvalidOperationException($"Local .NET CLI path does not exist. Did you run build.(ps1|sh) from the command line?");
            }

            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);
            var configuration = builder.Build();

            var environment      = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace);
            var loggerFactory    = new LoggerFactory().AddXunit(testOutput);
            var sharedTextWriter = new TestSharedTextWriter(testOutput);

            var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration);

            var compositionHost = new CompositionHostBuilder(serviceProvider, environment, NullEventEmitter.Instance)
                                  .WithAssemblies(s_lazyAssemblies.Value)
                                  .Build();

            var workspace = compositionHost.GetExport <OmniSharpWorkspace>();
            var logger    = loggerFactory.CreateLogger <OmniSharpTestHost>();

            var dotNetCli = compositionHost.GetExport <DotNetCliService>();

            dotNetCli.SetDotNetPath(dotNetPath);
            var version = dotNetCli.GetVersion();

            logger.LogInformation($"Using .NET CLI: {version}");

            var oldMSBuildSdksPath = SetMSBuildSdksPath(dotNetCli);

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger);

            var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost, oldMSBuildSdksPath);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
示例#4
0
        public async Task Start()
        {
            _server.LogMessage(new LogMessageParams()
            {
                Message = "Starting server...",
                Type    = MessageType.Log
            });

            await _server.Initialize();

            _server.LogMessage(new LogMessageParams()
            {
                Message = "initialized...",
                Type    = MessageType.Log
            });

            var logger = _loggerFactory.CreateLogger(typeof(LanguageServerHost));

            WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost);

            // Kick on diagnostics
            var diagnosticHandler = _handlers.GetAll()
                                    .OfType <IRequestHandler <DiagnosticsRequest, DiagnosticsResponse> >();

            foreach (var handler in diagnosticHandler)
            {
                await handler.Handle(new DiagnosticsRequest());
            }

            logger.LogInformation($"Omnisharp server running using Lsp at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");

            Console.CancelKeyPress += (sender, e) =>
            {
                _cancellationTokenSource.Cancel();
                e.Cancel = true;
            };

            if (_environment.HostProcessId != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(_environment.HostProcessId);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => _cancellationTokenSource.Cancel());
                }
                catch
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    _cancellationTokenSource.Cancel();
                }
            }
        }
        public static OmniSharpTestHost Create(
            IServiceProvider serviceProvider,
            IEnumerable <ExportDescriptorProvider> additionalExports = null)
        {
            var compositionHost = new CompositionHostBuilder(serviceProvider, s_lazyAssemblies.Value, additionalExports)
                                  .Build();

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost);

            var host = new OmniSharpTestHost(serviceProvider, compositionHost);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
        public static OmniSharpTestHost Create(
            IServiceProvider serviceProvider,
            IEnumerable <ExportDescriptorProvider> additionalExports = null,
            [CallerMemberName] string callerName = "")
        {
            var environment     = serviceProvider.GetRequiredService <IOmniSharpEnvironment>();
            var compositionHost = new CompositionHostBuilder(serviceProvider, s_lazyAssemblies.Value, additionalExports)
                                  .Build(environment.TargetDirectory);

            WorkspaceInitializer.Initialize(serviceProvider, compositionHost);

            var host = new OmniSharpTestHost(serviceProvider, compositionHost, callerName);

            // Force workspace to be updated
            var service = host.GetWorkspaceInformationService();

            service.Handle(new WorkspaceInformationRequest()).Wait();

            return(host);
        }
示例#7
0
        public void Configure(
            IApplicationBuilder app,
            IServiceProvider serviceProvider,
            ILoggerFactory loggerFactory,
            HttpEnvironment httpEnvironment)
        {
            var workspace = _compositionHost.GetExport <OmniSharpWorkspace>();
            var logger    = loggerFactory.CreateLogger <Startup>();

            logger.LogInformation($"Starting OmniSharp on {Platform.Current}");

            app.UseRequestLogging();
            app.UseExceptionHandler("/error");
            app.UseMiddleware <EndpointMiddleware>(_compositionHost);
            app.UseMiddleware <StatusMiddleware>(workspace);
            app.UseMiddleware <StopServerMiddleware>();

            WorkspaceInitializer.Initialize(serviceProvider, _compositionHost);

            logger.LogInformation($"Omnisharp server running on port '{httpEnvironment.Port}' at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");
        }
示例#8
0
        public async Task Start()
        {
            var server = await LanguageServer.From(_options);

            server.Exit.Subscribe(Observer.Create <int>(i => _cancellationTokenSource.Cancel()));

            _eventEmitter.SetLanguageServer(server);

            server.Window.LogMessage(new LogMessageParams()
            {
                Message = "initialized...",
                Type    = MessageType.Log
            });

            WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost);

            _logger.LogInformation($"Omnisharp server running using Lsp at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");

            Console.CancelKeyPress += (sender, e) =>
            {
                _cancellationTokenSource.Cancel();
                e.Cancel = true;
            };

            if (_environment.HostProcessId != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(_environment.HostProcessId);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => _cancellationTokenSource.Cancel());
                }
                catch
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    _cancellationTokenSource.Cancel();
                }
            }
        }
示例#9
0
        public void Configure(
            IApplicationBuilder app,
            IServiceProvider serviceProvider,
            ILoggerFactory loggerFactory,
            IEventEmitter eventEmitter,
            ISharedTextWriter writer,
            HttpEnvironment httpEnvironment,
            IOptionsMonitor <OmniSharpOptions> options)
        {
            var workspace = _compositionHost.GetExport <OmniSharpWorkspace>();
            var logger    = loggerFactory.CreateLogger <Startup>();

            loggerFactory.AddConsole((category, level) =>
            {
                if (HostHelpers.LogFilter(category, level, _environment))
                {
                    return(true);
                }

                if (string.Equals(category, typeof(ExceptionHandlerMiddleware).FullName, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                return(false);
            });

            logger.LogInformation($"Starting OmniSharp on {Platform.Current}");

            app.UseRequestLogging();
            app.UseExceptionHandler("/error");
            app.UseMiddleware <EndpointMiddleware>(_compositionHost);
            app.UseMiddleware <StatusMiddleware>(workspace);
            app.UseMiddleware <StopServerMiddleware>();

            WorkspaceInitializer.Initialize(serviceProvider, _compositionHost, _configuration, logger);

            logger.LogInformation($"Omnisharp server running on port '{httpEnvironment.Port}' at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");
        }
示例#10
0
        public void Start()
        {
            WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost, _configuration, _logger);

            Task.Factory.StartNew(async() =>
            {
                _writer.WriteLine(new EventPacket()
                {
                    Event = "started"
                });

                while (!_cancellationTokenSource.IsCancellationRequested)
                {
                    var line = await _input.ReadLineAsync();
                    if (line == null)
                    {
                        break;
                    }

                    var ignored = Task.Factory.StartNew(async() =>
                    {
                        try
                        {
                            await HandleRequest(line, _logger);
                        }
                        catch (Exception e)
                        {
                            if (e is AggregateException aggregateEx)
                            {
                                e = aggregateEx.Flatten().InnerException;
                            }

                            _writer.WriteLine(new EventPacket()
                            {
                                Event = "error",
                                Body  = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default)
                            });
                        }
                    });
                }
            });

            _logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");

            Console.CancelKeyPress += (sender, e) =>
            {
                _cancellationTokenSource.Cancel();
                e.Cancel = true;
            };

            if (_environment.HostProcessId != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(_environment.HostProcessId);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => _cancellationTokenSource.Cancel());
                }
                catch
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    _cancellationTokenSource.Cancel();
                }
            }
        }