public async Task InitializeAsync()
        {
            var services             = new ServiceCollection();
            var configurationBuilder = new ConfigurationBuilder();

            services.AddSingleton <IConfiguration>(configurationBuilder.AddJsonFile("appsettings.json").Build());

            var builder = new WebHostBuilder()
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json");
                config.AddEnvironmentVariables();
            });

            builder.ConfigureLogging((context, loggingBuilder) =>
            {
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });
            builder.UseStartup <TStartup>();

            LocalTestServer = new TestServer(builder);

            var client = LocalTestServer.CreateClient();

            services.AddScoped(p => RestService.For <IMeasureDistanceClient>(client));
            services.AddScoped(p => RestService.For <IMeasureDistanceResponse>(client));

            ServiceProvider = services.BuildServiceProvider(false);
            await Task.CompletedTask;
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

            _ = Task.Run(async() =>
            {
                var builder = new WebHostBuilder();

                builder.ConfigureServices(services =>
                {
                    var server = new OwinServer();
                    server.UseOwin(appFunc =>
                    {
                        _appFunc = appFunc;
                    });

                    services.AddSingleton <IServer>(server);
                    services.AddMvc();
                });

                builder.ConfigureLogging(logging =>
                {
                    logging.AddConsole();
                });

                _host = builder
                        .UseStartup <Startup>()
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .Build();

                await _host.RunAsync();
            });
        }
Exemple #3
0
        /// <summary>
        /// Starts the service using the default controller factory.
        /// </summary>
        /// <param name="port">The port where the server will listen.</param>
        private void StartServer <TStartup>(int port)
            where TStartup : class
        {
            Covenant.Requires <ArgumentException>(port == 0 || NetHelper.IsValidPort(port), nameof(port));

            var app = new WebHostBuilder()
                      .UseStartup <TStartup>()
                      .UseKestrel(
                options =>
            {
                options.Listen(IPAddress.Loopback, port);
            });

            if (logWriter != null && logLevel != LogLevel.None)
            {
                app.ConfigureLogging(
                    (hostingContext, logging) =>
                {
                    logging.AddProvider(new LoggingProvider(logWriter, logLevel));
                });
            }

            hostConfigurator?.Invoke(app);
            WebHost = app.Build();
            WebHost.Start();
        }
Exemple #4
0
        /// <summary>
        /// Build web host.
        /// </summary>
        /// <returns>web host.</returns>
        private static IWebHost BuildWebHost <T>(string[] args) where T : class
        {
            var baseRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            Directory.SetCurrentDirectory(baseRoot);

            if (IsServiceMode(args))
            {
                var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                baseRoot = Path.GetDirectoryName(exePath);
            }

            var config = new ConfigurationBuilder()
                         .SetBasePath(baseRoot)
                         .AddJsonFile("appsettings.json", optional: true)
                         .AddEnvironmentVariables()
                         .Build();

            var url = $"http://*:{config["ServicePort"]}";
            var env = config["ASPNETCORE_ENVIRONMENT"] ?? "Development";

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(config)
                         .CreateLogger();
            try
            {
                Log.Information("Application starting up. ");

                Console.WriteLine(baseRoot);

                var webHostBuilder = new WebHostBuilder()
                                     .UseKestrel()
                                     .UseUrls(url)
                                     .UseSerilog()
                                     .UseEnvironment(env)
                                     .UseContentRoot(baseRoot)
                                     .UseConfiguration(config);
                webHostBuilder.ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddSerilog(Log.Logger);
                    if (env.Equals("Development"))
                    {
                        logging.AddConsole();
                        logging.AddDebug();
                    }
                });

                return(webHostBuilder.UseStartup <T>().Build());
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
                return(null);
            }
            finally
            {
                ////Log.CloseAndFlush();
            }
        }
