public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

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

                try
                {
                    var context = services.GetRequiredService <UniversityContext>();
                    DbInitialiser.Initialize(context);

                    // context.Database.EnsureCreated();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }

            host.Run();

            // BuildWebHost(args).Run();
        }
Exemple #2
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DatabaseContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

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

            DbInitialiser.Initialise(context);
        }
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, NORTHWNDContext oldContext, 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=Home}/{action=Index}/{id?}");
            });

            DbInitialiser.MigrateNorthwindData(oldContext, context);
        }
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var env      = services.GetRequiredService <IHostingEnvironment>();
                if (env.IsDevelopment())
                {
                    var context = services.GetRequiredService <Db>();
                    context.Database.Migrate();
                    try
                    {
                        DbInitialiser.SeedTestData(context, services).Wait();
                    }
                    catch (Exception)
                    {
                        var logger = services.GetRequiredService <ILogger <Program> >();
                        logger.LogDebug("Seeding test data failed.");
                    }
                }
            }

            host.Run();
        }
Exemple #5
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, Ultimates_CricketContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

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

            context.Database.Migrate();

            DbInitialiser.Initialize(context);
        }
Exemple #6
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var env     = services.GetRequiredService <IWebHostEnvironment>();
                    var context = services.GetRequiredService <LrpDbContext>();
                    if (env.IsDevelopment())
                    {
                        context.Database.EnsureDeleted();
                    }

                    context.Database.EnsureCreated();
                    DbInitialiser.Initialise(context);

                    var authContext = services.GetRequiredService <AccountsContext>();
                    authContext.Database.EnsureCreated();
                    authContext.Database.Migrate();
                }
                catch (Exception e)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(e, "A Seeding Error Occured");
                }
            }
            host.Run();
        }
Exemple #7
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.Where(
                    d => ToRemove.Contains(d.ServiceType)).ToList();

                foreach (var d in descriptor)
                {
                    services.Remove(d);
                }

                // Add ApplicationDbContext using an in-memory database for testing.
                services.AddDbContext <CodeGolfContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });
                services.AddSingleton <IGetIp, GetMockIp>();
                services.AddSingleton <IRecaptchaVerifier, MockRecaptchaVerifier>();

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ApplicationDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <CodeGolfContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        DbInitialiser.InitializeDbForTests(db);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(
                            ex,
                            "An error occurred seeding the database with test messages. Error: {Message}",
                            ex.Message);
                    }
                }
            });

            builder.ConfigureAppConfiguration((_, configurationBuilder) =>
                                              configurationBuilder.AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("GitHub:ClientId", "aaa"),
                new KeyValuePair <string, string>("GitHub:ClientSecret", "aaa"),
                new KeyValuePair <string, string>("DbPath", "Data Source=codeGolf.db"),
                new KeyValuePair <string, string>("Execution:UseRemoteService", "false"),
                new KeyValuePair <string, string>("AdminGithubNames:0", "luhis"),
            }));
        }
Exemple #8
0
        public void MockContext()
        {
            var options = new DbContextOptionsBuilder <CheckoutContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            context = new CheckoutContext(options);
            DbInitialiser.Initialize(context);
        }
Exemple #9
0
 private static void CreateDbIfNotExists(IHost host)
 {
     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         var context  = services.GetRequiredService <UserContext>();
         //context.Database.EnsureCreated();
         DbInitialiser.Initialise(context);
     }
 }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.Where(
                    d => ToRemove.Contains(d.ServiceType)).ToList();

                foreach (var d in descriptor)
                {
                    services.Remove(d);
                }

                // Add ApplicationDbContext using an in-memory database for testing.
                services.AddDbContext <MyRentalsContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ApplicationDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <MyRentalsContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        DbInitialiser.InitializeDbForTests(db);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(
                            ex,
                            "An error occurred seeding the database with test messages. Error: {Message}",
                            ex.Message);
                    }
                }
            });

            builder.ConfigureAppConfiguration((_, configurationBuilder) =>
                                              configurationBuilder.AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("DbPath", "Data Source=myRentalsTest.db"),
                new KeyValuePair <string, string>("AdminEmails:0", "*****@*****.**"),
            }));
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
                                    ILoggerFactory loggerFactory, ApplicationDbContext context,
                                    UserManager <ApplicationUser> userManager, IServiceProvider serviceProvider)
        {
            app.UseSession();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

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

            DbInitialiser.Initialise(context);
            await CreateRoles(serviceProvider);

            /*Assign other users to 'Customer' category*/
            ICollection <ApplicationUser> appUsers = context.ApplicationUsers.ToList();

            if (appUsers.Count > 0)
            {
                foreach (var user in appUsers)
                {
                    var roleCount = userManager.GetRolesAsync(user).Result.Count();
                    if (roleCount < 1)//If user doesn't have a role
                    {
                        await userManager.AddToRoleAsync(user, "Customer");
                    }
                }
            }
        }
