Example #1
0
        /// <summary>
        /// Method to see the database. Should not be used in production: demo purposes only.
        /// </summary>
        /// <param name="options">The configured options.</param>
        /// <param name="count">The number of contacts to seed.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        private static async Task SeedDBAsync(DbContextOptions <JASContext> options, int count)
        {
            // empty to avoid logging while inserting (otherwise will flood console)
            var factory = new LoggerFactory();
            var builder = new DbContextOptionsBuilder <JASContext>(options)
                          .UseLoggerFactory(factory);

            using var context = new JASContext(builder.Options);
            // result is true if the database had to be created
            if (await context.Database.EnsureCreatedAsync())
            {
                var issueSeed = new SeedIssues();
                await issueSeed.SeedIssuesAsync(context);
            }

            RelationalDatabaseCreator databaseCreator =
                (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();

            try
            {
                databaseCreator.CreateTables();
            }
            catch (Exception err) { }
            finally
            {
                Debug.WriteLine("Seeding Table");
                var issueSeed = new SeedIssues();
                await issueSeed.SeedIssuesAsync(context);
            }
        }
        public bool EnsureCreated()
        {
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)_orderDatabaseContext.Database.GetService <IDatabaseCreator>();

            databaseCreator.CreateTables();
            return(true);
        }
Example #3
0
 public bool CreateDb()
 {
     try
     {
         _applicationContext.Database.EnsureCreated();
         try
         {
             RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)_applicationContext.Database.GetService <IDatabaseCreator>();
             databaseCreator.CreateTables();
         }
         catch { }
         try
         {
             RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)_storeContext.Database.GetService <IDatabaseCreator>();
             databaseCreator.CreateTables();
         }
         catch { }
         return(true);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Create DB fail!");
         return(false);
     }
 }
Example #4
0
        /// <summary>
        /// Creates necessary database tables and seeds initial data.
        /// </summary>
        private async Task InitializeDatabase()
        {
            using (var context = new MeterReaderContext()) {
                DatabaseFacade            db = context.Database;
                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)db.GetService <IDatabaseCreator>();

                try {
                    databaseCreator.Create();
                }
                catch (Exception e) {
                    // Database already exists
                }
                try {
                    databaseCreator.CreateTables();
                }
                catch (Exception e) {
                    // Tables already exist
                }

                using (StreamReader accountsCsv = new StreamReader(CUSTOMER_CSV_FILE_PATH)) {
                    CustomerAccountCsvParser         csvParser = new CustomerAccountCsvParser();
                    CsvParseResult <CustomerAccount> accounts  = await csvParser.ParseCsvFileAsync(accountsCsv);

                    CustomerAccountDbTableInterface accountsTable = new CustomerAccountDbTableInterface();
                    await accountsTable.InsertEntriesAsync(accounts.Data);
                }
            }
        }
Example #5
0
 static void Main(string[] args)
 {
     if (_createTablesOnStartup)
     {
         try
         {
             TrackerDBContext          db        = new TrackerDBContext();
             RelationalDatabaseCreator dbCreator = (RelationalDatabaseCreator)db.Database.GetService <IDatabaseCreator>();
             dbCreator.CreateTables();
         }
         catch (Exception ex)
         {
             Console.WriteLine("Some of the tables already exist, consider changing CreateTablesOnStartup to false from App.config");
         }
     }
     ResultsTask.Start();
     ImagesTask.Start();
     PreliveTask.Start();
     TeamsTask.Start();
     if (ConfigurationManager.AppSettings["TrackLive"] == "true")
     {
         LiveTask.Start();
     }
     while (true)
     {
     }
 }
Example #6
0
        public static IServiceCollection AddDynamicPageService(this IServiceCollection serviceCollection, CommonDbContext dbContext)
        {
            RelationalDatabaseCreator databaseCreator =
                (RelationalDatabaseCreator)dbContext.Database.GetService <IDatabaseCreator>();

            databaseCreator.CreateTables();

            return(serviceCollection);
        }
        public SchemaBasedContext(DbContextOptions <SchemaBasedContext> options, string schema, bool create)
            : base(options)
        {
            _createState = create;
            Schema       = schema;
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)Database.GetService <IDatabaseCreator>();

            databaseCreator.CreateTables();
        }