Exemple #5
0
        private static TestServer CreateResourceServer(Action <OpenIddictValidationBuilder> configuration = null)
        {
            var builder = new WebHostBuilder();

            builder.UseEnvironment("Testing");

            builder.ConfigureLogging(options => options.AddDebug());

            builder.ConfigureServices(services =>
            {
                services.AddAuthentication();
                services.AddOptions();
                services.AddDistributedMemoryCache();

                services.AddOpenIddict()
                .AddValidation(options => configuration?.Invoke(options));
            });

            builder.Configure(app =>
            {
                app.UseAuthentication();

                app.Run(context => context.ChallengeAsync(OpenIddictValidationDefaults.AuthenticationScheme));
            });

            return(new TestServer(builder));
        }
Exemple #6
0
        public void Initialize(string basePath = null, bool enableLogging = false)
        {
            var builder = new WebHostBuilder();

            builder.ConfigureServices(ConfigureServices);
            builder.Configure(app =>
            {
                if (basePath != null)
                {
                    app.Map(basePath, map =>
                    {
                        ConfigureApp(map);
                    });
                }
                else
                {
                    ConfigureApp(app);
                }
            });

            if (enableLogging)
            {
                builder.ConfigureLogging((ctx, b) => b.AddConsole());
            }

            Server  = new TestServer(builder);
            Handler = Server.CreateHandler();

            BrowserClient     = new BrowserClient(new BrowserHandler(Handler));
            BackChannelClient = new HttpClient(Handler);
        }
        public TestServer Build()
        {
            var configurationBuilder = new ConfigurationBuilder().AddInMemoryCollection(Configuration);
            var hostBuilder          = new WebHostBuilder()
                                       .UseConfiguration(configurationBuilder.Build())
                                       .UseStartup <Startup>();

            if (_helper != null)
            {
                hostBuilder.ConfigureLogging((builder) =>
                {
                    builder.AddProvider(new XunitLoggerProvider(_helper));
                    builder.SetMinimumLevel(_minimumLevel);
                });
            }

            var server = new TestServer(hostBuilder);

            //Ensure that the Database is created, we use the same feature like inside the Startup in case of Env.IsDevelopment (EF-Migrations)
            var scopeFactory = server.Host.Services.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                scope.ServiceProvider
                .GetRequiredService <IContext>()
                .Database
                .Migrate();
            }
            return(server);
        }
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder();

            host.UseKestrel();
            host.UseContentRoot(Directory.GetCurrentDirectory());

            host.ConfigureAppConfiguration((context, configuration) =>
            {
                var environment = context.HostingEnvironment;

                configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_shared.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_api.json", optional: true, reloadOnChange: true);
                configuration.AddEnvironmentVariables();
            });

            host.ConfigureLogging((context, logging) =>
            {
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            host.UseStartup <Startup>();
            host.Build().Run();
        }
        private static TestServer CreateAuthorizationServer(Action <OpenIddictServerBuilder> configuration = null)
        {
            var builder = new WebHostBuilder();

            builder.UseEnvironment("Testing");

            builder.ConfigureLogging(options => options.AddDebug());

            builder.ConfigureServices(services =>
            {
                services.AddAuthentication();
                services.AddOptions();
                services.AddDistributedMemoryCache();

                services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.SetDefaultApplicationEntity <OpenIddictApplication>()
                    .SetDefaultAuthorizationEntity <OpenIddictAuthorization>()
                    .SetDefaultScopeEntity <OpenIddictScope>()
                    .SetDefaultTokenEntity <OpenIddictToken>();
                })

                .AddServer(options => configuration?.Invoke(options));
            });

            builder.Configure(app =>
            {
                app.UseAuthentication();

                app.Run(context => context.ChallengeAsync(OpenIddictServerDefaults.AuthenticationScheme));
            });

            return(new TestServer(builder));
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            Mapper.RegisterConverter <Model.User, Database.Entities.User>(new UserConverter().ConvertToEntity);
            Mapper.RegisterConverter <Database.Entities.User, Model.User>(new UserConverter().ConvertToModel);

            var host = new WebHostBuilder();

            host.UseKestrel();
            host.UseContentRoot(System.IO.Directory.GetCurrentDirectory());

            host.ConfigureAppConfiguration((context, configuration) =>
            {
                var environment = context.HostingEnvironment;

                configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_shared.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_directory.json", optional: true, reloadOnChange: true);
                configuration.AddEnvironmentVariables();
            });

            host.ConfigureLogging((context, logging) =>
            {
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            host.UseStartup <Startup>();
            host.Build().Run();
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var builder = new WebHostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.UseKestrel((builderContext, options) =>
            {
                options.Listen(IPAddress.Any, 50500);
            });
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddEnvironmentVariables();
                if (env.IsDevelopment())
                {
                    config.AddUserSecrets <Program>();
                }
            });
            builder.ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
            });
            builder.UseStartup <Startup>();

            var host = builder.Build();

            host.Run();
        }
