public DbMigratorEventArgs(DbMigrationsConfiguration migrationConfiguration)
        {
            this.MigrationConfiguration = migrationConfiguration;

            DbMigrator migrator = new DbMigrator(migrationConfiguration);
            this.PendingMigrations = migrator.GetPendingMigrations();
            this.CompletedMigrations = migrator.GetDatabaseMigrations();
        }
 public static DbMigrator GetMigrator(TestContext testContext)
 {
     var configuration = new Configuration();
     configuration.TargetDatabase = new DbConnectionInfo("DefaultConnection");
     var migrator = new DbMigrator(configuration);
     return migrator;
 }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>The connection string for the newly created database</returns>
        public static string CreateTestDatabase()
        {
            if (DatabaseTestHelpers.IsLocalDBAvailable() == false)
            {
                throw new InvalidOperationException("Can't create a new test database when localDb is not available");
            }

            string dbPrefix = Guid.NewGuid().ToString().ToLowerInvariant().Substring(0, 30);

            string connString = @"Data Source=(LocalDB)\v11.0;Initial Catalog=" + dbPrefix + @";Integrated Security=True;Connect Timeout=30";

            Console.WriteLine("Using local database: " + connString);

            Stopwatch timer = new Stopwatch();

            timer.Start();

            var migrate = new System.Data.Entity.Migrations.DbMigrator(new TestConfiguration(connString));

            migrate.Update();
            //var dacService = new DacServices(connString);
            //var dacPackage = DacPackage.Load(System.IO.Directory.GetCurrentDirectory() + "\\Client.Database.dacpac");
            //dacService.Deploy(dacPackage, dbPrefix, true, new DacDeployOptions { CreateNewDatabase = true });

            timer.Stop();
            Console.WriteLine("Database setup took {0}s", timer.Elapsed.TotalSeconds);

            return(connString);
        }
Beispiel #4
0
        public static void RegisterAuth()
        {
            var migrator = new DbMigrator(new Configuration());
            migrator.Update();

               if (!WebSecurity.Initialized)
               {
               WebSecurity.InitializeDatabaseConnection("AnunciosDbContext", "UserProfile", "UserId",
                                                       "UserName", autoCreateTables: true);
            }
            // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
            // you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

            //OAuthWebSecurity.RegisterMicrosoftClient(
            //    clientId: "",
            //    clientSecret: "");

            //OAuthWebSecurity.RegisterTwitterClient(
            //    consumerKey: "",
            //    consumerSecret: "");

            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "",
            //    appSecret: "");

            //OAuthWebSecurity.RegisterGoogleClient();
        }
Beispiel #5
0
        private static void RunUpdate(string connectionName)
        {
            Console.WriteLine("RUNNING MIGRATIONS FOR CONNECTION NAME: " + connectionName);

            var configuration = new Configuration();

            configuration.TargetDatabase =
                new DbConnectionInfo(connectionName);

            try
            {
                Console.WriteLine("TRYING...");
                var migrator = new DbMigrator(configuration);

                migrator.Update();
                Console.WriteLine("SUCCESS!");
                ExitCode = 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine("EXCEPTION:");
                Console.WriteLine(ex.Message);
                Console.WriteLine("FAILURE!");
            }

            Console.WriteLine("DONE!");
            Environment.Exit(ExitCode);
        }
        public static void ConfigureMobileApp(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686
            config.EnableSystemDiagnosticsTracing();

            new MobileAppConfiguration().UseDefaultConfiguration().ApplyTo(config);

            // Use Entity Framework Code First to create database tables based on your DbContext
            // Database.SetInitializer(new mouselightInitializer());
            var migrator = new DbMigrator(new Janelia.Mouse.Mobile.Server.Migrations.Configuration());
            migrator.Update();

            // To prevent Entity Framework from modifying your database schema, use a null database initializer
            // Database.SetInitializer<MouseLightContext>(null);

            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            if (string.IsNullOrEmpty(settings.HostName))
            {
                // This middleware is intended to be used locally for debugging. By default, HostName will
                // only have a value when running in an App Service application.
                app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
                {
                    SigningKey = ConfigurationManager.AppSettings["SigningKey"],
                    ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                    ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                    TokenHandler = config.GetAppServiceTokenHandler()
                });
            }

            app.UseWebApi(config);
        }
