Exemplo n.º 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, StoreContextSeed seeder, UserManager <AppUser> userManager)
        {
            seeder.Seed();

            app.UseMiddleware <ExceptionMiddleware>();

            if (env.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }

            app.UseStatusCodePagesWithReExecute("/errors/{0}");

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseStaticFiles();

            app.UseCors(CorsPolicyName);

            app.UseAuthentication();

            IdentitySeeder.SeedData(userManager);

            app.UseAuthorization();


            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              IdentitySeeder identitySeeder
                              )
        {
            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.UseAuthentication();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

            identitySeeder.Seed().Wait();
        }
        protected override void Seed(MyResume.Data.ApplicationDbContext context)
        {
            IdentitySeeder.Seed(context);

            // Just in case i don't save in any of the seeders
            context.SaveChanges();
        }
Exemplo n.º 4
0
        private static void SeedDatabase(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();

                try
                {
                    //provide the instance of teh context class to data seeder
                    var aspnetRunContext = services.GetRequiredService <DotNetAppContext>();

                    //var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
                    //var userManager = services.GetRequiredService<UserManager<IdentityUser
                    var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                    var userManager = services.GetRequiredService <UserManager <IdentityUser> >();

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

                    IdentitySeeder.Seed(aspnetRunContext, roleManager, userManager);



                    //craete the admin and other users
                    //IdentitySeeder.Seed(aspnetRunContext, roleManager, userManager);
                    //DataSeeder.SeedAsync(aspnetRunContext, loggerFactory).Wait();
                }
                catch (Exception exception)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(exception, "An error occurred seeding the DB.");
                }
            }
        }
 public static void DeleteAndRecreateDatabase(this IApplicationBuilder app, IConfiguration configuration)
 {
     using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
     {
         var context     = serviceScope.ServiceProvider.GetRequiredService <SchoolMachineContext>();
         var roleManager = serviceScope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole <Guid> > >();
         var userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
         context.RebuildDbIfRequired(true);
         var identitySeeder = new IdentitySeeder(context, roleManager, userManager);
         var identityTask   = identitySeeder.Seed();
         identityTask.Wait();
     }
 }
Exemplo n.º 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)
        {
            using (var scopedService = app.ApplicationServices.CreateScope())
            {
                var dbContext = scopedService.ServiceProvider.GetService <KidsManagementDbContext>();

                if (env.IsDevelopment())
                {
                    dbContext.Database.Migrate();
                    var seeder = new IdentitySeeder(scopedService.ServiceProvider, dbContext); seeder.SeedAll().GetAwaiter().GetResult();
                }
            }


            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();
            }
            //var cultureInfo = new CultureInfo("bg-BG"); //fix this so that Monday is day1
            ////cultureInfo.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
            //CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            //CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            app.UseHttpsRedirection();
            app.UseStaticFiles(); //has todo with identity UI

            app.UseSession();
            app.UseRouting();

            app.UseAuthentication(); //IDENTITY
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceProvider"></param>
        public IdentityDatabase(IServiceProvider serviceProvider)
        {
            ConnectionString = serviceProvider.GetIdentityConnectionString();
            DatabaseFilePath = ConnectionString.Split(new[] { '=' })[1];
            DatabaseName     = DatabaseFilePath;
            _storage         = new IdentityStorage(ConnectionString, new SqliteOptions());

            if (!File.Exists(DatabaseFilePath))
            {
                _storage.CreateDatabase();
                var seeder = new IdentitySeeder();
                seeder.UsersSeed(_storage);
            }
        }
Exemplo n.º 8
0
        public static void BaseTestClassSetup(TestContext context)
        {
            IConfiguration Configuration = new ConfigurationBuilder().Build();

            try
            {
                string[] args           = new string[0];
                var      webHostBuilder = WebHost
                                          .CreateDefaultBuilder(args)
                                          .ConfigureAppConfiguration(
                    (context, config) =>
                    KeyVaultConnectionManager.ConfigureSchoolMachineConfiguration(config)
                    )
                                          .UseStartup <Startup>();
                var webHost     = webHostBuilder.Build();
                var roleManager = webHost.Services.GetRequiredService <RoleManager <IdentityRole <Guid> > >();
                var userManager = webHost.Services.GetRequiredService <UserManager <ApplicationUser> >();
                var builder     = new DbContextOptionsBuilder <SchoolMachineContext>();
                builder.UseInMemoryDatabase(databaseName: "SchoolMachine");
                var dbContextOptions = builder.Options;
                SchoolMachineContext = new SchoolMachineContext(dbContextOptions, Configuration);
                DataSeeder.Seed(SchoolMachineContext);
                var identitySeeder = new IdentitySeeder(SchoolMachineContext, roleManager, userManager);
                var identityTask   = identitySeeder.Seed();
                identityTask.Wait();

                // Test Assertions

                Assert.IsTrue(SchoolMachineContext.Districts.Count() >= DataSeeder.DistrictSeeder.Objects.Count()
                              , string.Format("Database has {0} SchoolDistricts and Seeder has {1}", SchoolMachineContext.Districts.Count(), DataSeeder.DistrictSeeder.Objects.Count()));

                Assert.IsTrue(SchoolMachineContext.Schools.Count() >= DataSeeder.SchoolSeeder.Objects.Count()
                              , string.Format("Database has {0} Schools and Seeder has {1}", SchoolMachineContext.Schools.Count(), DataSeeder.SchoolSeeder.Objects.Count()));

                Assert.IsTrue(SchoolMachineContext.Students.Count() >= DataSeeder.StudentSeeder.Objects.Count()
                              , string.Format("Database has {0} Students and Seeder has {1}", SchoolMachineContext.Students.Count(), DataSeeder.StudentSeeder.Objects.Count()));

                Assert.IsTrue(SchoolMachineContext.DistrictSchools.Count() >= DataSeeder.DistrictSchools.Count()
                              , string.Format("Database has {0} SchoolDistrictSchools and Seeder has {1}", SchoolMachineContext.DistrictSchools.Count(), DataSeeder.DistrictSchools.Count()));

                Assert.IsTrue(SchoolMachineContext.SchoolStudents.Count() >= DataSeeder.SchoolStudents.Count()
                              , string.Format("Database has {0} SchoolStudents and Seeder has {1}", SchoolMachineContext.SchoolStudents.Count(), DataSeeder.SchoolStudents.Count()));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception occurred during test class intialization: {0}", ex));
            }
        }
Exemplo n.º 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, ApplicationContext context, UserManager <User> userManager, RoleManager <Role> roleManager, IBackgroundJobClient backgroundJobs)
        {
            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.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();
            app.UseCors("quanganh9x");
            app.UseHangfireDashboard();

            /* seeders */
            Task.Run(async() =>
            {
                await IdentitySeeder.Seed(userManager, roleManager);
            }).Wait();
            Task.Run(async() =>
            {
                await DbSeeder.Seed(context);
            }).Wait();

            app.UseSignalR(route =>
            {
                route.MapHub <NotificationHub>("/notificationHub");
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 10
0
        public static IWebHost SeedSystemIdentity(this IWebHost host)
        {
            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider      services             = scope.ServiceProvider;
                UserManager <User>    userManager          = services.GetRequiredService <UserManager <User> >();
                RoleManager <Role>    roleManager          = services.GetRequiredService <RoleManager <Role> >();
                IPermissionRepository permissionRepository = services.GetRequiredService <IPermissionRepository>();
                IUserRepository       userRepository       = services.GetRequiredService <IUserRepository>();

                // TODO: обязательно в таком порядке
                IdentitySeeder identitySeeder = new IdentitySeeder(userManager, roleManager, userRepository);
                identitySeeder.SeedSystemRolesAsync().Wait();
                identitySeeder.SeedSystemUsersAsync().Wait();
                identitySeeder.SeedUserWorkgroupRoles().Wait();
                PermissionSeeder permissionSeeder = new PermissionSeeder(permissionRepository);
                permissionSeeder.SeedSystemPermissionsAsync().Wait();
            }

            return(host);
        }
Exemplo n.º 11
0
        private static void SeedDatabase(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();

                try
                {//here is main editing
                    var aspnetRunContext = services.GetRequiredService <RecruitmentPortalDbContext>();
                    var roleManager      = services.GetRequiredService <RoleManager <IdentityRole> >();
                    var userManager      = services.GetRequiredService <UserManager <ApplicationUser> >();

                    IdentitySeeder.Seed(aspnetRunContext, roleManager, userManager);
                }
                catch (Exception exception)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(exception, "An error occurred seeding the DB.");
                }
            }
        }
Exemplo n.º 12
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ViLabContext viLabContext, IdentitySeeder identitySeeder)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddNLog();
            loggerFactory.ConfigureNLog(Path.Combine(env.ContentRootPath, "nlog.config"));

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

            viLabContext.EnsureSeedDataForContext();

            app.UseStatusCodePages();

            AutoMapper.Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <PointOfInterestForUpdateDto, PointOfInterest>();
                cfg.CreateMap <PointOfInterest, PointOfInterestForUpdateDto>();

                cfg.CreateMap <CategoryForCreationDto, Category>();
                cfg.CreateMap <Category, CategoryDto>();

                cfg.CreateMap <SubcategoryForCreationDto, Subcategory>();
                cfg.CreateMap <Subcategory, SubcategoryDto>();

                cfg.CreateMap <CaseForCreationDto, Case>();
            });

            //InitAwsCredetialsFile();
            app.UseIdentity();

            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer              = Configuration["Tokens:Issuer"],
                    ValidAudience            = Configuration["Tokens:Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                    ValidateLifetime         = true
                }
            });

            app.UseMvc();

            //identitySeeder.Seed().Wait();
        }