Exemple #12
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddCommandLine(args)
                         .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                         .Build();

            var builder = new WebHostBuilder()
                          .UseConfiguration(config)
                          .UseIISIntegration()
                          .UseStartup("MusicStore")
                          .UseDefaultServiceProvider((context, options) => {
                options.ValidateScopes = true;
            });

            var environment = builder.GetSetting("environment") ??
                              Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
            {
                if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
                {
                    // Set up NTLM authentication for WebListener like below.
                    // For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
                    // modify the applicationHost.config to enable NTLM.
                    builder.UseHttpSys(options =>
                    {
                        options.Authentication.Schemes        = AuthenticationSchemes.NTLM;
                        options.Authentication.AllowAnonymous = false;
                    });
                }
                else
                {
                    builder.UseHttpSys();
                }
            }
            else
            {
                builder.UseKestrel();
            }

            // In Proc
            builder.UseIIS();

            builder.ConfigureLogging(factory =>
            {
                factory.AddConsole();

                var logLevel = string.Equals(environment, "Development", StringComparison.Ordinal) ? LogLevel.Information : LogLevel.Warning;
                factory.SetMinimumLevel(logLevel);

                // Turn off Info logging for EF commands
                factory.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
            });

            var host = builder.Build();

            host.Run();
        }
Exemple #13
0
 public virtual void ConfigureLogging(Microsoft.Extensions.Logging.LogLevel logLevel)
 {
     WebHostBuilder.ConfigureLogging(logging =>
     {
         logging.ClearProviders();
         logging.SetMinimumLevel(logLevel);
     });
 }
Exemple #14
0
 private void ConfigureLogging()
 {
     _builder.ConfigureLogging((hostingContext, logging) =>
     {
         logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
         logging.AddConsole();
         logging.AddDebug();
     });
 }
        //private void CreateBasic(out )

        protected WebHostBuilder CreateDefaultWebHostBuilder()
        {
            var webHostBuilder = new WebHostBuilder();

            webHostBuilder.ConfigureLogging(lb => lb.AddXUnit(outputHelper).AddFilter("RTUITLab", LogLevel.Trace));
            webHostBuilder.Configure(app => app.UseWebAppConfigure());
            webHostBuilder.ConfigureServices(services => services.AddSingleton <TestValuesStorage>());
            return(webHostBuilder);
        }
Exemple #16
0
        public void ConfigureWebHostBuilder(ExecutionContext executionContext, WebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(ConfigureAppConfiguration);
            builder.ConfigureLogging(Logging);

            if (environment.IsDevelopment())
            {
                builder.UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "../../../../../src/DotNetDevOps.Web"));
            }
        }