Exemple #12
0
        //[Test]
        //public void UrlRewriteService_GetAll_ReturnsList()
        //{
        //    var data = UrlRewriteService.GetOptions(_context);

        //    Assert.IsTrue(data.Count > 0);
        //}

        private ApplicationDbContext CreateContext()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "CrowdOrderDatabase").Options;

            // Insert seed data into the database using one instance of the context
            var context = new ApplicationDbContext(options);

            DbInitialiser.Initialize(context);
            return(context);
        }
Exemple #13
0
        public async Task InitDatabaseAndModel()
        {
            var dbContext = GetBastardDBContext();

            bool newModel = await DbInitialiser.Init(dbContext);

            if (newModel)
            {
                await TrainAndPublishNewModel();
            }
        }
Exemple #14
0
        public static IServiceProvider AddDb(this IServiceCollection services)
        {
            services.AddDbContext <CheckoutContext>(options => options.UseInMemoryDatabase("CheckoutDatabaseContext"));

            var serviceProvider = services.BuildServiceProvider();
            var context         = serviceProvider.GetService <CheckoutContext>();

            DbInitialiser.Initialize(context);

            return(serviceProvider);
        }
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context  = services.GetRequiredService <CragLocationContext>();
                DbInitialiser.Initialize(context);
            }

            host.Run();
        }
Exemple #16
0
        private FantasyTraderDataContext GetContext(string methodName)
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();
            var options = new DbContextOptionsBuilder <FantasyTraderDataContext>()
                          .UseSqlite(connection)
                          .Options;
            var context       = new FantasyTraderDataContext(options);
            var dbInitialiser = new DbInitialiser(context, new NullLogger <DbInitialiser>());

            dbInitialiser.Initialize();
            return(context);
        }
Exemple #17
0
 public async Task CanInitializeADatabase()
 {
     using (var cn = GetConnection())
     {
         var init = new DbInitialiser(cn, this.GetType().Assembly);
         await init.InitialiseDatabase();
     }
     using (var cn = GetConnection())
     {
         var init   = new DbInitialiser(cn, this.GetType().Assembly);
         var tables = init.GetTableNames();
         Assert.IsTrue(tables.Contains("Person"));
         Assert.IsTrue(tables.Contains("Stuff"));
     }
 }
        public static async Task Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            // inserting seeding logic here based on
            // https://stackoverflow.com/questions/46222692/asp-net-core-2-seed-database
            using (var scope = host.Services.CreateScope())
            {
                var context = scope.ServiceProvider
                              .GetRequiredService <HolidayContext>();
                await DbInitialiser.Seed(context);
            }

            host.Run();
        }
Exemple #19
0
        public async Task CanModifyATable()
        {
            using (var cn = GetConnection())
            {
                var init = new DbInitialiser(cn, null);
                await init.InitialiseDatabase(new IMigration[] { new Migration201(), new Migration202() });
            }

            using (var cn = GetConnection())
            {
                var init        = new DbInitialiser(cn, null);
                var columnNames = init.GetColumnNames("Person");
                Assert.AreEqual(4, columnNames.Length);
            }
        }
Exemple #20
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.Where(
                    d => ToRemove.Contains(d.ServiceType)).ToList();

                foreach (var d in descriptor)
                {
                    services.Remove(d);
                }

                // Add ApplicationDbContext using an in-memory database for testing.
                services.AddDbContext <AutoTestContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ApplicationDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <AutoTestContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        DbInitialiser.InitializeDbForTests(db);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(
                            ex,
                            "An error occurred seeding the database with test messages. Error: {Message}",
                            ex.Message);
                    }
                }
            });
        }
