Ejemplo n.º 1
0
 public static void ClassCleanup()
 {
     DatabaseSeeder.CleanDatabase();
 }
Ejemplo n.º 2
0
        private void Initialize()
        {
            if (MapperConfiguration == null)
            {
                MapperConfiguration = new MapperConfiguration(cfg =>
                {
                    cfg.AddExpressionMapping();

                    cfg.AddProfile <ParameterToDescriptorMappingProfile>();
                    cfg.AddProfile <DescriptorToOperatorMappingProfile>();
                    cfg.AddProfile <SchoolProfile>();
                    cfg.AddProfile <ExpansionParameterToDescriptorMappingProfile>();
                    cfg.AddProfile <ExpansionDescriptorToOperatorMappingProfile>();
                });
            }
            MapperConfiguration.AssertConfigurationIsValid();
            serviceProvider = new ServiceCollection()
                              .AddDbContext <SchoolContext>
                              (
                options => options.UseSqlServer
                (
                    @"Server=(localdb)\mssqllocaldb;Database=RulesVsNoRulesDurationTest;ConnectRetryCount=0"
                ),
                ServiceLifetime.Transient
                              )
                              .AddLogging
                              (
                loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.Services.AddSingleton <ILoggerProvider>
                (
                    serviceProvider => new XUnitLoggerProvider(this.output)
                );
                loggingBuilder.AddFilter <XUnitLoggerProvider>("*", LogLevel.None);
                loggingBuilder.AddFilter <XUnitLoggerProvider>("Contoso.Bsl.Flow", LogLevel.Trace);
            }
                              )
                              .AddTransient <ISchoolStore, SchoolStore>()
                              .AddTransient <ISchoolRepository, SchoolRepository>()
                              .AddSingleton <AutoMapper.IConfigurationProvider>
                              (
                MapperConfiguration
                              )
                              .AddTransient <IMapper>(sp => new Mapper(sp.GetRequiredService <AutoMapper.IConfigurationProvider>(), sp.GetService))
                              .AddTransient <IFlowManager, FlowManager>()
                              .AddTransient <FlowActivityFactory, FlowActivityFactory>()
                              .AddTransient <DirectorFactory, DirectorFactory>()
                              .AddTransient <ICustomActions, CustomActions>()
                              .AddTransient <IGetItemFilterBuilder, GetItemFilterBuilder>()
                              .AddSingleton <FlowDataCache, FlowDataCache>()
                              .AddSingleton <Progress, Progress>()
                              .AddSingleton <IRulesCache>(sp =>
            {
                return(Bsl.Flow.Rules.RulesService.LoadRules().GetAwaiter().GetResult());
            })
                              .BuildServiceProvider();

            ReCreateDataBase(serviceProvider.GetRequiredService <SchoolContext>());
            DatabaseSeeder.Seed_Database(serviceProvider.GetRequiredService <ISchoolRepository>()).Wait();
        }
Ejemplo n.º 3
0
 public static void ClassInitialize(TestContext context)
 {
     DatabaseSeeder.SeedDatabase();
 }
Ejemplo n.º 4
0
 public FakeDatabaseService()
 {
     DatabaseSeeder.SeedDatabase();
 }
