public CreatePmCommandTestFixture()
 {
     MaterialCategorySeeder.Seed(Context);
     Materials = MaterialSeeder.Seed(Context);
     UserSeeder.Seed(Context);
     SeedMaterials();
 }
Beispiel #2
0
        public static void Seed(DatabaseContext context)
        {
            PermissonSeeder.Seeder(context.Permissions);
            context.SaveChanges();

            RoleSeeder.Seeder(context.Roles);
            context.SaveChanges();

            UserSeeder.Seeder(context.Users);
            context.SaveChanges();

            CompanySeeder.Seeder(context.Companies);
            context.SaveChanges();

            ProjectSeeder.Seeder(context.Projects, context.Companies);
            context.SaveChanges();

            ExperimentSeeder.Seeder(context.Experiments, context.Projects);
            context.SaveChanges();

            LicenseTypeSeeder.Seeder(context.LicenseTypes);
            context.SaveChanges();

            LicenseSeeder.Seeder(context.Licenses, context.LicenseTypes, context.Companies);
            context.SaveChanges();
        }
Beispiel #3
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

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

                try
                {
                    var context     = services.GetRequiredService <SupportPlatformDbContext>();
                    var userManager = services.GetRequiredService <UserManager <UserEntity> >();
                    var roleManager = services.GetRequiredService <RoleManager <RoleEntity> >();
                    await context.Database.MigrateAsync();

                    await UserSeeder.SeedUsers(userManager, roleManager);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occured during migration");
                }
            }
            await host.RunAsync();
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            var deploy = args.Any(x => x == "/deploy");

            if (deploy)
            {
                args = args.Except(new[] { "/deploy" }).ToArray();
            }

            var host = CreateWebHostBuilder(args).Build();

            if (deploy)
            {
                long tenatId = 1;
                var  config  = host.Services.GetRequiredService <IConfiguration>();
                var  shardMapManagerConnString = config.GetConnectionString("ShardMapManager");
                var  shardMapConnString        = config.GetConnectionString("ShardMap");

                var deployUtil = new DeployUtil(shardMapManagerConnString, shardMapConnString);
                deployUtil.DeployShardManagerDbIfNotExist();
                deployUtil.DeployTenantDbIfNotExist(tenatId);

                var userSeeder = new UserSeeder(shardMapConnString);
                userSeeder.SeedDefaultUser(tenatId);

                var productSeeder = new ProductSeeder(shardMapConnString);
                productSeeder.SeedProducts(tenatId);

                return;
            }

            host.Run();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              UserManager <User> userManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseFileServer();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Index}");

                routes.MapRoute(
                    name: "shipDetails",
                    template: "Dashboard/Details/{shipId}",
                    defaults: new { controller = "Dashboard", action = "Details" });
            });

            UserSeeder.SeedUsers(userManager);
            ShipSeeder.SeedShips();
            KpiSeeder.SeedKpis();
        }
        public static async Task Run(IServiceProvider serviceProvider)
        {
            using (var serviceScope = serviceProvider.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();
                serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>().Database.Migrate();

                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                foreach (var resource in IdentityServerSeeder.GetIdentityResources())
                {
                    await context.IdentityResources.AddAsync(resource.ToEntity());
                }

                foreach (var resource in IdentityServerSeeder.GetApiResources())
                {
                    await context.ApiResources.AddAsync(resource.ToEntity());
                }

                foreach (var client in IdentityServerSeeder.GetClients())
                {
                    await context.Clients.AddAsync(client.ToEntity());
                }

                await context.SaveChangesAsync();

                // migrate the data for our identity server
                var identityServerContext = serviceScope.ServiceProvider.GetRequiredService <IdentityServerDbContext>();
                identityServerContext.Database.Migrate();

                await UserSeeder.Seed(identityServerContext);
            }
        }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager <User> userManager)
        {
            app.UseCors("EnableCORS");

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

            app.UseStaticFiles();

            app.UseHttpsRedirection();

            app.UseRouting();

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

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

            UserSeeder.SeedAsync(userManager).Wait();
        }