Exemple #17
0
        public DefaultWebHostConfiguration ConfigureLogging()
        {
            _builder.ConfigureLogging((WebHostBuilderContext hostingContext, ILoggingBuilder logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            return(this);
        }
Exemple #18
0
        public static IWebHost BuildWebHost(string[] args)
        {
            IWebHostBuilder hostBuilder = new WebHostBuilder();

            CommandLineArgs commandLine = ReadCommandLine(args);

            // Load the config file to read some early startup settings
            // Namely, the logging config file path and everything in the Hosting section.
            // ASP.NET Core will read the same file again because the rest of the app's settings are there.
            IConfigurationBuilder bootstrapConfigBuilder = new ConfigurationBuilder()
                                                           .AddXmlFile(commandLine.ConfigFile);
            IConfigurationRoot bootstrapRawConfig = bootstrapConfigBuilder.Build();
            Config             bootstrapConfig    = bootstrapRawConfig.Get <Config>();

            if (!string.IsNullOrWhiteSpace(bootstrapConfig.LoggingConfigPath))
            {
                Logging.SetUpLogging(bootstrapConfig.LoggingConfigPath);
                hostBuilder.UseNLog();
            }
            else
            {
                Console.Error.WriteLine("No logging configuration file set. Logging to console.");
                Logging.SetUpConsoleLogging();
                hostBuilder.ConfigureLogging((hostingContext, logging) =>
                {
                    logging.SetMinimumLevel(LogLevel.Information);
                    logging.AddConsole();
                });
            }

            string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            hostBuilder
            .UseKestrel(options =>
            {
                if (bootstrapConfig.Hosting.UnixSocketPath != null)
                {
                    options.ListenUnixSocket(bootstrapConfig.Hosting.UnixSocketPath);
                }
                else
                {
                    options.Listen(IPAddress.Loopback, bootstrapConfig.Hosting.Port);
                }
            })
            .UseContentRoot(Environment.CurrentDirectory)
            .ConfigureAppConfiguration((context, configBuilder) =>
            {
                configBuilder.AddXmlFile(commandLine.ConfigFile, optional: false, reloadOnChange: true);
            })
            .UseStartup <Startup>();

            return(hostBuilder.Build());
        }
Exemple #19
0
        public static TestApplication BuildTestApplication <TStartup>(TestApplication testApp,
                                                                      string environmentName = "Production",
                                                                      Action <IWebHostBuilder> configureHost = null) where TStartup : class
        {
            testApp.LoggerProvider = new StubLoggerProvider();
            testApp.User           = new ClaimsPrincipal(new ClaimsIdentity());

            var hostBuilder = new WebHostBuilder();

            configureHost?.Invoke(hostBuilder);
            hostBuilder.ConfigureServices(services =>
            {
                services.AddTransient <HttpContextFactory>();
                services.AddTransient <IHttpContextFactory>((sp) =>
                {
                    var defaultContextFactory = sp.GetService <HttpContextFactory>();
                    var httpContextFactory    = new WrappedHttpContextFactory(defaultContextFactory);
                    httpContextFactory.ConfigureFeatureWithContext((features, httpCtx) =>
                    {
                        features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature {
                            User = testApp.User
                        });
                        features.Set <IServiceProvidersFeature>(new RequestServicesFeature(httpCtx,
                                                                                           testApp.ApplicationServices.GetService <IServiceScopeFactory>()));
                    });
                    return(httpContextFactory);
                });
            });
            var connectionStringEVKey = $"DOTNETCLUB_{ServiceExtensions.ConfigKeyConnectionString}";

            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(connectionStringEVKey)))
            {
                Environment.SetEnvironmentVariable(connectionStringEVKey, " ");
            }
            Environment.SetEnvironmentVariable("DOTNETCLUB_Logging:Console:LogLevel:Default", "Warning");

            Configuration.ConfigureHost(hostBuilder);
            hostBuilder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddProvider(testApp.LoggerProvider);
            });
            hostBuilder
            .UseContentRoot(TestEnv.WebProjectPath())
            .UseEnvironment(environmentName)
            .UseStartup <TStartup>();

            testApp.Server = new TestServer(hostBuilder);
            testApp.ApplicationServices = testApp.Server.Host.Services;
            testApp._spOverrider        = new ServiceProviderOverrider(testApp.ApplicationServices);

            return(testApp);
        }
        public async Task Response422IfUpdatingNotSettableAttribute()
        {
            // Arrange
            var builder = new WebHostBuilder().UseStartup <TestStartup>();

            var loggerFactory = new FakeLoggerFactory();

            builder.ConfigureLogging(options =>
            {
                options.AddProvider(loggerFactory);
                options.SetMinimumLevel(LogLevel.Trace);
                options.AddFilter((category, level) => level == LogLevel.Trace &&
                                  (category == typeof(JsonApiReader).FullName || category == typeof(JsonApiWriter).FullName));
            });

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var todoItem = _todoItemFaker.Generate();

            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var serializer = TestFixture <TestStartup> .GetSerializer <TodoItem>(server.Host.Services, ti => new { ti.CalculatedValue });

            var content = serializer.Serialize(todoItem);
            var request = PrepareRequest("PATCH", $"/api/v1/todoItems/{todoItem.Id}", content);

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

            // Assert
            Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var document = JsonConvert.DeserializeObject <ErrorDocument>(body);

            Assert.Single(document.Errors);

            var error = document.Errors.Single();

            Assert.Equal(HttpStatusCode.UnprocessableEntity, error.StatusCode);
            Assert.Equal("Failed to deserialize request body.", error.Title);
            Assert.StartsWith("Property 'TodoItem.CalculatedValue' is read-only. - Request body: <<", error.Detail);

            Assert.NotEmpty(loggerFactory.Logger.Messages);
            Assert.Contains(loggerFactory.Logger.Messages,
                            x => x.Text.StartsWith("Received request at ") && x.Text.Contains("with body:"));
            Assert.Contains(loggerFactory.Logger.Messages,
                            x => x.Text.StartsWith("Sending 422 response for request at ") && x.Text.Contains("Failed to deserialize request body."));
        }
        public void ConfigureWebHostBuilder(WebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(ConfigureAppConfiguration);
            builder.ConfigureLogging(Logging);

            if (hostingEnvironment.IsDevelopment())
            {
                builder.UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "../../.."));
            }
            // builder.UseContentRoot();
            //   builder.UseContentRoot(Directory.GetCurrentDirectory());
            // builder.UseContentRoot();
        }
        private static void ConfigureLogging(WebHostBuilder builder)
        {
            builder.ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
                logging.AddDebug();
                logging.AddApplicationInsights(azureAppConfig.Global.InstrumentationKey);
                logging.SetMinimumLevel(LogLevel.Debug);

                // The following configures LogLevel Information or above to be sent to Application Insights for all categories.
                logging.AddFilter <ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Information);
            });
        }
        public static TestApplication BuildTestApplication <TStartup>(TestApplication testApp,
                                                                      string environmentName = "Production",
                                                                      Action <IWebHostBuilder> configureHost = null) where TStartup : class
        {
            testApp.LoggerProvider = new StubLoggerProvider();
            testApp.User           = new ClaimsPrincipal(new ClaimsIdentity());

            var hostBuilder = new WebHostBuilder();

            configureHost?.Invoke(hostBuilder);
            hostBuilder.ConfigureServices(services =>
            {
                services.AddTransient <HttpContextFactory>();
                services.AddTransient <IHttpContextFactory>((sp) =>
                {
                    var defaultContextFactory = sp.GetService <HttpContextFactory>();
                    var httpContextFactory    = new WrappedHttpContextFactory(defaultContextFactory);
                    httpContextFactory.ConfigureFeatureWithContext((features, httpCtx) =>
                    {
                        features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature {
                            User = testApp.User
                        });
                        features.Set <IServiceProvidersFeature>(new RequestServicesFeature(httpCtx,
                                                                                           testApp.ApplicationServices.GetService <IServiceScopeFactory>()));
                    });
                    return(httpContextFactory);
                });
            });

            Environment.SetEnvironmentVariable("SGConnectionString", "Data Source=.;Initial Catalog=siegrain.blog;Integrated Security=True");

            WebHostConfiguration.Configure(hostBuilder);
            hostBuilder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddProvider(testApp.LoggerProvider);
            });
            hostBuilder
            .UseContentRoot(TestEnv.WebProjectPath())
            .UseEnvironment(environmentName)
            .UseStartup <TStartup>();

            testApp.Server = new TestServer(hostBuilder);
            testApp.ApplicationServices = testApp.Server.Host.Services;
            testApp._spOverrider        = new ServiceProviderOverrider(testApp.ApplicationServices);

            return(testApp);
        }
