public RoutingTestFixture()
        {
            var builder = new GameHostBuilder()
                          .UseStartup(typeof(TStartup));

            _server = new TestServer(builder);

            Client             = _server.CreateClient();
            Client.BaseAddress = new Uri("http://localhost");
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            var host = new GameHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .UseStartup <Startup>()
                       .Build();

            host.Run();
        }
        public static IDisposable CreateServer(ILoggerFactory loggerFactory, out int port, Func <HttpContext, Task> app, Action <GameSocketOptions> configure = null)
        {
            configure = configure ?? (o => { });
            Action <IApplicationBuilder> startup = builder =>
            {
                builder.Use(async(ct, next) =>
                {
                    try
                    {
                        // Kestrel does not return proper error responses:
                        // https://github.com/aspnet/KestrelHttpServer/issues/43
                        await next();
                    }
                    catch (Exception ex)
                    {
                        if (ct.Response.HasStarted)
                        {
                            throw;
                        }

                        ct.Response.StatusCode = 500;
                        ct.Response.Headers.Clear();
                        await ct.Response.WriteAsync(ex.ToString());
                    }
                });
                builder.UseGameSockets();
                builder.Run(c => app(c));
            };

            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddInMemoryCollection();
            var config = configBuilder.Build();

            config["server.urls"] = $"http://127.0.0.1:0";

            var host = new GameHostBuilder()
                       .ConfigureServices(s =>
            {
                s.AddGameSockets(configure);
                s.AddSingleton(loggerFactory);
            })
                       .UseConfiguration(config)
                       .UseKestrel()
                       .Configure(startup)
                       .Build();

            host.Start();
            port = host.GetPort();

            return(host);
        }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="GameHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IGameHostBuilder"/>.</returns>
        public static IGameHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new GameHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(GameHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            }).
            UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            ConfigureGameDefaults(builder);

            return(builder);
        }
        public async Task UseRouter_MapGet_MatchesRequest(Action <IRouteBuilder> routeBuilder, ProtoRequestMessage request, string expected)
        {
            // Arrange
            var gamehostbuilder = new GameHostBuilder();

            gamehostbuilder
            .ConfigureServices(services => services.AddRouting())
            .Configure(app =>
            {
                app.UseRouter(routeBuilder);
            });
            var testServer = new TestServer(gamehostbuilder);
            var client     = testServer.CreateClient();

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.Equal(ProtoStatusCode.OK, response.StatusCode);
            var actual = await response.Content.ReadAsStringAsync();

            Assert.Equal(expected, actual);
        }
Exemple #6
0
        public static IGameHostBuilder GetGameHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddCommandLine(args)
                         .AddEnvironmentVariables(prefix: "RoutingBenchmarks_")
                         .Build();

            // Consoler logger has a major impact on perf results, so do not use
            // default builder.

            var gameHostBuilder = new GameHostBuilder()
                                  .UseConfiguration(config)
                                  .UseKestrel();

            var scenario = config["scenarios"]?.ToLower();

            if (scenario == "plaintextdispatcher" || scenario == "plaintextendpointrouting")
            {
                gameHostBuilder.UseStartup <StartupUsingEndpointRouting>();
                // for testing
                gameHostBuilder.UseSetting("Startup", nameof(StartupUsingEndpointRouting));
            }
            else if (scenario == "plaintextrouting" || scenario == "plaintextrouter")
            {
                gameHostBuilder.UseStartup <StartupUsingRouter>();
                // for testing
                gameHostBuilder.UseSetting("Startup", nameof(StartupUsingRouter));
            }
            else
            {
                throw new InvalidOperationException(
                          $"Invalid scenario '{scenario}'. Allowed scenarios are PlaintextEndpointRouting and PlaintextRouter");
            }

            return(gameHostBuilder);
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            var scenarioName = "Unknown";
            var config       = new ConfigurationBuilder()
                               .AddCommandLine(args)
                               .Build();

            var builder = new GameHostBuilder()
                          .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole())
                          .UseConfiguration(config)
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .UseIISIntegration()
                          .UseStartup <Startup>();

            if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
            {
                scenarioName = "HttpSysServer";
                Console.WriteLine("Using HttpSys server");
                builder.UseHttpSys();
            }
            else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
            {
                // ANCM is hosting the process.
                // The port will not yet be configured at this point, but will also not require HTTPS.
                scenarioName = "AspNetCoreModule";
                Console.WriteLine("Detected ANCM, using Kestrel");
                builder.UseKestrel();
            }
            else
            {
                // Also check "server.urls" for back-compat.
                var urls = builder.GetSetting(GameHostDefaults.ServerUrlsKey) ?? builder.GetSetting("server.urls");
                builder.UseSetting(GameHostDefaults.ServerUrlsKey, string.Empty);

                Console.WriteLine($"Using Kestrel, URL: {urls}");

                if (urls.Contains(";"))
                {
                    throw new NotSupportedException("This test app does not support multiple endpoints.");
                }

                var uri = new Uri(urls);

                builder.UseKestrel(options =>
                {
                    options.Listen(IPAddress.Loopback, uri.Port, listenOptions =>
                    {
                        if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                        {
                            scenarioName = "Kestrel(SSL)";
                            var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx");
                            Console.WriteLine($"Using SSL with certificate: {certPath}");
                            listenOptions.UseHttps(certPath, "testPassword");
                        }
                        else
                        {
                            scenarioName = "Kestrel(NonSSL)";
                        }
                    });
                });
            }

            var host = builder.Build();

            AppDomain.CurrentDomain.UnhandledException += (_, a) =>
            {
                Console.WriteLine($"Unhandled exception (Scenario: {scenarioName}): {a.ExceptionObject.ToString()}");
            };

            Console.WriteLine($"Starting Server for Scenario: {scenarioName}");
            host.Run();
        }