Exemple #1
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.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Property API V1");
                c.RoutePrefix = string.Empty;
            });

            using var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope();

            var dbContext = serviceScope.ServiceProvider.GetService <SqlDbContext>();

            // Seed the Landlord table in the Db.
            DbSeeder.Seed(dbContext);
        }
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            var db = CreateContext();

            DbSeeder.Seed(db);
            db.Dispose();
        }
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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext   = serviceScope.ServiceProvider.GetRequiredService <DataDbContext>();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
        }
Exemple #4
0
 public TestFYCoreService()
 {
     svc = new FYCoreService();
     //ensures blank database before each test
     svc.Initialise();
     DbSeeder.Seed(svc);
 }
Exemple #5
0
        protected override TestServer CreateServer(IWebHostBuilder builder)
        {
            var server = base.CreateServer(builder);

            try
            {
                using (var serviceScope = server.Host.Services.CreateScope())
                {
                    var rng = new Random();

                    var seeder = new DbSeeder(serviceScope.ServiceProvider,
                                              new DbSeederOptions()
                    {
                        FakesOptions = new DbFakesOptions()
                        {
                            ModuleCount          = () => 30,
                            ReplacementPerModule = () => rng.Next(0, 2),
                            TagPerModule         = () => rng.Next(1, 2),
                            ReplacementsCount    = () => rng.Next(2, 3),
                        },
                    });
                    seeder.Seed().Wait();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred initializing the " +
                                    $"database with test messages. Error: {ex.Message}");
            }

            return(server);
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     DbSeeder.Seed();
 }
Exemple #7
0
        public static void Main(string[] args)
        {
            //var host = new WebHostBuilder()
            //    .UseKestrel()
            //    .UseContentRoot(Directory.GetCurrentDirectory())
            //    .ConfigureAppConfiguration((hostingContext, config) =>
            //    {
            //        var env = hostingContext.HostingEnvironment;
            //        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            //            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            //        config.AddEnvironmentVariables();
            //    })
            //    .ConfigureLogging((hostingContext, logging) =>
            //    {
            //        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            //        logging.AddConsole();
            //        logging.AddDebug();
            //    })
            //    .UseStartup<Startup>()
            //    .Build();
            var host = BuildWebHost(args);

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

                var context = services.GetService <PostsCommentsContext>();
                DbSeeder.Seed(context);
            }

            host.Run();
        }
Exemple #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();


            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Skillpoint V1");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();

            app.UseCors("CorsPolicy");

            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext   = serviceScope.ServiceProvider.GetService <DatabaseContext>();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <User> >();


                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ApplicationDbContext context, UserManager <ApplicationUser> userManager,
                              RoleManager <ApplicationRole> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

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

            app.UseAuthentication();

            DbSeeder.Seed(context, userManager, roleManager).Wait();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #10
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();
                app.UseCustomCodeExceptionsMiddleware();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

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

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

                dbContext.Database.EnsureCreated();
                dbContext.Database.Migrate();
                DbSeeder.Seed(dbContext);
            }
        }
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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    //Disable caching for all static files
                    context.Context.Response.Headers["Cache-Control"] =
                        Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"] =
                        Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"] =
                        Configuration["StaticFiles:Headers:Expires"];
                }
            }); //allows you to use static files like .html or .js files.
            app.UseSpaStaticFiles();

            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";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            //Create a service scope to get an ApplicationDbContext instance using DI
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                //create the Db if it doesn't exist and applies any pending migration.
                dbContext.Database.Migrate();

                //seed the Db
                DbSeeder.Seed(dbContext);
            }
        }
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

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

                try
                {
                    var dbContext =
                        services.GetService <ApplicationDbContext>();
                    var roleManager = services.GetService <RoleManager <IdentityRole> >();
                    var userManager = services.GetService <UserManager <UserModel> >();
                    dbContext.Database.Migrate();
                    // Wype³nij bazê danymi pocz¹tkowymi
                    DbSeeder.Seed(dbContext, roleManager, userManager);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
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, ApplicationDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

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

            DbSeeder.Seed(context);
        }
Exemple #14
0
        public async static Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

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

            try
            {
                var dbContext = services.GetRequiredService <ApplicationDbContext>();
                if (dbContext.Database.IsSqlite() || dbContext.Database.IsSqlServer())
                {
                    dbContext.Database.Migrate();
                    //seeding the initial users
                    DbSeeder.Seed(dbContext);
                }
            }
            catch (Exception ex)
            {
                var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >();

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

                throw;
            }

            await host.RunAsync();
        }
        public async Task <IActionResult> Get()
        {
            DbSeeder dbSeeder = new DbSeeder(_db);
            await dbSeeder.Seed();

            return(Ok());
        }
