Exemplo n.º 1
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(
                services =>
            {
                // constant time in all integration testing
                services.Replace(
                    new ServiceDescriptor(
                        typeof(ITimeService),
                        typeof(TimeServiceMock),
                        ServiceLifetime.Transient
                        )
                    );
            }
                );

            builder.ConfigureServices(
                services =>
            {
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .BuildServiceProvider();

                services.AddDbContext <RepositoryContext>(
                    options =>
                {
                    options.UseInMemoryDatabase(TestDbName)
                    .ConfigureWarnings(
                        x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)
                        );
                    options.UseInternalServiceProvider(serviceProvider);
                }
                    );

                services.PostConfigure <JwtBearerOptions>(
                    JwtBearerDefaults.AuthenticationScheme,
                    options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        SignatureValidator       = (token, parameters) => new JwtSecurityToken(token),
                        ValidateIssuer           = false,
                        ValidateLifetime         = false,
                        ValidateIssuerSigningKey = false,
                        ValidateAudience         = false
                    };
                }
                    );

                using var scope = services.BuildServiceProvider().CreateScope();
                var appDb       = scope.ServiceProvider.GetRequiredService <RepositoryContext>();
                appDb.Database.EnsureDeleted();
                appDb.Database.EnsureCreated();

                try
                {
                    CommonSeeder.Seed(appDb);
                }
                catch (Exception ex)
                {
                    var logger = scope.ServiceProvider
                                 .GetRequiredService <ILogger <CustomWebApplicationFactoryWithInMemoryDb <TStartup> > >();
                    logger.LogError(
                        ex,
                        "An error occurred while seeding the database with messages. Error: {ex.Message}"
                        );
                }
            }
                );
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CommonSeeder seeder)
        {
            seeder.Configuration = this.Configuration;

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            ForceHttps(app);

            if (env.IsDevelopment() || true)
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // Security
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                CookieName            = "AU",
                CookieHttpOnly        = true,
                CookiePath            = "/",
                CookieSecure          = CookieSecurePolicy.SameAsRequest,
                AuthenticationScheme  = CookieAuthenticationDefaults.AuthenticationScheme,
                LoginPath             = new PathString($"/User/Login/"),
                AccessDeniedPath      = new PathString($"/User/Login/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                ExpireTimeSpan        = TimeSpan.FromHours(9),
                SlidingExpiration     = true
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller=Accounts}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "account",
                    template: "{accountNum:long}/{controller=home}/{action=index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Accounts}/{action=Index}/{id?}");
            });

            // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    // Create the Common database schema.
                    serviceScope.ServiceProvider
                    .GetService <CommonContext>()
                    .Database
                    .Migrate();

                    // Seed the data for the Common database.
                    seeder.SeedEverythingForCommon();

                    // Create the schema for the Account databases.
                    seeder.ApplyAccountMigrations();
                }
            }
            catch (Exception ex)
            {
                Log.ForContext <Startup>().Error(ex, $"An unhandled exception occurred while trying to migrate and seed databases");
                throw;
            }
        }