Пример #1
0
        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());
            }
        }
Пример #2
0
        // 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");
                }
            });
        }