예제 #1
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.Cities.AnyAsync())
            {
                List <City> references = new List <City>();

                var cities = new List <City>
                {
                    new City {
                        Name = "Kiev", Alias = "kiev"
                    },
                    new City {
                        Name = "Dnipro", Alias = "dnipro"
                    },
                    new City {
                        Name = "Lviv", Alias = "lviv"
                    },
                };

                foreach (var city in cities)
                {
                    await context.Cities.AddAsync(city);

                    references.Add(city);
                }

                await context.SaveChangesAsync();

                ApplicationDbSeed.SetReferences(GetReferenceKeyName(), references);
            }
        }
예제 #2
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.Doctors.AnyAsync())
            {
                List <Doctor> references = new List <Doctor>();

                var doctors = new List <Doctor>
                {
                    new Doctor("elena-gaidai", "Елена", "Гайдай", "Владимировна", "", 33,
                               "Врач проводит консультации, диагностику и терапию заболеваний нервной системы. Елена Владимировна владеет методикой немедикаментозной тренажерной коррекции заболеваний позвоночника (осложненный и неосложненный остеохондроз позвоночника , спондилоартроз, нарушения осанки, миофасциальный болевой синдром ) , разрабатывает программу физической реабилитации пациентов на вертебрологических устройствах для лечения и профилактики заболеваний опорно-двигательного аппарата Eurospine",
                               "photo"),
                    new Doctor("olga-kusebenko", "Ольга", "Козубенко", "Геннадьевна", "Детский врач", 16,
                               "Врач-невролог ведет консультативные приемы маленьких пациентов, оказывает лечебно-диагностическую помощь. Занимается снятием и расшифровкой электроэнцефалограммы головного мозга, определяет тактику ведения пациента. Лечит неврологии раннего детского возраста, специализируется на перинатальной патологии, подростковой неврологии",
                               "photo"),
                };

                foreach (var doctor in doctors)
                {
                    await context.Doctors.AddAsync(doctor);

                    references.Add(doctor);
                }

                await context.SaveChangesAsync();

                ApplicationDbSeed.SetReferences(GetReferenceKeyName(), references);
            }
        }
예제 #3
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try
                {
                    var context = services.GetRequiredService <ApplicationDbContext>();
                    await context.Database.MigrateAsync();

                    await ApplicationDbSeed.SeedAsync(context, loggerFactory);

                    // Identity
                    var userManager     = services.GetRequiredService <UserManager <AppUser> >();
                    var identityContext = services.GetRequiredService <AppIdentityDbContext>();
                    await identityContext.Database.MigrateAsync();

                    await AppIdentityDbContextSeed.SeedUserAsync(userManager);
                }
                catch (Exception ex)
                {
                    // <Program> thats specify class what we want to log all errors and
                    // pass them in exception (ex)
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occured during migration");
                }
            }
            host.Run();
        }
예제 #4
0
        private static async Task MakeSeeds(this IHost host)
        {
            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

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

            await ApplicationDbSeed.SeedDataAsync(context);
        }
예제 #5
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.Stats.AnyAsync())
            {
                var doctors = ApplicationDbSeed.GetReferences <List <Doctor> >(DoctorsSeed.GetReferenceKeyName());

                foreach (var doctor in doctors)
                {
                    var stats = new Stats(9.2, 25, 1, 0, doctor);

                    await context.Stats.AddAsync(stats);
                }

                await context.SaveChangesAsync();
            }
        }
예제 #6
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args)
                       .Build();

            using (var scope = host.Services.CreateScope())
            {
                var services    = scope.ServiceProvider;
                var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                var context     = services.GetRequiredService <ApplicationDbContext>();
                ApplicationDbSeed.SeedAsync(context, userManager)
                .Wait();
            }

            host.Run();
        }
예제 #7
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                //DbContext isntance here
                var dbContext = scope.ServiceProvider.GetService <ApplicationDbContext>();
                var logger    = scope.ServiceProvider.GetService <ILogger <Program> >();

                ApplicationDbSeed.Seed(dbContext, logger);

                //DB seeding code here
            }
            host.Run();
        }