Exemple #24
0
    protected override void ConfigureBuilder(WebHostBuilder builder)
    {
        Events    = new List <SentryEvent>();
        Configure = options =>
        {
            options.BeforeSend = @event =>
            {
                Events.Add(@event);
                LastEvent = @event;
                return(@event);
            };
        };

        ConfigureApp = app =>
        {
#if NETCOREAPP3_1_OR_GREATER
            app.UseExceptionHandler(new ExceptionHandlerOptions
            {
#if NET6_0_OR_GREATER
                AllowStatusCode404Response = true,
#endif
                ExceptionHandlingPath = "/error"
            });
#endif
        };

        var sentry           = FakeSentryServer.CreateServer();
        var sentryHttpClient = sentry.CreateClient();
        _ = builder.UseSentry(options =>
        {
            options.Dsn = DsnSamples.ValidDsnWithSecret;
            options.SentryHttpClientFactory = new DelegateHttpClientFactory(_ => sentryHttpClient);

            Configure?.Invoke(options);
        });

        builder.ConfigureLogging(loggingBuilder =>
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry()
                         .CreateLogger();
            loggingBuilder.AddSerilog(logger);
        });

        AfterConfigureBuilder?.Invoke(builder);
    }
        public static TestApplication BuildApplication(TestApplication testApp, string environmentName = "Production", Action <IWebHostBuilder> configureHost = null)
        {
            testApp.LoggerProvider = new StubLoggerProvider();
            testApp.User           = new ClaimsPrincipal(new ClaimsIdentity());

            var hostBuilder = new WebHostBuilder();

            configureHost?.Invoke(hostBuilder);
            hostBuilder.ConfigureServices(services =>
            {
                services.AddTransient <HttpContextFactory>();
                services.AddTransient <IHttpContextFactory>((sp) =>
                {
                    var defaultContextFactory = sp.GetService <HttpContextFactory>();
                    var httpContextFactory    = new WrappedHttpContextFactory(defaultContextFactory);
                    httpContextFactory.ConfigureFeatureWithContext((features, httpCtx) =>
                    {
                        features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature {
                            User = testApp.User
                        });
                        features.Set <IServiceProvidersFeature>(new RequestServicesFeature(httpCtx, testApp.ServiceReplacer.CreateScopeFactory()));
                    });
                    return(httpContextFactory);
                });
            });

            Environment.SetEnvironmentVariable("DOTNETCLUB_sqliteConnectionString", " ");
            Environment.SetEnvironmentVariable("DOTNETCLUB_Logging:Console:LogLevel:Default", "Warning");
            Configurer.ConfigureHost(hostBuilder);

            hostBuilder.ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddProvider(testApp.LoggerProvider);
            });
            hostBuilder.UseContentRoot(WebProjectPath()).UseEnvironment(environmentName);

            testApp.Server = new TestServer(hostBuilder);
            testApp.ApplicationServices = testApp.Server.Host.Services;
            testApp.ServiceReplacer     = new ReplacableServiceProvider(testApp.ApplicationServices);

            return(testApp);
        }