Example #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string stage = Environment.GetEnvironmentVariable("STAGE") ?? "dev";

            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService <MQuinceDbContext>();
                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
                if (stage == "test")
                {
                    if (!databaseCreator.HasTables())
                    {
                        context.Database.Migrate();
                    }
                }
            }


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


            app.Use(async(context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = "/public/ErrorPage/ErrorPage.html";
                    await next();
                }
            });

            app.UseCors(builder =>
                        builder.AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowAnyMethod());
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });

            app.UseOcelot().Wait();
        }
Example #9
0
        public MySQLPCFRepository(IServiceProvider serviceProvider)
        {
            _serviceScope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope();
            _db           = _serviceScope.ServiceProvider.GetService <TraceMetadataContext>();

            if (!_db.Database.EnsureCreated())
            {
                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)_db.Database.GetService <IDatabaseCreator>();
            }
        }
Example #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var    context = serviceScope.ServiceProvider.GetRequiredService <MQuinceDbContext>();
                string stage   = Environment.GetEnvironmentVariable("STAGE") ?? "dev";
                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
                if (!databaseCreator.HasTables() && stage == "test")
                {
                    context.Database.Migrate();
                }

                //RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService<IDatabaseCreator>();
                //databaseCreator.CreateTables();
            }

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

            app.UseCors(builder =>
                        builder.AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowAnyMethod());

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseSpaStaticFiles();
            app.UseAuthorization();


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

            app.UseSpa(spa =>
            {
                if (env.IsDevelopment())
                {
                    spa.Options.SourcePath = "ClientApp";
                }
                else
                {
                    spa.Options.SourcePath = "dist";
                }

                if (env.IsDevelopment())
                {
                    spa.UseVueCli(npmScript: "serve");
                }
            });
        }
Example #11
0
        public static void EnsureCreated(OrdersContext context)
        {
            System.Console.WriteLine("Creating database...");
            context.Database.EnsureCreated();
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();

            databaseCreator.CreateTables();


            System.Console.WriteLine("Database and tables' creation complete.....");
        }
Example #12
0
        private DatabaseContext()
        {
            RelationalDatabaseCreator creator = (RelationalDatabaseCreator)Database.GetService <IRelationalDatabaseCreator>();

            try
            {
                creator.CreateTables();
            }catch (Exception e)
            {
            }
        }
Example #13
0
 public DataContext()
 {
     try
     {
         RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)Database.GetService <IRelationalDatabaseCreator>();
         databaseCreator.CreateTables();
     }
     catch (Exception e)
     {
     }
 }
        public DatabaseContextService()
        {
            RelationalDatabaseCreator creator = (RelationalDatabaseCreator)Database.GetService <IRelationalDatabaseCreator>();

            try
            {
                creator.CreateTables();
            }
            catch
            {
            }
        }
Example #15
0
 public void CreateTable(string tablecreate)
 {
     using (var context = new tc_dataCollectionContext())
     {
         context.DBMS             = "MySQL";
         context.ConnectionString = ConnectionString;
         context.Tablename        = tablecreate;
         RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
         databaseCreator.CreateTables();
     }
     Console.WriteLine("table created: " + tablecreate);
 }
Example #16
0
        public static void Main(string[] args)
        {
            if (!File.Exists("Kuivuri.db"))
            {
                using (var db = new KuivuriContext())
                {
                    RelationalDatabaseCreator databaseCreator =
                        (RelationalDatabaseCreator)db.Database.GetService <IDatabaseCreator>();
                    databaseCreator.CreateTables();
                }
            }

            CreateWebHostBuilder(args).Build().Run();
        }
