public async Task CanListActiveRegions() { var source = new[] { new Region { Name = "region1", Active = true }, new Region { Name = "region2", Active = true }, new Region { Name = "region3", Active = true }, new Region { Name = "region4", Active = true }, }; var repo = new SeederRepository(ctx); repo.AddOrUpdateRegions(source); var result = await di.GetRegionsAsync(); Assert.Equal(source.Count(c => c.Active), result.Count()); foreach (var item in result) { Assert.Contains(item.Name, source.Select(e => e.Name)); } }
public async Task CanListActiveCommunities() { var region = new Region { Name = "region1", Active = true }; var source = new[] { new Community { Name = "community1", RegionName = region.Name, Active = true }, new Community { Name = "community2", RegionName = region.Name, Active = true }, new Community { Name = "community3", RegionName = region.Name, Active = false }, new Community { Name = "community4", RegionName = region.Name, Active = true }, }; var repo = new SeederRepository(ctx); repo.AddOrUpdateRegions(new[] { region }); repo.AddOrUpdateCommunities(source); var result = await di.GetCommunitiesAsync(); Assert.Equal(source.Count(c => c.Active), result.Count()); foreach (var item in result) { Assert.Contains(new { name = item.Name, regionName = item.Region.Name }, source.Select(e => new { name = e.Name, regionName = e.RegionName })); } }
public async Task CanListActiveCountries() { var source = new[] { new Country { Name = "country1", CountryCode = "USA", Active = true }, new Country { Name = "country2", CountryCode = "CAN", Active = true }, new Country { Name = "country3", CountryCode = "IND", Active = false }, new Country { Name = "country4", CountryCode = "MEX", Active = true }, }; var repo = new SeederRepository(ctx); repo.AddOrUpdateCountries(source); var result = await di.GetCountriesAsync(); Assert.Equal(source.Count(c => c.Active), result.Count()); foreach (var item in result) { Assert.Contains(item.Id, source.Select(e => e.CountryCode)); } }
public async Task CanListActiveFamilyRelationshipTypes() { var source = new[] { new FamilyRelationshipType { Code = "FMR1", Active = true }, new FamilyRelationshipType { Code = "FMR2", Active = true }, new FamilyRelationshipType { Code = "FMR3", Active = false }, new FamilyRelationshipType { Code = "FMR4", Active = true }, }; var repo = new SeederRepository(ctx); repo.AddOrUpdateFamilyRelationshipTypes(source); var result = await di.GetFamilyRelationshipTypesAsync(); Assert.Equal(source.Count(c => c.Active), result.Count()); foreach (var item in result) { Assert.Contains(item.Code, source.Select(e => e.Code)); } }
private void SetupDatabase(IHostingEnvironment env, EmbcDbContext adminCtx) { log.LogInformation("Fetching the application's database context ..."); if (configuration.DbFullRefresh()) { log.LogWarning("DROPPING the database! ..."); adminCtx.Database.EnsureDeleted(); } log.LogInformation("Initializing the database ..."); if (configuration.HasDbAdminPassword()) { //For OpenShift deployments DatabaseTools.CreateDatabaseIfNotExists(DatabaseTools.GetSaConnectionString(configuration, "master"), configuration.GetDbName(), configuration.GetDbUser(), configuration.GetDbUserPassword()); } log.LogInformation("Syncing migrations prior to migrating..."); DatabaseTools.SyncInitialMigration(DatabaseTools.GetSaConnectionString(configuration)); log.LogInformation("Migrating the database ..."); adminCtx.Database.Migrate(); log.LogInformation("The database migration is complete."); try { // run the database seeders log.LogInformation("Adding/Updating seed data ..."); ISeederRepository seederRepository = new SeederRepository(adminCtx); var seedDataLoader = new SeedDataLoader(loggerFactory); var seeder = new EmbcSeeder(loggerFactory, seederRepository, env, seedDataLoader); seeder.SeedData(); log.LogInformation("Seeding operations are complete."); } catch (Exception e) { StringBuilder msg = new StringBuilder(); msg.AppendLine("The database setup failed!"); msg.AppendLine("The database may not be available and the application will not function as expected."); msg.AppendLine("Please ensure a database is available and the connection string is correct."); msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string."); msg.AppendLine("Error message is " + e.Message); log.LogCritical(new EventId(-1, "Database Seeding Failed"), e, msg.ToString()); } }
private void SeedData() { var db = Services.ServiceProvider.GetService <EmbcDbContext>(); if (!db.Database.IsInMemory()) { return; } var repo = new SeederRepository(db); var types = new[] { new FamilyRelationshipType { Code = "FMR1", Active = true }, new FamilyRelationshipType { Code = "FMR2", Active = true }, new FamilyRelationshipType { Code = "FMR3", Active = false }, new FamilyRelationshipType { Code = "FMR4", Active = true }, }; var regions = new[] { new Region { Name = "region1", Active = true }, new Region { Name = "region2", Active = true }, new Region { Name = "region3", Active = true }, new Region { Name = "region4", Active = true }, }; var countries = new[] { new Country { Name = "country1", CountryCode = "USA", Active = true }, new Country { Name = "country2", CountryCode = "CAN", Active = true }, new Country { Name = "country3", CountryCode = "IND", Active = false }, new Country { Name = "country4", CountryCode = "MEX", Active = true }, }; var communities = new[] { new Community { Name = "community1", RegionName = regions[0].Name, Active = true }, new Community { Name = "community2", RegionName = regions[0].Name, Active = true }, new Community { Name = "community3", RegionName = regions[0].Name, Active = false }, new Community { Name = "community4", RegionName = regions[0].Name, Active = true }, }; repo.AddOrUpdateFamilyRelationshipTypes(types); repo.AddOrUpdateCountries(countries); repo.AddOrUpdateRegions(regions); repo.AddOrUpdateCommunities(communities); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { var env = app.ApplicationServices.GetService <IHostingEnvironment>(); var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); var log = loggerFactory.CreateLogger <Startup>(); //Initialize the static AutoMapper Mapper.Initialize(cfg => cfg.AddMaps(typeof(Startup))); // DATABASE SETUP log.LogInformation("Fetching the application's database context ..."); var adminCtx = new EmbcDbContext(new DbContextOptionsBuilder <EmbcDbContext>() .UseLoggerFactory(loggerFactory) .UseSqlServer(DatabaseTools.GetSaConnectionString(Configuration)).Options); if (Configuration.DbFullRefresh()) { log.LogWarning("DROPPING the database! ..."); adminCtx.Database.EnsureDeleted(); } log.LogInformation("Initializing the database ..."); if (!string.IsNullOrEmpty(Configuration["DB_ADMIN_PASSWORD"])) { //For OpenShift deployments DatabaseTools.CreateDatabaseIfNotExists(DatabaseTools.GetSaConnectionString(Configuration, "master"), Configuration["DB_DATABASE"], Configuration["DB_USER"], Configuration["DB_PASSWORD"]); } //Check if the database exists var databaseExists = adminCtx.Database.CanConnect(); if (databaseExists) { log.LogInformation("Syncing migrations prior to migrating..."); DatabaseTools.SyncInitialMigration(DatabaseTools.GetSaConnectionString(Configuration)); } log.LogInformation("Migrating the database ..."); adminCtx.Database.Migrate(); log.LogInformation("The database migration is complete."); try { // run the database seeders log.LogInformation("Adding/Updating seed data ..."); ISeederRepository seederRepository = new SeederRepository(adminCtx); var seedDataLoader = new SeedDataLoader(loggerFactory); var seeder = new EmbcSeeder(loggerFactory, seederRepository, env, seedDataLoader); seeder.SeedData(); log.LogInformation("Seeding operations are complete."); } catch (Exception e) { StringBuilder msg = new StringBuilder(); msg.AppendLine("The database setup failed!"); msg.AppendLine("The database may not be available and the application will not function as expected."); msg.AppendLine("Please ensure a database is available and the connection string is correct."); msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string."); msg.AppendLine("Error message is " + e.Message); log.LogCritical(new EventId(-1, "Database Seeding Failed"), e, msg.ToString()); } string pathBase = Configuration["BASE_PATH"]; if (!string.IsNullOrEmpty(pathBase)) { app.UsePathBase(pathBase); } if (!env.IsProduction()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.Use(async(ctx, next) => { ctx.Response.Headers.Add("Content-Security-Policy", "script-src 'self' 'unsafe-eval' 'unsafe-inline' https://apis.google.com https://maxcdn.bootstrapcdn.com https://cdnjs.cloudflare.com https://code.jquery.com https://stackpath.bootstrapcdn.com https://fonts.googleapis.com"); ctx.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload"); await next(); }); app.UseXContentTypeOptions(); app.UseXfo(xfo => xfo.Deny()); StaticFileOptions staticFileOptions = new StaticFileOptions(); staticFileOptions.OnPrepareResponse = ctx => { ctx.Context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private"; ctx.Context.Response.Headers[HeaderNames.Pragma] = "no-cache"; ctx.Context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN"; ctx.Context.Response.Headers["X-XSS-Protection"] = "1; mode=block"; ctx.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; }; app.UseStaticFiles(staticFileOptions); app.UseSpaStaticFiles(staticFileOptions); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseNoCacheHttpHeaders(); // IMPORTANT: This session call MUST go before UseMvc() var sessionTimout = TimeSpan.FromMinutes(Configuration.ServerTimeoutInMinutes()); app.UseSession(new SessionOptions() { IdleTimeout = sessionTimout }); app.UseAuthentication(); // global policy - assign here or on each controller // IMPORTANT: Make sure UseCors() is called BEFORE UseMvc() app.UseCors("AllowAnyOrigin"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; // Only run the angular CLI Server in Development mode (not staging or test.) if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); }