Beispiel #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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            // Global CORS policy
            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseAuthentication();

            app.UseHttpsRedirection();
            app.UseMvc();

            // Seed the DB with an user if none exist
            UserSeeder.Initialize(app.ApplicationServices.CreateScope().ServiceProvider);
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager <WebShopUser> userManager, RoleManager <IdentityRole <Guid> > roleManager, WebShopDbContext context)
        {
            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.UseAuthentication();


            app.UseRouting();

            app.UseAuthorization();

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

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

            //TODO: So ugly, debug thread issue with dbcontext error in SeedUsers
            UserSeeder.SeedUsers(userManager, roleManager, context).Wait();
        }
Beispiel #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,
                              UserManager <AppUser> userManager, RoleManager <IdentityRole> roleManager,
                              HotelsDbContext context)
        {
            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();

            UserSeeder.Seed(userManager, roleManager).Wait();
            DataSeeder.Seed(context, userManager).Wait();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Beispiel #11
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity <UserTask>()
            .ToTable("UserTasks")
            .HasOne(ut => ut.User)
            .WithMany(u => u.UserTasks)
            .HasForeignKey(ut => ut.UserId);
            modelBuilder.Entity <UserTask>()
            .HasOne(ut => ut.Task)
            .WithMany(t => t.TaskUsers)
            .HasForeignKey(ut => ut.TaskId);

            modelBuilder.Entity <Message>()
            .ToTable("Messages")
            .HasKey(m => m.Id);
            modelBuilder.Entity <Message>()
            .HasOne(m => m.Sender)
            .WithMany(u => u.SendMessages)
            .OnDelete(DeleteBehavior.NoAction)
            .HasForeignKey(m => m.SenderId);
            modelBuilder.Entity <Message>()
            .HasOne(m => m.Receiver)
            .WithMany(u => u.ReceivedMessages)
            .OnDelete(DeleteBehavior.NoAction)
            .HasForeignKey(m => m.ReceiverId);
            modelBuilder.Entity <Message>()
            .HasOne(m => m.Task)
            .WithMany(t => t.Messages)
            .HasForeignKey(m => m.TaskId);

            modelBuilder.Entity <Picture>()
            .ToTable("Pictures")
            .Ignore(p => p.Image);
            modelBuilder.Entity <Picture>()
            .HasOne(p => p.Task)
            .WithMany(t => t.Pictures)
            .HasForeignKey(p => p.TaskId);

            modelBuilder.Entity <AppTask>()
            .ToTable("Tasks")
            .HasOne(t => t.Project)
            .WithMany(p => p.Tasks)
            .HasForeignKey(t => t.ProjectId);


            UserSeeder.Seed(modelBuilder);
            IdentityRoleSeeder.Seed(modelBuilder);
            IdentityUserRoleSeeder.Seed(modelBuilder);
            ProjectSeeder.Seed(modelBuilder);
            TaskSeeder.Seed(modelBuilder);
            UserTaskSeeder.Seed(modelBuilder);
            MessageSeeder.Seed(modelBuilder);
            PictureSeeder.Seed(modelBuilder);
        }
Beispiel #12
0
        private static async Task InitializeIdentityDb()
        {
            using (var serviceScope = _serviceProvider.GetService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService <IdentityServerDbContext>();
                context.Database.Migrate();

                await UserSeeder.Seed(context);
            }
        }
        public static void Initialize(LectureContext context)
        {
            context.Database.EnsureCreated();

            UserSeeder.Seed(context);
            UniSeeder.Seed(context);
            LectureSeeder.Seed(context);
            LectureCommentSeeder.Seed(context);

            context.SaveChanges();
        }
Beispiel #14
0
        public static void SeedDatabase(this IServiceProvider serviceProvider, string password = "******", string emailDomain = "ssrd.io",
                                        string adminUserName = "******", string adminPassword = "******")
        {
            SystemEntitySeeder systemEntitySeeder = serviceProvider.GetRequiredService <SystemEntitySeeder>();
            AdminSeeder        adminSeeder        = serviceProvider.GetRequiredService <AdminSeeder>();
            UserSeeder         userSeeder         = serviceProvider.GetRequiredService <UserSeeder>();

            Task.WaitAll(systemEntitySeeder.SeedIdentityUI());
            Task.WaitAll(adminSeeder.SeedIdentityAdmin(adminUserName, adminPassword));
            Task.WaitAll(userSeeder.Seed(emailDomain, password));
        }
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context  = services.GetRequiredService <UsersDbContext>();
                UserSeeder.Run(services);
            }
            host.Run();
        }
