예제 #1
0
        public void Creates_database()
        {
            var settings       = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");

            taskAttributes.RequestedDatabaseAction = RequestedDatabaseAction.Create;
            var mocks         = new MockRepository();
            var queryExecutor = mocks.StrictMock <IQueryExecutor>();
            var executor      = mocks.StrictMock <IScriptFolderExecutor>();
            var taskObserver  = mocks.StrictMock <ITaskObserver>();

            using (mocks.Record())
            {
                queryExecutor.ExecuteNonQuery(settings, "create database [db]");
                taskObserver.Log(string.Format("Run scripts in Create folder."));
                executor.ExecuteScriptsInFolder(taskAttributes, "Create", taskObserver);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor creator = new DatabaseCreator(queryExecutor, executor);
                creator.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new KavaDocsConfiguration();

            Configuration.Bind("KavaDocs", config);
            services.AddSingleton(config);

            KavaDocsConfiguration.Current = config;

            services.AddDbContext <KavaDocsContext>(builder =>
            {
                var connStr = config.ConnectionString;
                if (string.IsNullOrEmpty(connStr))
                {
                    connStr = "server=.;database=KavaDocs; integrated security=true;MultipleActiveResultSets=true";
                }
                //connStr = "";

                builder.UseSqlServer(connStr, opt =>
                {
                    opt.EnableRetryOnFailure();
                    opt.CommandTimeout(15);
                });
            });

            services.AddTransient <UserBusiness>();
            services.AddTransient <RepositoryBusiness>();
            services.AddTransient <OrganizationBusiness>();

            Task.Run(() =>
            {
                // preload data on separate thread if possible
                var ctx = KavaDocsContext.GetKavaDocsContext(config.ConnectionString);
                DatabaseCreator.EnsureKavaDocsData(ctx);
                ctx.Users.Any(p => p.Id == Guid.NewGuid());
            });

            // set up and configure Authentication - make sure to call .UseAuthentication()
            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

            .AddCookie(o =>
            {
                o.LoginPath         = "/account/signin";
                o.LogoutPath        = "/account/signout";
                o.SlidingExpiration = true;
                o.ExpireTimeSpan    = new TimeSpan(2, 0, 0, 0);
            });

            services.AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                opt.SerializerSettings.Converters.Add(new StringEnumConverter()
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                });
            })
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
        }