Ejemplo n.º 5
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UserManager <User> userManager, ApplicationDbContext dbContext, DatabaseSeeder seeder)
        {
            dbContext.Database.EnsureCreated();
            DatabaseConfiguration.EnsureEventStoreIsCreated(Configuration);

            if (!env.IsEnvironment(Environment.IntegrationTests))
            {
                DatabaseConfiguration.AddDefaultAdminAccountIfNoneExisting(userManager, Configuration).Wait();
                seeder.SeedDatabase().Wait();
            }

            if (!env.IsDevelopment())
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseCors(builder => builder
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .WithOrigins("http://localhost:3000", "https://*.devadventures.net")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            loggerFactory.AddLogging(Configuration.GetSection("Logging"));

            app.UseSwagger("Cafe");
            app.UseStaticFiles();
            app.UseAuthentication();

            // It's very important that UseAuthentication is called before UseSignalR
            app.UseSignalR(routes =>
            {
                routes.MapHub <ConfirmedOrdersHub>("/confirmedOrders");
                routes.MapHub <HiredWaitersHub>("/hiredWaiters");
                routes.MapHub <TableActionsHub>("/tableActions");
            });

            app.UseMvc();
        }
Ejemplo n.º 6
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, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
                // 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", "ComplyTo Compliance Cloud Product API v1");
                });
            }
            else
            {
                app.UseExceptionHandler("/LandingPages/Home/Error");

                //redirect to https
                //var options = new RewriteOptions().AddRedirectToHttps();
                //app.UseRewriter(options);
            }

            // Http Error Handler
            app.UseMyExceptionMiddleware();

            // It is important to place UseAuthentication method before Use method.
            app.UseAuthentication();

            // It is important to place Use method after UseAuthentication method.
            app.Use(async(context, next) =>
            {
                // Set antiforgery cookie for the response
                context.Response.Cookies.Append("XSRF-TOKEN", antiforgery.GetAndStoreTokens(context).RequestToken, new CookieOptions {
                    HttpOnly = false, SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict
                });

                // Add recommended security headers for the responses
                context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
                context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
                context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
                context.Response.Headers.Add("Referrer-Policy", "no-referrer");
                context.Request.EnableRewind();

                await next();
                if (context.Response.StatusCode == (int)HttpStatusCode.NotFound &&
                    !Path.HasExtension(context.Request.Path.Value) &&
                    !context.Request.Path.Value.StartsWith("/api") &&
                    !context.Request.Path.Value.StartsWith("/landingpages"))
                {
                    context.Request.Path = context.Request.Path.Value.StartsWith("/sai") ? "/sai/index.html" : "/index.html";
                    await next();
                }
            });

            app.UseDefaultFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = (context) =>
                {
                    const int durationInSeconds = 60 * 60 * 24 * 30;
                    if (context.File.Name.ToLower().Contains(".css") || context.File.Name.ToLower().Contains(".png") || context.File.Name.ToLower().Contains(".jpg") ||
                        context.File.Name.ToLower().Contains(".js") || context.File.Name.ToLower().Contains(".woff"))
                    {
                        context.Context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=" + durationInSeconds;
                    }
                }
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
                RequestPath = new PathString(String.Empty)
            });

            //Configure database encryption
            //InitializeAzureKeyVaultProvider(Configuration["Azure:AppRegistrationId"], Configuration["Azure:AppRegistrationKey"]);

            app.UseSession();

            app.UseAuthentication();

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

            DatabaseSeeder.EnsureSeeded(app.ApplicationServices.GetRequiredService <ApplicationDbContext>());
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            DatabaseSeeder databaseSeeder = new DatabaseSeeder();

            databaseSeeder.Run();
        }
Ejemplo n.º 8
0
        private async void Seed3_Click(object sender, RoutedEventArgs e)
        {
            await DatabaseSeeder.SeedData3();

            FacultiesButton.Command.Execute("faculties");
        }
Ejemplo n.º 9
0
 void IAdministrationService.ResetAdministration()
 {
     DatabaseSeeder.Seed(GetCurrentContext());
 }
Ejemplo n.º 10
0
 public ArmDbContext(DbContextOptions <ArmDbContext> options, DatabaseSeeder seeder = null) : base(options)
 {
     _seeder = seeder;
 }
Ejemplo n.º 11
0
 protected override void Configure()
 {
     Log.Debug("Seeding database");
     DatabaseSeeder.Seed(database);
 }
Ejemplo n.º 12
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            DatabaseSeeder.SeedData1();

            RefreshView();
        }
Ejemplo n.º 13
0
        public void DatabaseSeederTest()
        {
            var seeder = new DatabaseSeeder();

            seeder.SeedDatabase(new CcgDbContext());
        }