Beispiel #16
0
 private void Seed(ModelBuilder modelBuilder)
 {
     modelBuilder.Entity <User>().HasData(UserSeeder.Create(10));
     modelBuilder.Entity <OrdersDiscount>().HasData(OrdersDiscountSeeder.Create());
     modelBuilder.Entity <Brand>().HasData(BrandSeeder.Create());
     modelBuilder.Entity <Model>().HasData(ModelSeeder.Create());
     modelBuilder.Entity <DaysDiscount>().HasData(DaysDiscountSeeder.Create());
     modelBuilder.Entity <GearBox>().HasData(GearBoxSeeder.Create());
     modelBuilder.Entity <BodyType>().HasData(BodyTypeSeeder.Create());
     modelBuilder.Entity <CarClass>().HasData(CarClassSeeder.Create());
     modelBuilder.Entity <DriveType>().HasData(DriveTypeSeeder.Create());
     modelBuilder.Entity <FuelType>().HasData(FuelTypeSeeder.Create());
 }
Beispiel #17
0
 public Seeder(
     SeederDependencies dependencies,
     UserSeeder userSeeder,
     ClientSeeder clientSeeder,
     ProjectSeeder projectSeeder,
     WorkflowStepItemSeeder workflowStepItemSeeder
     ) : base(dependencies)
 {
     this.userSeeder             = userSeeder;
     this.clientSeeder           = clientSeeder;
     this.projectSeeder          = projectSeeder;
     this.workflowStepItemSeeder = workflowStepItemSeeder;
 }
Beispiel #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            // This needs to be enabled to use DI for IOptions<> to map appsettings
            services.AddOptions();
            //services.Configure<ExampleSettings>(opt => Configuration.GetSection("ExampleSettings").Bind(opt));

            services.AddDbContext <SqlContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });;

            services.AddIdentity <User, Role>(options =>
            {
                options.Lockout = new LockoutOptions
                {
                    AllowedForNewUsers      = true,
                    DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30),
                    MaxFailedAccessAttempts = 5
                };
            })
            .AddEntityFrameworkStores <SqlContext>()
            .AddDefaultTokenProviders()
            .AddUserStore <UserStore <User, Role, SqlContext, Guid> >()
            .AddRoleStore <RoleStore <Role, SqlContext, Guid> >()
            .AddUserManager <ApplicationUserManager>();

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 5;
                options.Password.RequireLowercase       = true;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = true;
            });

            services.AddScoped <ApplicationUserManager>();
            services.AddScoped <ApplicationSignInManager>();
            services.AddScoped <SqlContext>();

            AutoMapperConfig.Register();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddTransient <RoleSeeder>();
            services.AddTransient <UserSeeder>();

            ServiceProvider = services.BuildServiceProvider();
            RoleSeeder      = ServiceProvider.GetService <RoleSeeder>();
            UserSeeder      = ServiceProvider.GetService <UserSeeder>();
        }
Beispiel #19
0
        private static void InsertUsers(BillsPaymentSystemContext context)
        {
            var users = UserSeeder.GetUsers();

            foreach (var user in users)
            {
                if (IsValid(user))
                {
                    context.Users.Add(user);
                }
            }

            context.SaveChanges();
        }
Beispiel #20
0
        protected override void Seed(DsContext context)
        {
            RoleSeeder.SeedInitialRoles(context);

            FeatureTierSeeder.SeedInitialFeatureTiers(context);

            UserSeeder.SeedInitialUsers(context);

            var categories = CategorySeeder.SeedInitialCategories(context);

            var keywords = KeywordSeeder.SeedInitialKeywords(context);

            DocumentSeeder.AddTestDocuments(context, categories, keywords);
        }
Beispiel #21
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Seeders
            UserSeeder.Seed(modelBuilder);
            PaymentSeeder.Seed(modelBuilder);
            OrderStatusSeeder.Seed(modelBuilder);

            //Configurations
            DecimalConfiguration.Configure(modelBuilder);
            UserRoleConfiguration.Configure(modelBuilder);
            ProductIngredientConfiguration.Configure(modelBuilder);

            base.OnModelCreating(modelBuilder);
        }