예제 #3
0
        public static void SetupMirroring(DatabaseInitializerParams param)
        {
            if (!string.IsNullOrEmpty(param.MirroringSharedFolder))
            {
                Console.WriteLine("Add Mirroring on the new Database ...");
                var creatorDb = new DatabaseCreator();

                Console.WriteLine("MirroringSharedFolder :" + param.MirroringSharedFolder);
                var backupFolder = Path.Combine(param.MirroringSharedFolder,
                                                param.CompanyName + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss"));
                Directory.CreateDirectory(backupFolder);

                creatorDb.InitMirroring(param.MasterConnectionString, param.CompanyName);

                var mirrorDbExist = creatorDb.DatabaseExists(param.MirrorMasterConnectionString, param.CompanyName);
                if (mirrorDbExist)
                {
                    Console.WriteLine("Deleting existing mirroring db...");
                    creatorDb.DropDatabase(param.MirrorMasterConnectionString, param.CompanyName, false);
                }

                Console.WriteLine("Backup for mirroring...");
                creatorDb.BackupDatabase(param.MasterConnectionString, backupFolder, param.CompanyName);

                Console.WriteLine("Restoring mirroring backup...");
                creatorDb.RestoreDatabase(param.MirrorMasterConnectionString, backupFolder, param.CompanyName);

                Console.WriteLine("Set Mirroring Partner...");
                creatorDb.SetMirroringPartner(param.MirrorMasterConnectionString, param.CompanyName, param.MirroringMirrorPartner);
                Console.WriteLine("Complete Mirroring...");
                creatorDb.CompleteMirroring(param.MasterConnectionString, param.CompanyName, param.MirroringPrincipalPartner, param.MirroringWitness);
                Console.WriteLine("Mirroring Completed.");
            }
        }
        public static void EnsureDatabaseCreation <TDatabaseContext>(this TDatabaseContext context)
            where TDatabaseContext : GeneralContext
        {
            var databaseCreator = new DatabaseCreator <TDatabaseContext>(context);

            databaseCreator.CreateIfNotExist();
        }
예제 #5
0
 /// <summary>
 ///
 /// </summary>
 protected virtual void CheckAndCreateDatabase()
 {
     if (!DatabaseCreator.IsDatabaseExists())
     {
         DatabaseCreator.CreateDatabase();
     }
 }
예제 #6
0
        public static void MainMenu(DatabaseCreator creator)
        {
            while (true)
            {
                Console.WriteLine("* Database Maintenence *");
                Console.WriteLine("* DBCreator Overwrite Property is {0}", creator.OverwriteExisting.ToString());
                Console.WriteLine("1. Set DBCreator Overwrite Property to TRUE");
                Console.WriteLine("2. Set DBCreator Overwrite Property to FALSE");
                Console.WriteLine("3. Create/update DB schema");
                Console.WriteLine("X. Go Back");
                Console.Write("--> ");

                switch (Console.ReadLine().ToLowerInvariant())
                {
                case "1":
                    creator.OverwriteExisting = true;
                    break;

                case "2":
                    creator.OverwriteExisting = false;
                    break;

                case "3":
                    creator.CreatePokerPalooza();
                    break;

                case "x":
                    return;

                default:
                    Console.WriteLine("gall darn you're a stupid f**k aintcha");
                    continue;
                }
            }
        }
예제 #7
0
        public void Setup()
        {
            Sut = new DatabaseCreator();

            _testFolder =
                Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }
예제 #8
0
        public void CreateTables(SqlEngineVersion version)
        {
            var dd = new TestDatabaseCircular2FK();

            Init(version, dd);
            var creator = new DatabaseCreator(dd, _sqlExecuterTestAdapter.GetExecuter(version.UniqueName));

            creator.ReCreateDatabase(true);
        }
예제 #9
0
        public pokerpalooza()
        {
            Creator = new DatabaseCreator(ConfigurationManager.ConnectionStrings["pokerpalooza-db"].ConnectionString);
            Creator.OverwriteExisting = true;

            Repo       = new pokerpalooza_repo(ConfigurationManager.ConnectionStrings["pokerpalooza-db"].ConnectionString);
            Controller = new GameController(Repo);

            menu();
        }
        public void CreateTables(SqlEngineVersion version)
        {
            var dd = new ForeignKeyComposite();

            Init(version, dd);

            var creator = new DatabaseCreator(dd, _sqlExecuterTestAdapter.GetExecuter(version.UniqueName));

            creator.ReCreateDatabase(true);
        }
        // [SqlVersions(typeof(MsSql2016))]
        //public void CreateTables(SqlVersion version)
        public void CreateTables()
        {
            var version = MsSqlVersion.MsSql2016;
            var dd      = new TestDatabaseUniqueConstraint();

            Init(version, dd);
            var creator = new DatabaseCreator(dd, _sqlExecuterTestAdapter.GetExecuter(version.UniqueName));

            creator.ReCreateDatabase(true);
        }
예제 #12
0
        public TestBase()
        {
            Db = DatabaseCreator.Create();

            Db.CreateTable <Trajectory>();
            Db.CreateTable <Graphic>();
            Db.CreateTable <TrajectoryGraphicRelationalTable>();
            Db.CreateTable <TrajectoryPoint>();
            Db.CreateTable <Geometry>();
            Db.CreateTable <Well>();
        }
예제 #13
0
 public FluentMigratorHandler(FluentMigratorConfiguration configuration,
                              IConnectionStringBuilder connectionStringBuilder,
                              DatabaseCreator databaseCreator,
                              ICommandExecutor commandExecutor)
     : base(configuration)
 {
     _configuration           = configuration;
     _connectionStringBuilder = connectionStringBuilder;
     _databaseCreator         = databaseCreator;
     _commandExecutor         = commandExecutor;
 }
예제 #14
0
    public override void OnInspectorGUI()
    {
        DatabaseCreator t = (DatabaseCreator)target;

        DrawDefaultInspector();

        if (GUILayout.Button("Create Database", GUILayout.MaxWidth(115)))
        {
            t.CreateDataBase(t.dbPath, t.dbName, t.type);
        }
    }
예제 #15
0
 public void CreateDatabase()
 {
     try
     {
         DatabaseCreator.Create(ctx);
     }
     catch (Exception e)
     {
         Assert.Fail(String.Format("CreateMetaDb fails with exception: {0}", e.Message));
     }
 }
예제 #16
0
 public void DropDatabase()
 {
     try
     {
         DatabaseCreator.DropAllTables(ctx);
     }
     catch (Exception e)
     {
         Assert.Fail(String.Format("DropDatabase fails with exception: {0}", e.Message));
     }
 }
예제 #17
0
        protected static void Init(SqlEngineVersion version, DatabaseDefinition dd)
        {
            SqlExecuterTestAdapter.Check(version);
            SqlExecuterTestAdapter.Initialize(version.UniqueName, dd);

            SqlExecuterTestAdapter.GetContext(version).Settings.Options.ShouldUseDefaultSchema = true;

            var databaseCreator = new DatabaseCreator(dd, SqlExecuterTestAdapter.GetExecuter(version.UniqueName));

            databaseCreator.ReCreateDatabase(true);
        }
예제 #18
0
        public static KavaDocsContext GetContext()
        {
            var options = new DbContextOptionsBuilder <KavaDocsContext>()
                          .UseSqlServer(ConnectionString)
                          .Options;

            var ctx = new KavaDocsContext(options);

            DatabaseCreator.EnsureKavaDocsData(ctx);
            return(ctx);
        }
예제 #19
0
        private void InitDatabase()
        {
            DatabaseCreator.CreateQuizzDatabase(StringResources.DbFile);
            var demo         = new Category("Demo");
            var question     = new Question("Demo question", new string[] { "Correct answer", "Alternative 1", "Alternative 2", "Alternative 3" });
            var textQuestion = new Question("This is text question", new string[] { "Accepted answer;separate;correct;answers;by;semicolon" });

            textQuestion.IsFreeText = true;
            QuestionTable.SaveQuestion(textQuestion);
            CategoryQuestionTable.AddCategoryQuestion(demo, question);
        }
예제 #20
0
        public static void AssemblyInit(TestContext context)
        {
            Configuration = new ConfigurationBuilder()
                            .SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
                            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                            .AddJsonFile($"appsettings.Development.json", optional: true)
                            .AddEnvironmentVariables()
                            .Build();

            DatabaseCreator creator = new DatabaseCreator(Configuration);

            creator.CreateDatabase(ConnectionStringName).Wait();
        }
        protected Fixture()
        {
            var config = ConfigLoader.Load("appsettings.tests.json");

            _connectionString = config.GetSection("Database").GetValue <string>("ConnectionString");

            DatabaseCreator.CreateIfNotExists(_connectionString).Wait();
            DatabaseCleanup.ClearDatabase(_connectionString);

            TimeProvider = new MockTimeProvider();

            _host = ApiHost.CreateWebHost(config, services => services.AddSingleton <ITimeProvider>(TimeProvider));
            _host.Start();
        }
예제 #22
0
        public void Start()
        {
            // Create Database
            DatabaseCreator.Create(_config.MasterConnectionString, _config.AppConnectionString);

            // Apply Migrations
            DatabaseMigrator.Migrate(_config.AppConnectionString);

            // Setup Automapper
            Mapper.Initialize(x =>
            {
                x.AddProfile <Mappings>();
            });
            Mapper.AssertConfigurationIsValid();
        }
예제 #23
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 6; i++)
            {
                iDataBase database = DatabaseCreator.Get(i);

                Console.WriteLine("id = {0},  Database = {1}", i, database.getName());
            }
            iDataBase Client = DatabaseCreator.Get(6);

            Console.WriteLine("Client Database : Databese id = {0},  Database Name = {1}", 6, Client.getName());
            Client.CreateTable();
            Client.ShowTable();
            Console.ReadKey();
        }
예제 #24
0
        // GET: Database
        public ActionResult Create(string password)
        {
            if (password != "destruir")
            {
                AddModelError("Contraseña incorrecta");
                return(View("Index"));
            }

            DatabaseCreator.Create();

            CreateStoredProcedures();
            CreateLogTable();


            return(View("IndexMessage", null, "La base de datos se creo con exito"));
        }
예제 #25
0
        /// <summary>
        /// Called when the program is loaded. Performs additional initialization.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            // Make certain we have an application data directory.
            string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            AppDataDirectory = Path.Combine(appDataFolder, DecodeProductName);
            if (!Directory.Exists(AppDataDirectory))
            {
                try {
                    Directory.CreateDirectory(AppDataDirectory);
                } catch (Exception ex) {
                    MessageBox.Show(String.Format("Unable to create application data directory: {0}", ex.Message),
                                    "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Application.Exit();
                }
            }
            // Make certain we have a directory for the database.
            DatabaseCreator.DatabaseFolder = DatabaseConfig.ReadDatabaseFolder();
            if (DatabaseCreator.DatabaseFolder == null)
            {
                DatabaseCreator.DatabaseFolder = ShowDatabaseConfiguration();
            }
            if (DatabaseCreator.DatabaseFolder == null)
            {
                Application.Exit();
            }
            // Make certain that we have a database. If not, create it.
            if (!DatabaseCreator.Exists())
            {
                try {
                    DatabaseCreator.CreateAndInitialize();
                } catch (Exception ex) {
                    string err = String.Format("Unable to coninue: failed to create and initialize the database. {0}",
                                               ex.Message);
                    MessageBox.Show(err, "Fatal Database Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Application.Exit();
                }
            }
            else
            {
                DatabaseCreator.PopulateConstantsMigrate();
            }
            // Load the default filters.
            DecodeFilters.ResultFilters.LoadDefaultFilters();
            // Load whether user-defined states are enabled.
            UserStatesEnabled = UserStatesConfig.ReadUserStateConfig(out UserStatesPath);
        }
        protected static void GenerateDatabase(DatabaseDefinition dd, SqlEngineVersion version, Action action = null)
        {
            _sqlExecuterTestAdapter.Check(version);
            _sqlExecuterTestAdapter.Initialize(version.UniqueName, dd);

            var databaseCreator = new DatabaseCreator(dd, _sqlExecuterTestAdapter.GetExecuter(version.UniqueName));

            try
            {
                databaseCreator.ReCreateDatabase(true);
                action?.Invoke();
            }
            finally
            {
                databaseCreator.CleanupDatabase();
            }
        }
예제 #27
0
 public override void OnFrameworkInitializationCompleted()
 {
     if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
     {
         var databaseAccess          = DatabaseCreator.CreateDatabaseAccess();
         var factory                 = new TodoItemViewFactory(databaseAccess);
         var listViewModel           = new TodoListViewModel(databaseAccess, factory);
         var creationViewModel       = new TodoItemCreationViewModel(databaseAccess);
         var windowControlsViewModel = new WindowControlsViewModel();
         var mainViewModel           = new MainViewModel(listViewModel,
                                                         creationViewModel, windowControlsViewModel);
         var mainWindow = new MainWindowViewModel(mainViewModel);
         desktop.MainWindow = new MainWindow
         {
             DataContext = mainWindow,
         };
     }
     base.OnFrameworkInitializationCompleted();
 }
예제 #28
0
        private IEnumerable <IExecutable> ReCreateDatabaseProcess(BasicScope scope, DatabaseDefinition definition)
        {
            yield return(new CustomAction(scope.Topic, nameof(ReCreateDatabaseProcess))
            {
                Then = proc =>
                {
                    System.Data.SqlClient.SqlConnection.ClearAllPools();

                    proc.Context.Log(LogSeverity.Information, proc, "opening connection to {DatabaseName}", "master");
                    using var connection = DbProviderFactories.GetFactory(TestConnectionString.ProviderName).CreateConnection();
                    connection.ConnectionString = "Data Source=(local);Initial Catalog=\"master\";Integrated Security=SSPI;Connection Timeout=5";
                    connection.Open();

                    try
                    {
                        proc.Context.Log(LogSeverity.Information, proc, "dropping {DatabaseName}", DatabaseName);
                        using var dropCommand = connection.CreateCommand();
                        dropCommand.CommandText = "ALTER DATABASE [" + DatabaseName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE IF EXISTS [" + DatabaseName + "]";
                        dropCommand.ExecuteNonQuery();
                    }
                    catch (Exception)
                    {
                    }

                    proc.Context.Log(LogSeverity.Information, proc, "creating {DatabaseName}", DatabaseName);
                    using var createCommand = connection.CreateCommand();
                    createCommand.CommandText = "CREATE DATABASE [" + DatabaseName + "];";
                    createCommand.ExecuteNonQuery();

                    var dbToolsContext = new Context()
                    {
                        Settings = Helper.GetDefaultSettings(MsSqlVersion.MsSql2016),
                        Logger = new DbTools.Common.Logger.Logger(),
                    };

                    var generator = new MsSql2016Generator(dbToolsContext);
                    var executer = new MsSql2016Executer(TestConnectionString, generator);
                    var creator = new DatabaseCreator(definition, executer);
                    creator.CreateTables();
                }
            });
예제 #29
0
        public void Creates_database()
        {
            var settings       = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");

            var mocks         = new MockRepository();
            var queryExecutor = mocks.CreateMock <IQueryExecutor>();
            var executor      = mocks.CreateMock <IScriptFolderExecutor>();
            var taskObserver  = mocks.CreateMock <ITaskObserver>();

            using (mocks.Record())
            {
                queryExecutor.ExecuteNonQuery(settings, "create database [db]", false);
                executor.ExecuteScriptsInFolder(taskAttributes, "ExistingSchema", taskObserver);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor creator = new DatabaseCreator(queryExecutor, executor);
                creator.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
예제 #30
0
        static void Main(string[] args)
        {
            var db = new DatabaseCreator();

            if (db.DatabaseExists())
            {
                Console.WriteLine("Database already exists!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("Creating database");
            if (args.Length > 0)
            {
                db.CreateProdDb();
            }
            else
            {
                db.CreateTestDevDb();
            }

            Console.WriteLine("Finished!");
            Console.ReadKey();
        }
 private void CreateDatabase()
 {
     var db = new DatabaseCreator(sql);
     db.Create(DatabaseName, TestDatabaseName);
 }
예제 #32
0
            [Fact] // CodePlex 1192
            public void CreateDatabase_throws_if_Migrations_is_configured()
            {
                var creator = new DatabaseCreator(
                    DbConfiguration.DependencyResolver, 
                    new MigrationsChecker(c => true));

                Assert.Equal(
                    Strings.DatabaseInitializationStrategy_MigrationsEnabled("FakeContextProxy"),
                    Assert.Throws<InvalidOperationException>(
                    () => creator.CreateDatabase(CreateMockContextForMigrator().Object, (_, __) => null, null)).Message);
            }