Example #17
0
        public Context2(DbConnection connection) :
            base(TestBase <Context2> .GetContextOptions(connection))
        {
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)Database.GetService <IDatabaseCreator>();

            try
            {
                databaseCreator.CreateTables();
            }
            catch
            {
                // ignored
            }
        }
Example #18
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();
            }
            string stage = Environment.GetEnvironmentVariable("STAGE") ?? "development";
            string host  = Environment.GetEnvironmentVariable("DATABASE_TYPE") ?? "localhost";

            using (var scope = app.ApplicationServices.CreateScope())
                using (var context = scope.ServiceProvider.GetService <RoomDbContext>())
                {
                    RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();

                    try
                    {
                        if (!stage.Equals("development") && host.Equals("postgres"))
                        {
                            databaseCreator.CreateTables();
                        }
                        else
                        {
                            context.Database.Migrate();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Failed to execute migration");
                    }

                    RoomDataSeeder seeder = new RoomDataSeeder();
                    if (!seeder.IsAlreadyFull(context))
                    {
                        seeder.SeedAllEntities(context);
                    }



                    app.UseRouting();

                    app.UseCors("AllowAll");
                    app.UseAuthorization();

                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapControllers();
                    });
                }
        }
Example #19
0
        public SqliteContext(DbContextOptions <SqliteContext> options) : base(options)
        {
            // Ensure database is created, however this does not create tables
            base.Database.Migrate();

            // Create tables in Sqlite Db
            RelationalDatabaseCreator creator = (RelationalDatabaseCreator)base.Database.GetService <IDatabaseCreator>();

            try
            {
                creator.CreateTables();
            }
            catch (SqliteException)
            {
            }
        }
        static async Task Main(string[] args)
        {
            ChallengeContext _context;

            using (DbConnection _connection = new SqliteConnection("Filename=:memory:"))
            {
                _connection.Open();

                _context = new ChallengeContext(new DbContextOptionsBuilder()
                    .UseSqlite(_connection)
                    .Options);
                RelationalDatabaseCreator databaseCreator = 
                    (RelationalDatabaseCreator) _context.Database.GetService<IDatabaseCreator>();
                databaseCreator.CreateTables();

                await SeedDatabaseAsync(_context);
        }
    }
Example #21
0
        private void CheckTable()
        {
            try
            {
                int rows = base.Database.ExecuteSqlCommand(@"SELECT * FROM Users");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");

                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)Database.GetService <IDatabaseCreator>();
                databaseCreator.CreateTables();
            }
            finally
            {
                // Create database if it's not there. This will also ensure the data seeding will happen.
                Database.EnsureCreated();
            }
        }
Example #22
0
 internal static void InitializeMyContexts(IServiceProvider serviceProvider)
 {
     if (serviceProvider == null)
     {
         throw new ArgumentNullException("serviceProvider");
     }
     using (var serviceScope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
     {
         Console.WriteLine("Ensuring database has been created...");
         var db = serviceScope.ServiceProvider.GetService <TestContext>();
         if (!db.Database.EnsureCreated())
         {
             Console.WriteLine("There may be another table in this database already, attempting to create with a workaround");
             RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)db.Database.GetService <IDatabaseCreator>();
             databaseCreator.CreateTables();
         }
     }
     InitializeContext(serviceProvider);
 }
        public IEntityFrameworkBuilder EnableAutoCreation()
        {
            if (_wasMigrated)
            {
                throw new Exception("Can not use EnableAutoCreation with EnableAutoMigrations!");
            }

            if (_wasCreated)
            {
                return(this);
            }

            foreach (var context in _service.GetDbContexts(_plugin))
            {
                if (!context.Database.EnsureCreated())
                {
                    _logger.LogDebug(
                        $"\"{_plugin.Name}\": \"{context.GetType().Name}\" exists already.");
                }
                else
                {
                    _logger.LogDebug($"\"{_plugin.Name}\": \"{context.GetType().Name}\" was created.");
                }

                try
                {
                    RelationalDatabaseCreator databaseCreator =
                        (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
                    databaseCreator.CreateTables();
                }
                catch (Exception e)
                {
                    _logger.LogDebug($"\"{_plugin.Name}\": \"{context.GetType().Name}\" failed to create tables", e);
                }
            }

            _wasCreated = true;
            return(this);
        }
Example #24
0
        public static async Task SeedAsync(IApplicationBuilder applicationBuilder)
        {
            using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <DockerDemoContext>();

                using (context)
                {
                    // Create database if not exists
                    context.Database.Migrate();

                    // Create tables if not exists
                    try
                    {
                        RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
                        databaseCreator.CreateTables();
                    }
                    catch (SqlException ex)
                    {
                        ex.Message.ToString();
                    }

                    // Check if a table has any data
                    if (!context.KhachHang.Any())
                    {
                        context.KhachHang.AddRange(GenerateKhachHangData());

                        await context.SaveChangesAsync();
                    }

                    if (!context.SanPham.Any())
                    {
                        context.SanPham.AddRange(GenerateSanPhamData());

                        await context.SaveChangesAsync();
                    }
                }
            }
        }