Exemple #21
0
        public async Task CanSeedADatabase()
        {
            using (var cn = GetConnection())
            {
                var init = new DbInitialiser(cn, null);
                await init.InitialiseDatabase(new IMigration[] { new Migration101() });
            }

            using (var cn = GetConnection())
            {
                var people = cn.Query <Migration101.Person>("SELECT * FROM Person");
                Assert.AreEqual(2, people.Count);
                var stuff = cn.Query <Migration101.Stuff>("SELECT * FROM Stuff");
                Assert.AreEqual(4, stuff.Count);
            }
        }
Exemple #22
0
        private async Task RunAsync()
        {
            var services = ConfigureServices();

            var provider = services.BuildServiceProvider();

            var dbContext = provider.GetRequiredService <CraigBotDbContext>();
            await DbInitialiser.Initialise(dbContext);

            provider.GetRequiredService <ILoggingService>();
            provider.GetRequiredService <ICommandHandler>();

            await provider.GetRequiredService <IStartupService>().StartClient();

            await Task.Delay(-1);
        }
 private static void CreateDbIfNotExists(IHost host)
 {
     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         try
         {
             var context = services.GetRequiredService <ApplicationDbContext>();
             DbInitialiser.Initialise(context);
         }
         catch (Exception ex)
         {
             var logger = services.GetRequiredService <ILogger <Program> >();
             logger.LogError(ex, "An error occurred creating the DB.");
         }
     }
 }
Exemple #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ZipCoContext context)
        {
            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();
            }

            RewriteOptions option = new RewriteOptions();

            option.AddRedirect("^$", "swagger");
            app.UseRewriter(option);

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();

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

            // 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(q =>
            {
                q.SwaggerEndpoint("/swagger/v1/swagger.json", "ZipCo API v1");
            });

            DbInitialiser.Initialise(context);
        }
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <PaymentContext>();
                    DbInitialiser.Initialise(context);
                }
                catch (Exception e)
                { }
            }

            host.Run();
        }
Exemple #26
0
        private static void MigrateAndSeedDatabase(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService <BlimpBotContext>();
                    DbInitialiser.Initialise(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
        public void Initialise_When_Users_Is_Not_Empty_Does_Not_Populate_Users()
        {
            // Arrange
            _quizManagerContext.Users.Add(new User()
            {
                Username = "******", Password = "******", Role = "TestRole"
            });
            _quizManagerContext.SaveChanges();
            _quizManagerContext.Quizzes.Add(new Quiz()
            {
                Title = "The Software Development Lifecycle"
            });
            _quizManagerContext.SaveChanges();
            _quizManagerContext.Questions.Add(new Question()
            {
                QuizId = _quizManagerContext.Quizzes.Single(x => x.Title == "The Software Development Lifecycle").Id, Text = "At which point in the software development lifecycle is a system design document produced?"
            });
            _quizManagerContext.SaveChanges();
            _quizManagerContext.Answers.Add(new Answer()
            {
                QuestionId = _quizManagerContext.Questions.Single(x => x.Text == "At which point in the software development lifecycle is a system design document produced?").Id, Text = "Deployment/implementation."
            });
            _quizManagerContext.SaveChanges();

            var expectedNumberOfUsers     = 1;
            var expectedNumberOfQuizzes   = 1;
            var expectedNumberOfQuestions = 1;
            var expectedNumberOfAnswers   = 1;

            // Act
            DbInitialiser.Initialise(_quizManagerContext);

            var actualNumberOfUsers     = _quizManagerContext.Users.Count();
            var actualNumberOfQuizzes   = _quizManagerContext.Quizzes.Count();
            var actualNumberOfQuestions = _quizManagerContext.Questions.Count();
            var actualNumberOfAnswers   = _quizManagerContext.Answers.Count();

            // Assert
            Assert.AreEqual(expectedNumberOfUsers, actualNumberOfUsers);
            Assert.AreEqual(expectedNumberOfQuizzes, actualNumberOfQuizzes);
            Assert.AreEqual(expectedNumberOfQuestions, actualNumberOfQuestions);
            Assert.AreEqual(expectedNumberOfAnswers, actualNumberOfAnswers);
        }
Exemple #28
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 context = services.GetRequiredService <AppDbContext>();
                    DbInitialiser.Seed(context);
                }
                catch (Exception)
                {
                }
            }

            host.Run();
        }
Exemple #29
0
        public static void Main(string[] args)
        {
            var webHost = BuildWebHost(args);

            using (var scope = webHost.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <QuestionGeneratorContext>();
                    DbInitialiser.Initialise(context);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }

            webHost.Run();
        }
Exemple #30
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

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

                try
                {
                    DbInitialiser.Initialise(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }