/// <summary>
        /// Seed database with initial data.
        /// </summary>
        /// <param name="serviceProvider">Service provider.</param>
        public static void Initialize(IServiceProvider serviceProvider)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", optional: false)
                                .Build();

            var initialDbSeedEnable = Convert.ToBoolean(configuration.GetSection("InitialDbSeedEnable").Value);

            if (!initialDbSeedEnable)
            {
                Log.Information(InitializationConstants.SeedDisabled);
                return;
            }

            try
            {
                Log.Information(InitializationConstants.SeedEnabled);

                var contextOptions = serviceProvider.GetRequiredService <DbContextOptions <ApplicationDbContext> >();

                using var applicationContext = new ApplicationDbContext(contextOptions);
                ApplicationDbContextSeeder.SeedAsync(applicationContext).GetAwaiter().GetResult();

                Log.Information(InitializationConstants.SeedSuccess);
            }
            catch (Exception ex)
            {
                Log.Error(ex, InitializationConstants.SeedError);
            }
        }
        public static ApplicationDbContext Create()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var operationalStoreOptions = Options.Create(
                new OperationalStoreOptions
            {
                DeviceFlowCodes =
                    new TableConfiguration("DeviceCodes"),
                PersistedGrants =
                    new TableConfiguration("PersistedGrants")
            });

            var currentUserServiceMock = new Mock <ICurrentUserService>();

            currentUserServiceMock.Setup(m => m.UserId)
            .Returns("00000000-0000-0000-0000-000000000000");

            var context = new ApplicationDbContext(
                options, operationalStoreOptions, currentUserServiceMock.Object);

            ApplicationDbContextSeeder.Seed(context);

            return(context);
        }
Exemple #3
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)
        {
            AutoMapperConfig.RegisterMappings(
                typeof(LoginViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                ApplicationDbContextSeeder.Seed(dbContext, app.ApplicationServices);
            }

            loggerFactory.AddConsole(this.configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public static ApplicationDbContext Create()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var operationalStoreOptions = Options.Create(
                new OperationalStoreOptions
            {
                DeviceFlowCodes =
                    new TableConfiguration("DeviceCodes"),
                PersistedGrants =
                    new TableConfiguration("PersistedGrants")
            });

            var currentUserServiceMock = new Mock <ICurrentUserService>();

            currentUserServiceMock.Setup(m => m.UserId)
            .Returns("00000000-0000-0000-0000-000000000000");

            var context = new ApplicationDbContext(
                options,
                operationalStoreOptions,
                currentUserServiceMock.Object);

            // NOTE: This centralised data will likely cause issues at some point, when someone changes the data to
            // suit the needs of another test.
            ApplicationDbContextSeeder.Seed(context);

            return(context);
        }
Exemple #5
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services
                                  .GetRequiredService <ApplicationDbContext>();

                    context.Database.Migrate();

                    ApplicationDbContextSeeder.Seed(context);
                }
                catch (Exception ex)
                {
                    var logger = services
                                 .GetRequiredService <ILogger <Program> >();

                    logger.LogError(ex, "An error occurred while " +
                                    "migrating or initializing the database.");

                    throw;
                }
            }

            host.Run();
        }
Exemple #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly,
                                              typeof(PostCreateModel).GetTypeInfo().Assembly
                                              );

            // Seed data on app launch
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var dbContext       = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                var dbContextSeeder = new ApplicationDbContextSeeder();
                dbContextSeeder.SeedAsync(dbContext, scope.ServiceProvider).GetAwaiter().GetResult();
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHub <ChatHub>("/chatHub");
                endpoints.MapHub <NotificationsHub>("/notificationsHub");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
        public async Task InvokeAsync(HttpContext httpContext, ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (!dbContext.Users.Any())
            {
                ApplicationDbContextSeeder.Seed(dbContext, serviceProvider);
            }

            await this.next(httpContext);
        }
        public static IApplicationBuilder Migrate(this IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <FootballizeDbContext>();
                dbContext.Database.Migrate();
                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            return(app);
        }
        // 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)
        {
            AutoMapperConfig.RegisterMappings(typeof(CategoryGetAllViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseExceptionHandler(application =>
                {
                    application.Run(async context =>
                    {
                        context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = GlobalConstants.JsonContentType;

                        var ex = context.Features.Get <IExceptionHandlerFeature>();
                        if (ex != null)
                        {
                            await context.Response
                            .WriteAsync(JsonConvert.SerializeObject(new { ex.Error?.Message, ex.Error?.StackTrace }))
                            .ConfigureAwait(continueOnCapturedContext: false);
                        }
                    });
                });
            }

            app.UseFileServer();

            app.UseJwtBearerTokens(
                app.ApplicationServices.GetRequiredService <IOptions <TokenProviderOptions> >(),
                PrincipalResolver);

            app.UseMvc(routes => routes.MapRoute("default", "api/{controller}/{action}/{id?}"));
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
Exemple #10
0
        public static IApplicationDbContext GetInMemoryContext()
        {
            var optionsbuilder = new DbContextOptionsBuilder <ApplicationDbContext>();

            optionsbuilder.UseInMemoryDatabase("TodosInMemory");

            var context = new ApplicationDbContext(optionsbuilder.Options, new MockedDateTimeProvider());
            var seeder  = new ApplicationDbContextSeeder(context);

            seeder.SeedAsync().Wait();

            return(context);
        }
Exemple #11
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)
        {
            AutoMapperConfig.RegisterMappings(typeof(LoginInputModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <UnravelTravelDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            loggerFactory.AddConsole(this.configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Configure Stripe ApiKeys
            StripeConfiguration.SetApiKey(this.configuration.GetSection("Stripe")["SecretKey"]);

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

            app.UseResponseCompression();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseSession();
            app.UseSetAdminMiddleware();
            app.UseSeedCountriesMiddleware();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();
                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    "areaRoute",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    "news",
                    "News/{id:int:min(1)}/{slug:required}",
                    new { controller = "News", action = "ById", });
                endpoints.MapControllerRoute(
                    "news",
                    "News/{id:int:min(1)}",
                    new { controller = "News", action = "ById", });
                endpoints.MapControllerRoute("default", "{controller=News}/{action=List}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemple #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            ScopeRead = Configuration["AzureAd:ScopeRead"];


            app.UseAuthentication();
            app.UseMvc();

            ApplicationDbContextSeeder.Initialize(app.ApplicationServices);
        }
Exemple #14
0
        private static void ConfigureServices(HostBuilderContext hostContext, IServiceCollection services)
        {
            var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false, true).AddEnvironmentVariables().Build();

            services.AddSingleton <IConfiguration>(configuration);

            var loggerFactory = new LoggerFactory();

            services.AddDbContext <ApplicationDbContext>(
                options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
                .UseLoggerFactory(loggerFactory));

            services.AddIdentity <ApplicationUser, ApplicationRole>(IdentityOptionsProvider.GetIdentityOptions)
            .AddEntityFrameworkStores <ApplicationDbContext>().AddUserStore <ApplicationUserStore>()
            .AddRoleStore <ApplicationRoleStore>().AddDefaultTokenProviders();

            // Identity stores
            services.AddTransient <IUserStore <ApplicationUser>, ApplicationUserStore>();
            services.AddTransient <IRoleStore <ApplicationRole>, ApplicationRoleStore>();

            // Seed data on application startup
            using (var serviceScope = services.BuildServiceProvider().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();
                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            // Data services
            services.AddScoped(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>));
            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddScoped <IDbQueryRunner, DbQueryRunner>();

            // Application services
            services.AddTransient <ISettingsService, SettingsService>();
            services.AddTransient <INewsService, NewsService>();
            services.AddTransient <IWorkerTasksDataService, WorkerTasksDataService>();

            // Register TaskRunnerHostedService
            services.AddTransient <ITasksAssemblyProvider, TasksAssemblyProvider>();
            var parallelTasksCount = int.Parse(configuration["TasksExecutor:ParallelTasksCount"]);

            for (var i = 0; i < parallelTasksCount; i++)
            {
                services.AddHostedService <TasksExecutor>();
            }
        }
        public static IApplicationBuilder UseDatabaseMigration(this IApplicationBuilder app, IHostingEnvironment env)
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            return(app);
        }
Exemple #16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();

                using (var serviceScope = app.ApplicationServices.CreateScope())
                {
                    var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                    dbContext.Database.Migrate();

                    ApplicationDbContextSeeder seeder = new ApplicationDbContextSeeder(serviceScope.ServiceProvider);
                    seeder.SeedDatabaseAsync().GetAwaiter().GetResult();
                }

                // Custom error handling only for development
                // app.UseMiddleware<GlobalExceptionMiddleware>();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area}/{controller}/{action=Index}/{id:int?}");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id:int?}");
                endpoints.MapRazorPages();
            });
        }