Beispiel #7
0
        private static void RunMigrations()
        {
            var efMigrationSettings = new ShippingExpress.Domain.Migrations.Configuration();
            var efMigrator = new DbMigrator(efMigrationSettings);

            efMigrator.Update();
        }
Beispiel #8
0
        public static void Main(string[] args)
        {
            Console.WriteLine(@"Migrating database...");
            var migrator = new DbMigrator(new Configuration());
            Console.WriteLine(@"Connection: " + GetConnectionString(migrator));

            var migrations = migrator.GetPendingMigrations().ToList();

            if (!migrations.Any()) {
                Console.WriteLine(@"No pending migrations.");
            } else {
                foreach (var migration in migrations) {
                    Console.WriteLine(migration);
                    migrator.Update(migration);
                }
            }

            if (args.Contains("--seed")) {
                Console.WriteLine(@"Seeding the database...");
                var context = new EntityContext();

                DatabaseSeeder.Seed(context);

                context.SaveChanges();
            } else {
                Console.WriteLine(@"No seeding required.");
            }
            Console.WriteLine(@"Migration done.");
        }
        public void InitializeDatabase()
        {
            var configuration = new Configuration();

            var migrator = new DbMigrator(configuration);
            migrator.Update();
        }
Beispiel #10
0
        public QueueFixture()
        {
            try
            {
                var configuration = new DbMigrationsConfiguration
                {
                    ContextType = typeof(QueueDataContext),
                    MigrationsAssembly = typeof(QueueDataContext).Assembly,
                    TargetDatabase = new DbConnectionInfo("QueueDataContext"),
                    MigrationsNamespace = typeof(InitialCreate).Namespace,
                    AutomaticMigrationDataLossAllowed = true
                };

                var migrator = new DbMigrator(configuration);
                //Update / rollback to "MigrationName"
                migrator.Update("0");
                migrator.Update();
                _sut = new SqlQueueImpl(new Infrastructure.DatabaseContextFactory());
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached) Debugger.Break();
                Console.WriteLine(ex);
                throw;
            }
        }
Beispiel #11
0
        private static void RunMigrations()
        {
            var efMigrationSettings = new HomeManager.Domain.Migrations.Configuration();
            var efMigrator = new DbMigrator(efMigrationSettings);

            efMigrator.Update();
        }
        protected void Application_Start()
        {
            var connString = ConfigurationManager.ConnectionStrings["BlogContext"];
            string commandText = @"
            CREATE TABLE [__MigrationHistory] (
            [Id] [uniqueidentifier] DEFAULT newid(),
            [Migration] [nvarchar](255) NOT NULL,
            [CreatedOn] [datetime] NOT NULL,
            [Hash] [binary](32) NOT NULL,
            [Model] [varbinary](max) NOT NULL,
            PRIMARY KEY ([Id])
            );
            ";
            using (var connection = new SqlConnection(connString.ConnectionString)) {
                using (var command = new SqlCommand(commandText, connection)) {
                    connection.Open();
                    try {
                        command.ExecuteNonQuery();
                    }
                    catch {
                    }
                }
            }

            var dbMigrator = new DbMigrator(new MvcApplicationCodeFirst.Migrations.Settings());
            dbMigrator.Update();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
        public void InitializeDatabase(TContext context)
        {
            var migrationConfig = CreateMigrationConfig(context);
            var migrator        = new System.Data.Entity.Migrations.DbMigrator(migrationConfig);

            EnsureAllExplicitMigrationsAddedAndMigrate(context, migrator);
        }
Beispiel #14
0
        protected void Application_Start()
        {
            var migrator = new DbMigrator(new Configuration());
            migrator.Configuration.AutomaticMigrationDataLossAllowed = true;
            migrator.Update();

            //Database.SetInitializer<ApplicationDbContext>(new AppDbInitializer());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            BundleMobileConfig.RegisterBundles(BundleTable.Bundles);
            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iphone")
            {
                ContextCondition = Context =>
                                Context.Request.Browser["HardwareModel"] == "iPhone"
            });

            DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("android")
            {
                ContextCondition = Context =>
                                Context.Request.Browser["PlatformName"] == "Android"
            });

            DisplayModeProvider.Instance.Modes.Insert(2, new DefaultDisplayMode("mobile")
            {
                ContextCondition = Context =>
                                Context.Request.Browser["IsMobile"] == "True"
            });
        }
Beispiel #15
0
        public static void Run()
        {
            ConsoleLogger.Information("Installing Database");
            using (var context = new DataContext())
            {
                try
                {
                    ConsoleLogger.Information("  Dropping database...");
                    context.Database.Delete();
                }
                catch (Exception ex)
                {
                    ConsoleLogger.Error("  Error: Could not drop database! " + ex);
                }

                try
                {
                    ConsoleLogger.Information("  Creating database...");
                    var migrator = new DbMigrator(new ClaimDbConfiguration());
                    migrator.Update();
                }
                catch (Exception ex)
                {
                    ConsoleLogger.Error("  Error: Could not create database! " + ex);
                }
            }

            ConsoleLogger.Information("Database Installed!");
        }
 public static string CreateScriptFromMigration()
 {
     var migrationConfig = new Configuration();
     var migrator = new DbMigrator(migrationConfig);
     var scriptor = new MigratorScriptingDecorator(migrator);
     return scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
 }
Beispiel #17
0
        static void Main(string[] args)
        {
            var configuration = new DbMigrationsConfiguration
            {
                AutomaticMigrationsEnabled        = true,
                AutomaticMigrationDataLossAllowed = true,
                ContextType         = typeof(ToDoAppContext),
                MigrationsAssembly  = Assembly.GetExecutingAssembly(),
                MigrationsNamespace = "ToDoApp.Entity.Context",
                TargetDatabase      = new DbConnectionInfo("ToDoAppContext")
            };

            try
            {
                var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
                migrator.Update();
                Console.WriteLine("All databases have been migrated.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occured during migration of host database.");
                Console.WriteLine("Exception Message: " + ex.Message);
            }
            Console.ReadKey();
        }
 public static void GenerateSqlUsingDbMigrator()
 {
     using (var context = new AdventureWorksContext())
     {
         var configuration = new Configuration
             {
                 ContextType = typeof(AdventureWorksContext),
                 TargetDatabase =
                     new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient")
             };
         var migrator = new DbMigrator(configuration);
         var migrations = migrator.GetDatabaseMigrations();
         if (migrations.Any())
         {
             var scriptor = new MigratorScriptingDecorator(migrator);
             string script = scriptor.ScriptUpdate(null, migrations.Last());
             if (!String.IsNullOrEmpty(script))
             {
                 Console.WriteLine(script);
                 //context.Database.ExecuteSqlCommand(script);
             }
         }                
         
         Console.ReadKey();
     }
 }
Beispiel #19
0
 public MainContext(string connectionString)
     : base(connectionString)
 {
     ConnectionString = connectionString;
     _Migrator = new DbMigrator(this.GetDbMigrationsConfiguration());
     logger = NLog.LogManager.GetCurrentClassLogger();
 }
        /// <summary>
        /// Initializes the database.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <inheritdoc />
        public virtual void InitializeDatabase(TContext context)
        {
            if (_config == null)
            {
                _config = new TMigrationsConfiguration
                {
                    TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient")
                };
            }

            var migrator = new System.Data.Entity.Migrations.DbMigrator(_config);
            var pending  = migrator.GetPendingMigrations().Count();
            var local    = migrator.GetLocalMigrations().Count();
            var exists   = context.Database.Exists();

            if (!exists || pending > 0)
            {
                try
                {
                    migrator.Update();
                }
                catch (SqlException ex)
                {
                    throw new ApplicationException($"Migrations failed with error \"{ex.ExpandExceptionMessage()}\"", ex);
                }

                InitializeDbSettings(context);

                if (pending == local)
                {
                    Seed(context);
                }
            }
        }
        private static void RunMigrations() {

            var efMigrationSettings = new PingYourPackage.Domain.Migrations.Configuration();
            var efMigrator = new DbMigrator(efMigrationSettings);

            efMigrator.Update();
        }
        private static void UpdateDb()
        {
            var settings = new Configuration();
            var migrator = new DbMigrator(settings);

            migrator.Update();
        }
        /// <summary>
        /// Creates a new database file at the specified path with the specified file name.
        /// The ".sdf" extension will be added to the file. Do not pass it in the file name.
        /// </summary>
        /// <param name="databaseFilePath">The path to the file, excluding the file's name</param>
        /// <param name="databaseFileName">The name of the new database file. Exclude the .sdf extension - it will be added automatically.</param>
        /// <param name="changeApplicationConnection">If true, the application's connection will be changed to this new database.</param>
        /// <returns>Returns the full path to the database file.</returns>
        public string CreateNewDatabase(string databaseFilePath, string databaseFileName, bool changeApplicationConnection)
        {
            string fullPath = databaseFilePath + "\\" + databaseFileName + ".sdf";
            string connectionString;

            // Update connection settings and the active module directory path
            if (changeApplicationConnection)
            {
                ChangeDatabaseConnection(fullPath);
                WinterConnectionInformation.ActiveModuleDirectoryPath = fullPath;
                connectionString = WinterConnectionInformation.ActiveConnectionString;
            }
            // Otherwise we're simply creating a new database file. Build a connection string.
            else
            {
                connectionString = BuildConnectionString(fullPath);
            }

            // Initialize the database - will create the database file at the specified location.
            // Also creates tables based on the code-first model.
            using (ModuleDataContext context = new ModuleDataContext(connectionString))
            {
                DbMigrator migrator = new DbMigrator(new ModuleDataContextMigrationConfiguration());
                migrator.Update();
            }

            return fullPath;
        }
Beispiel #24
0
        public string Run(string from, string to)
        {
            var configuration = new Configuration();

            //Can set the Target Database to be in another Server or Environment
            //configuration.TargetDatabase =
            //    new DbConnectionInfo("Server=.;Database=Investment;Trusted_Connection=True;",
            //        "System.Data.SqlClient");

            //var context = (InvestmentContext)Activator.CreateInstance(configuration.ContextType);
            var runUpdate = false;

            var migrator = new DbMigrator(configuration);

            var scriptor = new MigratorScriptingDecorator(migrator);
            var sql = scriptor.ScriptUpdate("", "");
            //var sql = scriptor.ScriptUpdate("Name-Of-Source-Migration", "Name-Of-Target-Migration");
            //configuration.RunSeedProcess(context);

            if (runUpdate)
            {
                //Can run the update from here
                migrator.Update(); //Could add a "TargetMigration"
            }

            return sql;
        }
 public void TestInitialize()
 {
     userManager = new UserManager(new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest)) );
     var migratorConfig = new UI.Web.MVC.Migrations.Configuration();
     migratorConfig.TargetDatabase = new DbConnectionInfo(ContextEnum.BeatBuddyTest.ToString());
     var dbMigrator = new DbMigrator(migratorConfig);
     dbMigrator.Update();
 }
Beispiel #26
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var migrator = new DbMigrator(new Configuration());
            migrator.Update();
        }
        public void FixtureTeardown()
        {
            // Return the database back to pre-first migration state
            var configuration = new Veil.DataAccess.Migrations.Configuration();
            var migrator = new DbMigrator(configuration);

            migrator.Update("0"); // 0 is equivalent to undoing all migrations
        }
Beispiel #28
0
        private void InitialiseDataBase()
        {
            var migrator = new DbMigrator(new DataLayer.Migrations.Configuration());
            migrator.Update();

            if (!WebSecurity.Initialized)
            WebSecurity.InitializeDatabaseConnection("NavasthalaContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
        }
Beispiel #29
0
 private static void UpdateDatabase()
 {
     var dbMigrator = new DbMigrator(new Settings());
     dbMigrator.Update();
     // The Seed method of Settings is never called, so 
     // we call it here again as a workaround.
     Settings.SeedDatabase(new EntitiesContext());
 }
 public void TestInitialize()
 {
     _accountController = new AccountController(ContextEnum.BeatBuddyTest);
     var migratorConfig = new Migrations.Configuration();
     migratorConfig.TargetDatabase = new DbConnectionInfo(ContextEnum.BeatBuddyTest.ToString());
     var dbMigrator = new DbMigrator(migratorConfig);
     dbMigrator.Update();
 }
        public void FixtureSetup()
        {
            // Migrate the database to the most current migration
            var configuration = new Veil.DataAccess.Migrations.Configuration();
            var migrator = new DbMigrator(configuration);

            migrator.Update();
        }
 private static void DbMigratorPostStart()
 {
     var dbMigrator = new DbMigrator(new MigrationsConfiguration());
     // After upgrading to EF 4.3 and MiniProfile 1.9, there is a bug that causes several 
     // 'Invalid object name 'dbo.__MigrationHistory' to be thrown when the database is first created; 
     // it seems these can safely be ignored, and the database will still be created.
     dbMigrator.Update();
 }
Beispiel #33
0
        public void MigrateIdentity()
        {
            var migrateConifg = new  Resume.IdentityMigrations.Configuration();
            var migrator = new DbMigrator(migrateConifg);
            var script = new MigratorScriptingDecorator(migrator);

            script.ScriptUpdate(DbMigrator.InitialDatabase, null);
        }
        protected void Application_Start()
        {
            WebApiConfig.Register();

            var configuration = new Migrations.Configuration();
            var migrator = new DbMigrator(configuration);
            migrator.Update();
        }
Beispiel #35
0
        /// <summary>
        /// 更新数据库
        /// </summary>
        public static bool UpdateDBToLast()
        {
            bool result = false;

            try
            {
                var m = new System.Data.Entity.Migrations.DbMigrator(new Configuration()
                {
                    TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(ConnectionString.connectionString, "System.Data.SqlClient")
                });
                m.Update();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }
            return(result);
        }
Beispiel #36
0
        public void Application_Start()
        {
            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<VeriTabanı, MvcProjem.Models.VeriTabanı.Configuration>("MvcProjemConnectionString"));
            using (var vt = new VeriTabanı())
            {
                if (vt.Database.Exists())
                {
                    DbMigrator migrator = new System.Data.Entity.Migrations.DbMigrator(new Configuration());
                    migrator.Update();
                }
                else
                {
                    vt.Database.Create();
                }
            }
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
Beispiel #37
0
        public void Can_upgrade_from_5_and_existing_code_migrations_still_work()
        {
            ResetDatabase();

            var migrationsConfiguration
                = new Ef5MigrationsConfiguration
                {
                TargetDatabase
                    = new DbConnectionInfo(ConnectionString, TestDatabase.ProviderName)
                };

            var migrator = new DbMigrator(migrationsConfiguration);

            migrator.Update();

            Assert.True(TableExists("dbo.Blogs"));
            Assert.True(TableExists("dbo." + HistoryContext.DefaultTableName));

            migrator.Update("0");

            Assert.False(TableExists("dbo.Blogs"));
            Assert.False(TableExists("dbo." + HistoryContext.DefaultTableName));
        }
Beispiel #38
0
 private static void FillInForeignKeyOperations(
     IEnumerable <MigrationOperation> operations,
     XDocument targetModel)
 {
     foreach (AddForeignKeyOperation foreignKeyOperation1 in operations.OfType <AddForeignKeyOperation>().Where <AddForeignKeyOperation>((Func <AddForeignKeyOperation, bool>)(fk =>
     {
         if (fk.PrincipalTable != null)
         {
             return(!fk.PrincipalColumns.Any <string>());
         }
         return(false);
     })))
     {
         AddForeignKeyOperation foreignKeyOperation = foreignKeyOperation1;
         string principalTable = DbMigrator.GetStandardizedTableName(foreignKeyOperation.PrincipalTable);
         string entitySetName  = targetModel.Descendants(EdmXNames.Ssdl.EntitySetNames).Where <XElement>((Func <XElement, bool>)(es => new DatabaseName(es.TableAttribute(), es.SchemaAttribute()).ToString().EqualsIgnoreCase(principalTable))).Select <XElement, string>((Func <XElement, string>)(es => es.NameAttribute())).SingleOrDefault <string>();
         if (entitySetName != null)
         {
             targetModel.Descendants(EdmXNames.Ssdl.EntityTypeNames).Single <XElement>((Func <XElement, bool>)(et => et.NameAttribute().EqualsIgnoreCase(entitySetName))).Descendants(EdmXNames.Ssdl.PropertyRefNames).Each <XElement>((Action <XElement>)(pr => foreignKeyOperation.PrincipalColumns.Add(pr.NameAttribute())));
         }
         else
         {
             CreateTableOperation createTableOperation = operations.OfType <CreateTableOperation>().SingleOrDefault <CreateTableOperation>((Func <CreateTableOperation, bool>)(ct => DbMigrator.GetStandardizedTableName(ct.Name).EqualsIgnoreCase(principalTable)));
             if (createTableOperation == null || createTableOperation.PrimaryKey == null)
             {
                 throw Error.PartialFkOperation((object)foreignKeyOperation.DependentTable, (object)foreignKeyOperation.DependentColumns.Join <string>((Func <string, string>)null, ", "));
             }
             createTableOperation.PrimaryKey.Columns.Each <string>((Action <string>)(c => foreignKeyOperation.PrincipalColumns.Add(c)));
         }
     }
 }