Ejemplo n.º 14
0
        public static int EnsureSeedData(this ApplDbContext context)
        {
            var bookCount               = default(int);
            var characterCount          = default(int);
            var bookSeriesCount         = default(int);
            var rolesCount              = default(int);
            var countriesCount          = default(int);
            var stockMovementTypesCount = default(int);
            var productsCount           = default(int);

            // Because each of the following seed method needs to do a save
            // (the data they're importing is relational), we need to call
            // SaveAsync within each method.
            // So let's keep tabs on the counts as they come back

            var dbSeeder = new DatabaseSeeder(context);

            if (!context.Countries.Any())
            {
                var pathToSeedData = Path.Combine(Directory.GetCurrentDirectory(), "SeedData", "CountrySeedData.json");
                countriesCount = dbSeeder.SeedCountriesFromJson(pathToSeedData).Result;
            }
            if (!context.StockMovementTypes.Any())
            {
                var pathToSeedData = Path.Combine(Directory.GetCurrentDirectory(), "SeedData", "StockMovementType.json");
                stockMovementTypesCount = dbSeeder.SeedStockMovementTypeFromJson(pathToSeedData).Result;
            }
            if (!context.Products.Any())
            {
                var pathToSeedData = Path.Combine(Directory.GetCurrentDirectory(), "SeedData", "ProductSeedData.json");
                productsCount = dbSeeder.SeedProductsFromJson(pathToSeedData).Result;
            }
            if (!context.Roles.Any())
            {
                var pathToSeedData = Path.Combine(Directory.GetCurrentDirectory(), "SeedData", "RoleSeedData.json");
                rolesCount = dbSeeder.SeedRolesFromJson(pathToSeedData).Result;
                if (rolesCount > 0)
                {
                    int adminId = context
                                  .Roles
                                  .Where(r => r.RoleName == "Admin")
                                  .Select(r => r.Id)
                                  .SingleOrDefault();

                    applevalApi.Entities.Role role = context.Roles.Find(adminId);

                    if (adminId > 0 && role != null)
                    {
                        byte[] passwordHash, passwordSalt;
                        var    password = "******";
                        Tools.CreatePasswordHash(password, out passwordHash, out passwordSalt);

                        // Add user Admin
                        var user = new applevalApi.Entities.User();
                        user.FirstName    = "admin";
                        user.LastName     = "admin";
                        user.Username     = "******";
                        user.Password     = "";
                        user.PasswordHash = passwordHash;
                        user.PasswordSalt = passwordSalt;
                        user.Role         = role;
                        user.Enabled      = true;

                        context.Users.Add(user);
                        context.SaveChanges();
                    }

                    int operatorId = context
                                     .Roles
                                     .Where(r => r.RoleName == "Operator")
                                     .Select(r => r.Id)
                                     .SingleOrDefault();

                    applevalApi.Entities.Role roleOperator = context.Roles.Find(operatorId);

                    int customerId = context
                                     .Roles
                                     .Where(r => r.RoleName == "Customer")
                                     .Select(r => r.Id)
                                     .SingleOrDefault();

                    applevalApi.Entities.Role roleCustomer = context.Roles.Find(customerId);

                    if (operatorId > 0 && roleOperator != null)
                    {
                        byte[] passwordHash, passwordSalt;
                        var    password = "******";
                        Tools.CreatePasswordHash(password, out passwordHash, out passwordSalt);

                        // Add user Admin
                        var userOperator = new applevalApi.Entities.User();
                        userOperator.FirstName    = "operator";
                        userOperator.LastName     = "operator";
                        userOperator.Username     = "******";
                        userOperator.Password     = "";
                        userOperator.PasswordHash = passwordHash;
                        userOperator.PasswordSalt = passwordSalt;
                        userOperator.Role         = roleOperator;
                        userOperator.Enabled      = true;

                        context.Users.Add(userOperator);
                        context.SaveChanges();
                    }


                    if (operatorId > 0 && roleOperator != null)
                    {
                        byte[] passwordHash, passwordSalt;
                        var    password = "******";
                        Tools.CreatePasswordHash(password, out passwordHash, out passwordSalt);

                        // Add user Admin
                        var userOperator = new applevalApi.Entities.User();
                        userOperator.FirstName    = "operator";
                        userOperator.LastName     = "operator";
                        userOperator.Username     = "******";
                        userOperator.Password     = "";
                        userOperator.PasswordHash = passwordHash;
                        userOperator.PasswordSalt = passwordSalt;
                        userOperator.Role         = roleOperator;
                        userOperator.Enabled      = true;

                        context.Users.Add(userOperator);
                        context.SaveChanges();
                    }

                    if (customerId > 0 && roleCustomer != null)
                    {
                        byte[] passwordHash, passwordSalt;
                        var    password = "******";
                        Tools.CreatePasswordHash(password, out passwordHash, out passwordSalt);

                        // Add user Admin
                        var userCustomer = new applevalApi.Entities.User();
                        userCustomer.FirstName    = "customer";
                        userCustomer.LastName     = "customer";
                        userCustomer.Username     = "******";
                        userCustomer.Password     = "";
                        userCustomer.PasswordHash = passwordHash;
                        userCustomer.PasswordSalt = passwordSalt;
                        userCustomer.Role         = roleCustomer;
                        userCustomer.Enabled      = true;

                        context.Users.Add(userCustomer);
                        context.SaveChanges();
                    }
                }
            }

            // Existen los productus pero el stock esta vacio
            if (!context.Stocks.Any() && context.Products.Any())
            {
                foreach (applevalApi.Entities.Product product in context.Products)
                {
                    //sw.WriteLine(sw.QuoteId.ToString() + "," + sw.Quotation);
                    var stockItem     = new applevalApi.Entities.Stock();
                    var stockMovement = new applevalApi.Entities.StockMovement();

                    int inStockMovementTypeId = context
                                                .StockMovementTypes
                                                .Where(r => r.Name == "In")
                                                .Select(r => r.Id)
                                                .SingleOrDefault();

                    applevalApi.Entities.StockMovementType stockMovementType = context.StockMovementTypes.Find(inStockMovementTypeId);

                    stockItem.Description = product.Description;
                    stockItem.product     = product;
                    stockItem.Quantity    = 1000;
                    context.Stocks.Add(stockItem);


                    stockMovement.product           = product;
                    stockMovement.DocumentID        = "Database-Initial-Seed-0001";
                    stockMovement.Quantity          = 1000;
                    stockMovement.StockMovementType = stockMovementType;

                    context.StockMovements.Add(stockMovement);
                    context.SaveChanges();
                }
            }

            return(bookCount + characterCount + bookSeriesCount);
        }