예제 #8
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.Specialties.AnyAsync())
            {
                List <Specialty> references = new List <Specialty>();

                var cities = ApplicationDbSeed.GetReferences <List <City> >(nameof(CitiesSeed));

                foreach (City city in cities)
                {
                    var specialties = new List <Specialty>
                    {
                        new Specialty {
                            Title = "Невролог", Alias = "nevrolog", City = city
                        },
                        new Specialty {
                            Title = "Отоларинголог", Alias = "otolaringolog-lor", City = city
                        },
                        new Specialty {
                            Title = "Психолог", Alias = "psiholog", City = city
                        },
                        new Specialty {
                            Title = "Трихолог", Alias = "triholog", City = city
                        },
                        new Specialty {
                            Title = "Косметолог", Alias = "kosmetolog", City = city
                        },
                        new Specialty {
                            Title = "Ортодонт", Alias = "ortodont", City = city
                        }
                    };

                    foreach (var specialty in specialties)
                    {
                        await context.Specialties.AddAsync(specialty);

                        references.Add(specialty);
                    }
                }

                await context.SaveChangesAsync();

                ApplicationDbSeed.SetReferences(GetReferenceKeyName(), references);
            }
        }
예제 #9
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.DoctorSpecialties.AnyAsync())
            {
                var doctors     = ApplicationDbSeed.GetReferences <List <Doctor> >(DoctorsSeed.GetReferenceKeyName());
                var specialties = ApplicationDbSeed.GetReferences <List <Specialty> >(SpecialtiesSeed.GetReferenceKeyName());

                foreach (var doctor in doctors)
                {
                    foreach (var specialty in specialties)
                    {
                        await context.DoctorSpecialties.AddAsync(new DoctorSpecialty(doctor, specialty));
                    }
                }

                await context.SaveChangesAsync();
            }
        }
예제 #10
0
        public async Task SeedAsync(IApplicationDbContext context)
        {
            if (!await context.Informations.AnyAsync())
            {
                var doctors = ApplicationDbSeed.GetReferences <List <Doctor> >(DoctorsSeed.GetReferenceKeyName());

                foreach (var doctor in doctors)
                {
                    var informations = new List <Information>
                    {
                        new Information(InformationType.WorkExperience,
                                        "1993 г. - невролог в Цетральном военном госпитале (СГВ, Польша)", 1, doctor),
                        new Information(InformationType.WorkExperience,
                                        "2013 г. - заведующая отделением специализированного приема Центральной Районной поликлиники Деснянського р-на, внештатный главный невролог района",
                                        1, doctor),
                        new Information(InformationType.WorkExperience,
                                        "2010 г.- невропатолог клиники «Эфферентной терапии»", 1, doctor),
                        new Information(InformationType.WorkExperience, "2016 г. - невролог клиники «ХелсиЕндХеппи»", 1,
                                        doctor),

                        new Information(InformationType.Procedures, "консультативный прием", 2, doctor),
                        new Information(InformationType.Procedures, "осмотр и изучение анамнеза", 2, doctor),
                        new Information(InformationType.Procedures, "назначение и коррекция схемы лечения", 2, doctor),


                        new Information(InformationType.Education,
                                        "Львовский национальный медицинский университет им Д. Галицкого - педиатрия (2002)", 3,
                                        doctor),
                    };

                    foreach (var information in informations)
                    {
                        await context.Informations.AddAsync(information);
                    }
                }

                await context.SaveChangesAsync();
            }
        }
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var serviceProvider = scope.ServiceProvider;
                try
                {
                    var db = serviceProvider.GetRequiredService <ApplicationDbContext>();

                    var userManager = serviceProvider.GetRequiredService <UserManager <Person> >();

                    ApplicationDbSeed.Seed(userManager, db, false);
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex);
                }
            }
            host.Run();
        }