Exemple #17
0
        public static void Main(string[] args)
        {
            // CreateWebHostBuilder(args).Build().Run();
            var host = CreateWebHostBuilder(args);

            using (var scope = host.Services.CreateScope()){
                var services = scope.ServiceProvider;
                try {
                    ApplicationDbContextSeeder.Initialize(services);
                }
                catch (Exception ex) {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }
            host.Run();
        }
Exemple #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            AutoMapperConfig.RegisterMappings(typeof(ApplicationUser).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");

                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
Exemple #19
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)
        {
            //  AutoMapperConfig.RegisterMappings(typeof(LoginViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

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

            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseAuthentication();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "AllArticles",
                    template: "AllWords/Page{currentPage}/Order-{order}",
                    defaults: new { controller = "Words", action = "AllWords" });

                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #20
0
        public async Task SeederTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>().
                          UseSqlServer(TestDatabaseConnectionProvider.GetConnectionStringDisposable()).Options;

            var context = new ApplicationDbContext(options);

            context.Database.Migrate();

            var seeder = new ApplicationDbContextSeeder();

            var logMock = new Mock <ILogger>();

            var exception = await Record.ExceptionAsync(() => seeder.SeedAsync(context, logMock.Object));

            Assert.Null(exception);

            context.Database.EnsureDeleted();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext context, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCors("MyAllowOrigins");
            // app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            RoleManager <Role> roleManager = serviceProvider.GetRequiredService <RoleManager <Role> >();
            UserManager <User> userManager = serviceProvider.GetRequiredService <UserManager <User> >();

            ApplicationDbContextSeeder.SeedAsync(context, env, roleManager, userManager).Wait();
            app.UseSwagger(); //enable swagger
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "swagger"; //path naar de UI: /swagger/index.html
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "AircraftIdentity_DB v1");
                // c.SwaggerEndpoint("/swagger/v2/swagger.json", "Recipes_DB latest");
            });


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemple #22
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)
        {
            AutoMapperConfig.RegisterMappings(
                typeof(ErrorViewModel).GetTypeInfo().Assembly,
                typeof(ServiceModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public static async Task <IHost> MigrateAndSeedDatabase(this IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <ApplicationDbContext>();
                    context.Database.Migrate();
                    await ApplicationDbContextSeeder.Seed(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while migrating or seeding the database.");
                    throw ex;
                }
            }

            return(host);
        }
        public static ApplicationDbContext Create()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var operationalStoreOptions = Options.Create(
                new OperationalStoreOptions
            {
                DeviceFlowCodes =
                    new TableConfiguration("DeviceCodes"),
                PersistedGrants =
                    new TableConfiguration("PersistedGrants")
            });

            var context = new ApplicationDbContext(
                options, operationalStoreOptions);

            ApplicationDbContextSeeder.Seed(context);

            return(context);
        }
Exemple #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #26
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IRecurringJobManager recurringJobManager)
        {
            AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();
                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
                this.SeedHangfireJobs(recurringJobManager, dbContext);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles(
                new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    if (ctx.Context.Request.Path.ToString().Contains("/news/"))
                    {
                        // Cache static files for 90 days
                        ctx.Context.Response.Headers.Add("Cache-Control", "public,max-age=31536000");
                        ctx.Context.Response.Headers.Add(
                            "Expires",
                            DateTime.UtcNow.AddYears(1).ToString("R", CultureInfo.InvariantCulture));
                    }
                },
            });

            app.UseRouting();

            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();

            if (env.IsProduction())
            {
                app.UseHangfireServer(new BackgroundJobServerOptions {
                    WorkerCount = 2
                });
                app.UseHangfireDashboard(
                    "/hangfire",
                    new DashboardOptions {
                    Authorization = new[] { new HangfireAuthorizationFilter() }
                });
            }

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    "areaRoute",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    "news",
                    "News/{id:int:min(1)}/{slug:required}",
                    new { controller = "News", action = "ById", });
                endpoints.MapControllerRoute(
                    "news",
                    "News/{id:int:min(1)}",
                    new { controller = "News", action = "ById", });
                endpoints.MapControllerRoute("default", "{controller=News}/{action=List}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemple #27
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            AutoMapperConfig.RegisterMappings(typeof(UserLoginResponseModel).GetTypeInfo().Assembly);

            app.UseResponseCompression();

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBlazorDebugging();
            }
            else
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseExceptionHandler(
                alternativeApp =>
            {
                alternativeApp.Run(
                    async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.OK;
                    context.Response.ContentType = GlobalConstants.JsonContentType;
                    var exceptionHandlerFeature  = context.Features.Get <IExceptionHandlerFeature>();
                    if (exceptionHandlerFeature?.Error != null)
                    {
                        var ex = exceptionHandlerFeature.Error;
                        while (ex is AggregateException aggregateException &&
                               aggregateException.InnerExceptions.Any())
                        {
                            ex = aggregateException.InnerExceptions.First();
                        }

                        //// TODO: Log it

                        var exceptionMessage = ex.Message;
                        if (env.IsDevelopment())
                        {
                            exceptionMessage = ex.ToString();
                        }

                        await context.Response
                        .WriteAsync(JsonConvert.SerializeObject(new ApiResponse <object>(new ApiError("GLOBAL", exceptionMessage))))
                        .ConfigureAwait(continueOnCapturedContext: false);
                    }
                });
            });

            app.UseAuthorization();
            app.UseJwtBearerTokens(
                app.ApplicationServices.GetRequiredService <IOptions <TokenProviderOptions> >(),
                PrincipalResolver);

            app.UseClientSideBlazorFiles <Client.Startup>();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("api", "api/{controller}/{action}/{id?}");
                endpoints.MapFallbackToClientSideBlazor <Client.Startup>("index.html");
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            AutoMapperConfig.RegisterMappings(typeof(TodoItemViewModel).GetTypeInfo().Assembly);

            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }



            if (env.IsDevelopment())
            {
                app.UseExceptionHandler(application =>
                {
                    application.Run(async context =>
                    {
                        context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = GlobalConstants.JsonContentType;

                        var ex = context.Features.Get <IExceptionHandlerFeature>();
                        if (ex != null)
                        {
                            await context.Response
                            .WriteAsync(JsonConvert.SerializeObject(new { ex.Error?.Message, ex.Error?.StackTrace }))
                            .ConfigureAwait(continueOnCapturedContext: false);
                        }
                    });
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseJwtBearerTokens(
                app.ApplicationServices.GetRequiredService <IOptions <TokenProviderOptions> >(),
                PrincipalResolver);

            app.UseMvc(routes => routes.MapRoute("default", "api/{controller}/{action}/{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";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
Exemple #29
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)
        {
            AutoMapperConfig.RegisterMappings(typeof(LoginViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                }

                ApplicationDbContextSeeder.Seed(dbContext, serviceScope.ServiceProvider);
            }

            loggerFactory.AddConsole(this.configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDeveloperExceptionPage();

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

            // Initialise ReactJS.NET. Must be before static files.
            app.UseReact(config =>
            {
                // If you want to use server-side rendering of React components,
                // add all the necessary JavaScript files here. This includes
                // your components as well as all of their dependencies.
                // See http://reactjs.net/ for more information. Example:
                config
                .SetJsonSerializerSettings(new JsonSerializerSettings
                {
                    StringEscapeHandling = StringEscapeHandling.EscapeHtml,
                    ContractResolver     = new CamelCasePropertyNamesContractResolver()
                });

                // If you use an external build too (for example, Babel, Webpack,
                // Browserify or Gulp), you can improve performance by disabling
                // ReactJS.NET's version of Babel and loading the pre-transpiled
                // scripts. Example:
                //config
                //    .SetLoadBabel(false)
                //    .AddScriptWithoutTransform("~/Scripts/bundle.server.js");
            });

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseFileServer();

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

            // npm
            app.UseFileServer(new FileServerOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, "node_modules")
                    ),
                RequestPath             = "/node_modules",
                EnableDirectoryBrowsing = false
            });
        }
Exemple #30
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider services, ApplicationDbContextSeeder seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else if (env.IsProduction())
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHttpsRedirection();
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Cover}/{id?}");
            });

            // For first run you need to apply migrations (PM> Update-Database), also check connection string in appsettings.json
            seeder.Seed().Wait();
            seeder.CreateUserRoles(services).Wait();
        }