Exemple #16
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())
            {
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var ctx = scope.ServiceProvider.GetService <PetShopDbContext>();
                    DbSeeder.Seed(ctx);
                }

                app.UseDeveloperExceptionPage();
            }
            else
            {
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var ctx = scope.ServiceProvider.GetService <PetShopDbContext>();
                    DbSeeder.Seed(ctx);
                }
                app.UseDeveloperExceptionPage();
                app.UseHsts();
                app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            }
            app.UseHttpsRedirection();
            app.UseMvc();
        }
        public static void Main(string[] args)
        {
            /*
             * Obsolete code: replaced on 2017/12/06 (see Startup.cs file) with the code below
             * ref.: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#move-database-initialization-code
             */
            // BuildWebHost(args).Run();


            /* New working code */

            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetService <ApplicationDbContext>();

                var roleManager = scope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = scope.ServiceProvider.GetService <UserManager <ApplicationUser> >();

                // Create the Db if it doesn't exist and applies any pending migration.
                //dbContext.Database.Migrate();

                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
            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, AppDbContext db, ILoggerFactory loggerfactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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();
            }

            #region Создание БД, если она не создана, накат миграций, заполнение тестовыми данными

            db.Database.EnsureCreated();
            db.Database.Migrate();
            DbSeeder.Seed(db);

            #endregion

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=ToDo}/{action=Index}/{id?}");
            });
        }
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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

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

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

            DbSeeder.Seed(app);
        }
Exemple #20
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            DbSeeder.Seed(modelBuilder);

            modelBuilder.Entity <Person>().HasIndex(p => p.FirstName);
            modelBuilder.Entity <Person>().HasIndex(p => p.LastName);
        }
Exemple #21
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();
            }
            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();

            // UseCors must before UseMvc
            app.UseCors("AllowAll");
            // UseAuthentication() must before UseMvc
            app.UseAuthentication();

            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";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            // Load MapsterConfig
            MapsterSetting.Load();

            #region Seeder
            // Create a service scope to get an AppDbContext instance using DI
            using (var serviceScope =
                       app.ApplicationServices.GetRequiredService <IServiceScopeFactory> ().CreateScope()) {
                var dbContext   = serviceScope.ServiceProvider.GetService <AppDbContext> ();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> > ();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <IdentityUser> > ();

                // Create the Db if it doesn't exist and applies any pending migration
                dbContext.Database.Migrate();

                // Seed the Db
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
            #endregion
        }
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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseCors("MobilePolicy");
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseStatusCodePagesWithReExecute("/errors/{0}");
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My First API");
            });

            app.UseAuthentication();
            app.UseValidateTocken();
            app.UseSignalR(conf =>
            {
                conf.MapHub <SensorHub>("/real/sensors");
            });
            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";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });



            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext   = serviceScope.ServiceProvider.GetService <ApplicationDbConrext>();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();

                dbContext.Database.Migrate();

                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
        }
Exemple #23
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();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            // Add the AuthenticationMiddleware to the pipeline
            app.UseAuthentication();

            //Add for StackifyMiddleware (uncomment the next line -- to run Stackify Prefix)
            //app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();

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

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });

            //Create a service scope to get an ApplicationDbContext instance using DI
            using (var serviceScope =
                       app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();

                // Create the Db if it doesn't exist and applies any pending migration.
                dbContext.Database.Migrate();
                // Seed the Db.
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
        }
Exemple #24
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DbSeeder.Seed();
 }
Exemple #25
0
 public static void Seed(IHost host)
 {
     using (IServiceScope scope = host.Services.CreateScope())
     {
         DbSeeder seeder = scope.ServiceProvider.GetService <DbSeeder>();
         seeder.Seed();
     }
 }
 public async Task StartAsync(CancellationToken cancellationToken)
 {
     using var scope   = _services.CreateScope();
     using var context = scope.ServiceProvider.GetRequiredService <QuestionnaireContext>();
     {
         DbSeeder.Seed(context);
     }
 }
Exemple #27
0
        /// <summary>
        /// Migrates database
        /// </summary>
        private static void MigrateDb(IServiceProvider services, ILogger <Program> logger)
        {
            logger.LogInformation("Migrating DB");

            DbSeeder.Seed(services);

            logger.LogInformation("Finished migrating DB");
        }
        // 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();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Quiz Laboratory API");
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] =
                        Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"] =
                        Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"] =
                        Configuration["StaticFiles:Headers:Expires"];
                }
            });

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

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });

            // Create a service scope to get an ApplicationDbContext instance using DI
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                // Create the Db if it doesn't exist and applies any pending migrations
                dbContext.Database.Migrate();

                // Seed the Db.
                DbSeeder.Seed(dbContext);
            }
        }
Exemple #29
0
 private static void SeedDatabase(IHost host)
 {
     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         var context  = services.GetRequiredService <ExercisesDbContext>();
         DbSeeder.Seed(context, services);
     }
 }
Exemple #30
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();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

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

            //Add the authenticationMiddleware to the pipeline
            app.UseAuthentication();

            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";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            //Create a service scope to get an ApplicationDbContext instace using DI
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();
                //adding new variables that support user authentication.
                //creating the role manager and assigning it support type IdentityRole
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();

                //creating the user manager and assigning it support type ApplicationUser
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();

                //create the db if it doesn't exist and apply any pending migration
                dbContext.Database.Migrate();

                //seed the database
                DbSeeder.Seed(dbContext, roleManager, userManager);
            }
        }