Exemple #26
0
        public static HttpHandlerBuilder Start(int port, Action <ILoggingBuilder> loggingBuilder = null)
        {
            var handlerBuilder = new HttpHandlerBuilder();

            var webHostBuilder = new WebHostBuilder()
                                 .UseKestrel(k => k.Listen(IPAddress.Any, port))
                                 .Configure(app => Configure(app, handlerBuilder));

            if (loggingBuilder != null)
            {
                webHostBuilder.ConfigureLogging(loggingBuilder);
            }

            var webHost = webHostBuilder.Build();

            handlerBuilder.SetServer(webHost);
            webHost.Start();

            return(handlerBuilder);
        }
Exemple #27
0
        public IWebHost BuildHost()
        {
            // SAMPLE: what-the-cli-is-doing

            // The --log-level flag value overrides your application's
            // LogLevel
            if (LogLevelFlag.HasValue)
            {
                Console.WriteLine($"Overwriting the minimum log level to {LogLevelFlag.Value}");
                WebHostBuilder.ConfigureLogging(x => x.SetMinimumLevel(LogLevelFlag.Value));
            }

            if (VerboseFlag)
            {
                Console.WriteLine("Verbose flag is on.");

                // The --verbose flag adds console and
                // debug logging, as well as setting
                // the minimum logging level down to debug
                WebHostBuilder.ConfigureLogging(x =>
                {
                    x.SetMinimumLevel(LogLevel.Debug);
                });
            }

            // The --environment flag is used to set the environment
            // property on the IHostedEnvironment within your system
            if (EnvironmentFlag.IsNotEmpty())
            {
                Console.WriteLine($"Overwriting the environment to `{EnvironmentFlag}`");
                WebHostBuilder.UseEnvironment(EnvironmentFlag);
            }

            if (ConfigFlag.Any())
            {
                WebHostBuilder.ConfigureAppConfiguration(c => c.AddInMemoryCollection(ConfigFlag));
            }
            // ENDSAMPLE

            return(WebHostBuilder.Build());
        }