Example #25
0
        public static void SeedDatabase(IServiceCollection services)
        {
            var serviceProvider = services.BuildServiceProvider();

            using (var context = new ShopContext(serviceProvider.GetRequiredService <DbContextOptions <ShopContext> >()))
            {
                RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();
                databaseCreator.EnsureCreated();
                if (context.Customers.Any())
                {
                    return;
                }
                context.Customers.AddRange(
                    new Customer
                {
                    FirstName    = "Dare",
                    LastName     = "Osewa",
                    DateCreated  = DateTime.Now,
                    CustomerType = CustomerType.Standard,
                    MobileNumber = "08160613889"
                },
                    new Customer
                {
                    FirstName    = "Dare",
                    LastName     = "Osewa",
                    DateCreated  = DateTime.Now.AddYears(-3),
                    CustomerType = CustomerType.Standard,
                    MobileNumber = "08160613889"
                },
                    new Customer
                {
                    FirstName    = "Tunde",
                    LastName     = "Osewa",
                    DateCreated  = DateTime.Now,
                    CustomerType = CustomerType.Employee,
                    MobileNumber = "08160613889"
                },
                    new Customer
                {
                    FirstName    = "Mary",
                    LastName     = "Ade",
                    DateCreated  = DateTime.Now.AddYears(-1),
                    CustomerType = CustomerType.Affiliate,
                    MobileNumber = "08160613887"
                }
                    );
                context.SaveChanges();

                if (context.Invoices.Any())
                {
                    return;
                }
                context.Discounts.AddRange(
                    new Discount
                {
                    Name        = "Affiliate",
                    Percentage  = "10",
                    DateCreated = DateTime.Now
                },
                    new Discount
                {
                    Name        = "Employee",
                    Percentage  = "30",
                    DateCreated = DateTime.Now
                },
                    new Discount
                {
                    Name        = "CustomerOlderThan2Years",
                    Percentage  = "5",
                    DateCreated = DateTime.Now
                });
                context.SaveChanges();
            }
        }