Beispiel #22
0
        /**
         * Seed tables with data and give relationships
         */
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            ChecklistSeeder cs = new ChecklistSeeder();
            CheckSeeder     qs = new CheckSeeder();
            UserSeeder      us = new UserSeeder();

            Check.InitRelationships(modelBuilder);
            User.InitRelationships(modelBuilder);
            Checklist.InitRelationships(modelBuilder);

            cs.Seed(modelBuilder);
            qs.Seed(modelBuilder);
            us.Seed(modelBuilder);
        }
Beispiel #23
0
        protected override void OnModelCreating(ModelBuilder builder)
        {
            UserSeeder.SeedRoles(builder);

            builder.ApplyConfiguration(new ArtistConfig());
            builder.ApplyConfiguration(new GenreConfig());
            builder.ApplyConfiguration(new TrackConfig());
            builder.ApplyConfiguration(new PlaylistConfig());
            builder.ApplyConfiguration(new TrackPlaylistConfig());

            var cascadeFKs = builder.Model.GetEntityTypes()
                             .SelectMany(t => t.GetForeignKeys())
                             .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);


            foreach (var fk in cascadeFKs)
            {
                fk.DeleteBehavior = DeleteBehavior.Restrict;
            }

            base.OnModelCreating(builder);
        }
Beispiel #24
0
 public CreateMaterialCommandTestFixture() : base()
 {
     MaterialCategorySeeder.Seed(Context);
     UserSeeder.Seed(Context);
 }
Beispiel #25
0
 public DevController(UserSeeder userSeeder)
 {
     this.userSeeder = userSeeder;
 }
 public PmQueryTestFixture()
 {
     UserSeeder.Seed(Context);
     SeedUser();
     SeedPms();
 }
Beispiel #27
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });

                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                    services.AddServicesDependencies(GcpProjectId);
                }
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedProto
                });

                var options = new RewriteOptions();

                options.Rules.Add(new NonWwwRule());
                options.AddRedirectToHttps();

                app.UseRewriter(options);

                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                if (HasGcpProjectId)
                {
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    logger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    logger.LogInformation(
                        "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                if (HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = new PathString("/lib")
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

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

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

                UserSeeder.Initialize(app.ApplicationServices);
            }).Build();

            host.Run();
        }
Beispiel #28
0
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            #region ApplicationUser

            builder.Entity <ApplicationUser>(b => {
                b.HasMany(x => x.UserRoles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
                b.HasMany(t => t.TreatmentHistories).WithOne(th => th.User).HasForeignKey(th => th.UserId).IsRequired();
                b.HasMany(t => t.Schedule).WithOne(s => s.User).HasForeignKey(s => s.UserId).IsRequired();
                b.HasMany(t => t.Comments).WithOne(c => c.User).HasForeignKey(th => th.UserId);
            });

            builder.Entity <ApplicationRole>(b =>
            {
                b.HasMany(ur => ur.UserRoles).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
            });

            builder.Entity <ApplicationUserRole>(b =>
            {
                b.HasOne(ur => ur.Role).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.RoleId);
                b.HasOne(ur => ur.User).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.UserId);
            });

            #endregion

            #region Affiliate

            builder.Entity <Affiliate>(b => {
                b.HasMany(u => u.Users).WithOne(a => a.Affiliate);
                b.HasOne(a => a.Address).WithOne(a => a.Affiliate).HasForeignKey <Address>(a => a.AffiliateId);
                b.HasMany(t => t.TreatmentHistories).WithOne(a => a.Affiliate);
            });

            #endregion

            #region Patient

            builder.Entity <Patient>(b =>
            {
                b.HasOne(p => p.MedicalChart).WithOne(mc => mc.Patient).HasForeignKey <MedicalChart>(mc => mc.PatientId);
                b.HasMany(p => p.Schedule).WithOne(c => c.Patient).HasForeignKey(th => th.PatientId);
            });

            #endregion

            #region MedicalChart

            builder.Entity <MedicalChart>(b =>
            {
                b.HasMany(t => t.Teeth).WithOne(mc => mc.MedicalChart);
                b.HasMany(t => t.Allergies).WithOne(mc => mc.MedicalChart);
                b.HasMany(t => t.Files).WithOne(mc => mc.MedicalChart);
                b.HasMany(t => t.TreatmentHistories).WithOne(mc => mc.MedicalChart);
            });

            #endregion

            #region ToothDisease

            builder.Entity <ToothDisease>().HasKey(td => new { td.DiseaseId, td.ToothId });

            builder.Entity <ToothDisease>().HasOne(td => td.Disease).WithMany(d => d.ToothDiseases).HasForeignKey(td => td.DiseaseId);

            builder.Entity <ToothDisease>().HasOne(td => td.Tooth).WithMany(d => d.ToothDiseases).HasForeignKey(td => td.ToothId);

            #endregion

            #region Treatment

            builder.Entity <Treatment>(b => {
                b.HasMany(t => t.TreatmentHistories).WithOne(th => th.Treatment);
            });

            #endregion

            #region Tooth

            builder.Entity <Tooth>(b => {
                b.HasMany(t => t.Comments).WithOne(c => c.Tooth);
                b.HasMany(t => t.TreatmentHistories).WithOne(c => c.Tooth);
            });

            #endregion

            #region Seeds

            RoleSeeder.Seed(builder);
            AffiliateSeeder.Seed(builder);
            UserSeeder.Seed(builder);
            UserRoleSeed.Seed(builder);

            #endregion
        }
Beispiel #29
0
        public static void Initialize(AppDbContext context, IServiceProvider services)
        {
            context.Database.EnsureCreated();

            var userSeeder = new UserSeeder(context);

            userSeeder.Seed();

            // usuarios

            //if (!context.Usuarios.Any())
            //{
            //context.Usuarios.Add(new UserEntity()
            //{
            //    NIF = "11223344A",
            //    Nombre = "Josep",
            //    Apellidos = "Temprà Cor",
            //    Direccion = "Carrer Trobadiners, 40",
            //    Movil = "615051815",
            //    Email = "*****@*****.**",
            //    PathFoto = "c:\\fotos\\jt.jpg",
            //    Rol = TipoUsuario.Administrador,
            //    UserName = "******",
            //    Password = "******",
            //    Lecturas = new List<LecturaEntity>(),
            //    Incidencias = new List<IncidenciaEntity>(),
            //    OrdenesTrabajoCreadas = new List<OTEntity>(),
            //    OrdenesTrabajoGestionadas = new List<OTEntity>()
            //});
            //context.Usuarios.Add(new UserEntity()
            //{
            //    NIF = "55667788B",
            //    Nombre = "Ahmed",
            //    Apellidos = "Al Azred",
            //    Direccion = "Carrer Allah, 3-2-1",
            //    Movil = "600112233",
            //    Email = "*****@*****.**",
            //    PathFoto = "c:\\fotos\\aaa.jpg",
            //    Rol = TipoUsuario.Lector,
            //    UserName = "******",
            //    Password = "******",
            //    Lecturas = new List<LecturaEntity>(),
            //    Incidencias = new List<IncidenciaEntity>(),
            //    OrdenesTrabajoCreadas = new List<OTEntity>(),
            //    OrdenesTrabajoGestionadas = new List<OTEntity>()
            //});
            //context.Usuarios.Add(new UserEntity()
            //{
            //    NIF = "99009900X",
            //    Nombre = "Joan",
            //    Apellidos = "Manges",
            //    Direccion = "Carrer de la frontera, 124",
            //    Movil = "600234532",
            //    Email = "*****@*****.**",
            //    PathFoto = "c:\\fotos\\jm.jpg",
            //    Rol = TipoUsuario.Operario,
            //    UserName = "******",
            //    Password = "******",
            //    Lecturas = new List<LecturaEntity>(),
            //    Incidencias = new List<IncidenciaEntity>(),
            //    OrdenesTrabajoCreadas = new List<OTEntity>(),
            //    OrdenesTrabajoGestionadas = new List<OTEntity>()
            //});
            //}



            //context.SaveChanges();
        }
Beispiel #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, ILoggerFactory loggerFactory, UserSeeder seeder)
        {
            loggerFactory.AddConsole();

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

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Customer, CustomerDto>();
                cfg.CreateMap <Order, OrderDto>();
                cfg.CreateMap <OrderItem, OrderItemDto>();
                cfg.CreateMap <Product, ProductDto>();
                cfg.CreateMap <OrderItemPostDto, OrderItem>();
            });

            app.UseIdentity();

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

            app.UseMvc();

            seeder.Seed().Wait();
        }