Exemple #28
0
        public TestServer Build()
        {
            Dictionary <string, string> testHostConfig = new Dictionary <string, string>();

            testHostConfig.Add("Database:Type", "Sqlite");
            string resolvedSqliteFile = Path.GetFullPath("..\\..\\baget.db");

            testHostConfig.Add("Database:ConnectionString", string.Format("Data Source={0}", resolvedSqliteFile));
            testHostConfig.Add("Storage:Type", "FileSystem");
            testHostConfig.Add("Mirror:EnableReadThroughCaching", false.ToString());

            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().AddInMemoryCollection(testHostConfig);
            IWebHostBuilder       hostBuilder          = new WebHostBuilder()
                                                         .UseConfiguration(configurationBuilder.Build())
                                                         .UseStartup <Startup>();

            if (_helper != null)
            {
                hostBuilder.ConfigureLogging((builder) =>
                {
                    builder.AddProvider(new XunitLoggerProvider(_helper));
                    builder.SetMinimumLevel(_minimumLevel);
                });
            }

            TestServer server = new TestServer(hostBuilder);

            //Ensure that the Database is created, we use the same feature like inside the Startup in case of Env.IsDevelopment (EF-Migrations)
            var scopeFactory = server.Host.Services.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                scope.ServiceProvider
                .GetRequiredService <IContext>()
                .Database
                .Migrate();
            }
            return(server);
        }
Exemple #29
0
        public IJasperHost BuildHost(StartMode mode)
        {
            // SAMPLE: what-the-cli-is-doing

            // The --log-level flag value overrides your application's
            // LogLevel
            if (LogLevelFlag.HasValue)
            {
                WebHostBuilder.ConfigureLogging(x => x.SetMinimumLevel(LogLevelFlag.Value));
            }

            if (VerboseFlag)
            {
                Console.WriteLine("Verbose flag is on.");

                // The --verbose flag adds console and
                // debug logging, as well as setting
                // the minimum logging level down to debug
                WebHostBuilder.ConfigureLogging(x =>
                {
                    x.SetMinimumLevel(LogLevel.Debug);

                    x.AddConsole();
                    x.AddDebug();
                });
            }

            // The --environment flag is used to set the environment
            // property on the IHostedEnvironment within your system
            if (EnvironmentFlag.IsNotEmpty())
            {
                WebHostBuilder.UseEnvironment(EnvironmentFlag);
            }
            // ENDSAMPLE

            return(mode == StartMode.Full ? WebHostBuilder.StartJasper() : new JasperRuntime(WebHostBuilder.Build()));
        }
        public IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var webHostBuilder = new WebHostBuilder();

            webHostBuilder.UseKestrel();
            webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", true, true).AddJsonFile(string.Format("appsettings.{0}.json", (object)hostingEnvironment.EnvironmentName), true, true);
                if (hostingEnvironment.IsDevelopment())
                {
                    Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    if (assembly != null)
                        config.AddUserSecrets(assembly, true);
                }
                config.AddEnvironmentVariables();
                if (args == null)
                    return;
                config.AddCommandLine(args);
            });
            webHostBuilder.ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            if (_withIisIntegration)
            {
                webHostBuilder.UseIISIntegration();
            }

            webHostBuilder.UseDefaultServiceProvider((context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment());

            return webHostBuilder;
        }