Example #26
0
        /// <summary>
        /// Verifies the database connection.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Returns an awaitable <see cref="Task"/>.</returns>
        private async Task VerifyDatabaseConnection(CancellationToken cancellationToken)
        {
            try
            {
                Console.WriteLine("Starting database verification..");
                NeuralmDbContext neuralmDbContext = _serviceProvider.GetService <IFactory <NeuralmDbContext> >().Create();
                if (neuralmDbContext.Database.IsInMemory())
                {
                    Console.WriteLine("InMemory database provider found.");
                    neuralmDbContext.Database.EnsureCreated();
                    Console.WriteLine("Ensured that the database is created.");
                    return;
                }

                RelationalDatabaseCreator relationalDatabaseCreator = neuralmDbContext.Database.GetService <IDatabaseCreator>() as RelationalDatabaseCreator;
                if (relationalDatabaseCreator is null)
                {
                    throw new TargetException("The DbProvider is not relational database provider.");
                }

                bool exists = relationalDatabaseCreator.Exists();
                cancellationToken.ThrowIfCancellationRequested();
                Console.WriteLine($"Database {(exists ? "" : "does not ")}exists.");
                if (!exists)
                {
                    relationalDatabaseCreator.Create();
                    Console.WriteLine("Database created.");
                }

                IEnumerable <string> pendingMigrations = neuralmDbContext.Database.GetPendingMigrations().ToList();
                bool hasPendingMigrations = pendingMigrations.Any();
                Console.WriteLine($"Database {(hasPendingMigrations ? "has" : "does not have")} pending migrations.");
                if (hasPendingMigrations)
                {
                    Console.WriteLine("Would you like to clear the database using EnsureDeleted. And, afterwards reapply all migrations? y/n");
                    ConsoleKeyInfo keyInfo = await WaitForReadKey(cancellationToken);

                    cancellationToken.ThrowIfCancellationRequested();
                    if (keyInfo.KeyChar == 'y')
                    {
                        neuralmDbContext.Database.EnsureDeleted();
                        cancellationToken.ThrowIfCancellationRequested();
                        foreach (string migration in neuralmDbContext.Database.GetMigrations())
                        {
                            Console.WriteLine($"\tMigration: {migration}");
                        }
                    }
                    else
                    {
                        foreach (string pendingMigration in pendingMigrations)
                        {
                            Console.WriteLine($"\tPending migration: {pendingMigration}");
                        }
                    }

                    neuralmDbContext.Database.Migrate();
                    cancellationToken.ThrowIfCancellationRequested();
                    Console.WriteLine("Applied the migrations to the database.");
                }

                Console.WriteLine("Finished database verification!");
            }
            catch (Exception e)
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine($"{nameof(VerifyDatabaseConnection)}: {e.Message}");
                    _cancellationTokenSource.Cancel();
                }
                Console.WriteLine("VerifyDatabaseConnection is cancelled.");
            }
        }
Example #27
0
        /// <summary>
        /// 检测关系型数据库是否存在
        /// </summary>
        public static bool ExistsRelationalDatabase(this DbContext context)
        {
            RelationalDatabaseCreator creator = context.Database.GetService <IDatabaseCreator>() as RelationalDatabaseCreator;

            return(creator != null && creator.Exists());
        }
Example #28
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();
            }

            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("AllowAll");

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

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

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Resources")),
                RequestPath = "/Resources"
            });

            string stage = Environment.GetEnvironmentVariable("STAGE") ?? "development";
            string host  = Environment.GetEnvironmentVariable("DATABASE_TYPE") ?? "localhost";

            using (var scope = app.ApplicationServices.CreateScope())
                using (var context = scope.ServiceProvider.GetService <UserDbContext>())
                {
                    RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();


                    try
                    {
                        if (!stage.Equals("development") && host.Equals("postgres"))
                        {
                            databaseCreator.CreateTables();
                        }
                        else
                        {
                            context.Database.Migrate();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Failed to execute migration");
                    }
                    try
                    {
                        UserDataSeeder seeder = new UserDataSeeder();
                        if (!seeder.IsAlreadyFull(context))
                        {
                            seeder.SeedAllEntities(context);
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Failed to seed data");
                    }
                }
        }
Example #29
0
        public MainContext(DbContextOptions <MainContext> options) : base(options)
        {
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)Database.GetService <IDatabaseCreator>();

            databaseCreator.EnsureCreated();
        }
Example #30
0
        private static RelationalDatabaseCreator GetDatabaseCreatorService(T context)
        {
            RelationalDatabaseCreator databaseCreator = (RelationalDatabaseCreator)context.Database.GetService <IDatabaseCreator>();

            return(databaseCreator);
        }