예제 #12
0
        public static void Main(string[] args)
        {
            //BuildWebHost(args).Run();
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var db          = services.GetRequiredService <ApplicationDbContext>();
                    var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                    ApplicationDbSeed.Seed(userManager, roleManager, db).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }
            host.Run();
        }
예제 #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();
                app.UseStatusCodePages();
            }

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "pagination",
                    template: "{controller}/Page{pageNumber}",
                    defaults: new { action = "Index" });

                routes.MapRoute(
                    name: "kudoDetails",
                    template: "{controller}/{id:int}",
                    defaults: new { action = "Details" });

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

            if (!_env.IsDevelopment())
            {
                var context = (ApplicationDbContext)app.ApplicationServices.GetService(typeof(ApplicationDbContext));
                context.Database.Migrate();
            }

            ApplicationDbSeed.CreateAdminAccount(app.ApplicationServices, Configuration).Wait();
            ApplicationDbSeed.EnsureSeeded(app.ApplicationServices, Configuration);
        }
예제 #14
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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            if (env.IsProduction())
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedProto
                });
            }

            app.UseRouting();
            app.UseStaticFiles();
            app.UseCookiePolicy(); // https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1
            app.UseAuthentication();
            app.UseAuthorization();

            // Set up hangfire capabilities
            var options = new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            };

            app.UseHangfireDashboard("/hangfire", options);
            app.UseHangfireServer();

            RecurringJob.AddOrUpdate <IGenerateTranscripts>(
                generator => generator.Execute(), Cron.Daily);

            BackgroundJob.Enqueue <IStudentDataImporter>(
                generator => generator.Execute());

            //BackgroundJob.Enqueue<IEmailQueue>(
            //    queue => queue.SendMail("*****@*****.**", "Test Message", "this is a scholarship email test.. did you get this?"));
            //BackgroundJob.Enqueue<ICreateApplicationPackage>(queue => queue.Execute());

            // If you want to run the job immediately

            /*
             * BackgroundJob.Enqueue<IGenerateTranscripts>(
             *  generator => generator.Execute());
             */

            // Set up App_Data directory
            // set
            var baseDir = env.ContentRootPath;

            AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(baseDir, "App_Data"));

            app.UseStatusCodePagesWithRedirects("/error/{0}");
            app.UseAnalyticsLogger(); // Custom middleware

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

                endpoints.MapControllerRoute(
                    "securedownload",
                    "{controller=SecureDownload}/{id?}/{filename?}",
                    new { controller = "SecureDownload", action = "Download" }
                    );
            });

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

                // seed the AspNetRoles table
                var roleSeed = new ApplicationRoleSeed(roleManager);
                roleSeed.CreateRoles();

                // seed the AspNetUsers table
                var userSeed = new ApplicationUserSeed(userManager, dbContext);
                userSeed.CreateAdminUser();

                var dbSeed = new ApplicationDbSeed(dbContext);
                dbSeed.SeedDatabase();
            }

            app.UseSmidge(bundles =>
            {
                bundles.CreateCss("scholarship-application-css",
                                  "~/lib/bootstrap/dist/css/bootstrap.css",
                                  "~/lib/font-awesome/css/font-awesome.css",
                                  "~/css/animate.css",
                                  "~/css/style.css",
                                  "~/css/site.css",
                                  "~/lib/heart/heart.css");

                // Libraries
                bundles.CreateJs("scholarship-js-libraries",
                                 "~/lib/jquery/dist/jquery.js",
                                 "~/lib/jquery-ui/jquery-ui.js",
                                 "~/lib/Popper/popper.js",
                                 "~/lib/bootstrap/dist/js/bootstrap.js"
                                 );

                // Custom scripts
                bundles.CreateJs("scholarship-js-custom",
                                 "~/js/site.js");

                // Inspinia scripts
                bundles.CreateJs("scholarship-js-inspinia",
                                 "~/lib/metisMenu/dist/jquery.metisMenu.js",
                                 "~/lib/slimScroll/jquery.slimscroll.js",
                                 "~/lib/pace/pace.js",
                                 "~/js/script.js");
            });
        }