public static void RunMigrations()
        {
            var migrator   = new Configuration();
            var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(migrator);

            dbMigrator.Update();
        }
        /// <summary>
        /// Migrates the database.
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public bool MigrateDatabase(RockContext rockContext)
        {
            bool result = false;

            // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so it doesn't try to do anything special
            Database.SetInitializer <Rock.Data.RockContext>(null);

            var fileInfo = new FileInfo(Server.MapPath("~/App_Data/Run.Migration"));

            if (fileInfo.Exists)
            {
                // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration
                var migrator          = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
                var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a);
                if (pendingMigrations.Any())
                {
                    LogMessage(APP_LOG_FILENAME, "Migrating Database...");

                    var lastMigration = pendingMigrations.Last();

                    // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes
                    migrator.Update(lastMigration);
                    result = true;
                }

                fileInfo.Delete();
            }

            return(result);
        }
        /// <summary>
        /// If EF migrations need to be done, does MF Migrations on the database
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public static bool MigrateDatabase(bool hasPendingEFMigrations)
        {
            if (!hasPendingEFMigrations)
            {
                return(false);
            }

            // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration
            var migrator          = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
            var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a);

            // double check if there are migrations to run
            if (pendingMigrations.Any())
            {
                LogStartupMessage("Migrating Database...");

                var lastMigration = pendingMigrations.Last();

                // create a logger, but don't enable any of the logs
                var migrationLogger = new Rock.Migrations.RockMigrationsLogger()
                {
                    LogVerbose = false, LogInfo = false, LogWarning = false
                };

                var migratorLoggingDecorator = new MigratorLoggingDecorator(migrator, migrationLogger);

                // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes
                migratorLoggingDecorator.Update(lastMigration);
                return(true);
            }

            return(false);
        }
Exemple #4
0
        public static void MigrateDbToLatest()
        {
            var configuration = new MyGenericUnitOfWork.Migrations.Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            migrator.Update();
        }
 private void CustomMigration(string key, System.Data.Entity.Migrations.DbMigrator migrator,
                              Migrations.Configuration config, AtlanticDXContext context)
 {
     //migrator.Update(key);
     ////var config = new AtlanticDX.ERP.Migrations.Configuration();
     //if (this.GetForceExternalSeedingFromConfig())
     config.SeedExternal(context, key);
 }
 public ActionResult DropSchema()
 {
     //Sistrategia.Drive.Data.DatabaseManager.DropSchema();
     var configuration = new Migrations.Configuration();
     var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
     migrator.Update("0");
     return Redirect("~/Dev");
 }
Exemple #7
0
        public void Initialize()
        {
            var migrator = new System.Data.Entity.Migrations.DbMigrator(new Migrations.Configuration());
            migrator.Update();

            Mapper.Reset();
            Mapper.CreateMap<Order, OrderDto>()
                .ForMember(dest => dest.OrderId, opt => opt.MapFrom(src => src.Id));
        }
Exemple #8
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var migrator = new System.Data.Entity.Migrations.DbMigrator(new Configuration());

            migrator.Update();
        }
Exemple #9
0
        private static void InitializeDataStore()
        {
            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GalleryDb, GalleryDbMigrationConfiguration>());

            var configuration = new GalleryDbMigrationConfiguration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }
        }
Exemple #10
0
        public ApplicationDbContext(string connectionString) : base(connectionString)
        {
            _connection = connectionString;
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <ApplicationDbContext, Configuration>());
            var configuration = new Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var migratorConfig = new Services.Migrations.Configuration();
            var dbMigrator     = new System.Data.Entity.Migrations.DbMigrator(migratorConfig);

            dbMigrator.Update();
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var migratorConfig = new Services.Migrations.Configuration();
            var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(migratorConfig);
            dbMigrator.Update();

        }
Exemple #13
0
        public void InitializeDatabase(TContext context)
        {
            if (!context.Database.Exists())
            {
                context.Database.CreateIfNotExists();
            }
            else
            {
                // this is either
                // -an old database with no history table, or
                // -a new table that has a history table

                //context.Database.CompatibleWithModel(true);
                // no metadata found in table because there is no history table
                // "Model compatibility cannot be checked because the database does not contain model metadata.
                //  Model compatibility can only be checked for databases created using Code First or Code First Migrations."

                if (IsOldDBWithoutHistoryTable(context))
                {
                    try
                    {
                        // add the MigrationHistory table and the initial row
                        RunDBTransaction(CON_SQL_Add_MigrationHistory_Table);
                        RunDBTransaction(CON_SQL_Add_InitialRow_MigrationHistory);
                    }
                    catch (Exception ex)
                    {
                        string s = ex.InnerException.Message;
                        throw;
                    }
                    //Initial initialMigration = new Initial();
                    //initialMigration.IsOldFileWithoutMigrationHistory = true;
                    //initialMigration.Up();
                }

                // see  https://galleryserverpro.com/using-entity-framework-code-first-migrations-to-auto-create-and-auto-update-an-application/
                // change first the DB conn string to SQL server express
                // then run the package manager with command: Add-Migration myMigrationName
                Configuration cf       = new Configuration();
                var           migrator = new System.Data.Entity.Migrations.DbMigrator(cf);
                if (migrator.GetPendingMigrations().Any())
                {
                    migrator.Update();
                }
            }


            // Do you want to migrate to latest in your initializer? Add code here!
            // Do you want to seed data in your initializer? Add code here!
        }
Exemple #14
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            MapperRegister.Register();

            var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(
                new MyPegasus.DataAccess.Migrations.Configuration());

            dbMigrator.Update();
        }
Exemple #15
0
 static DataContext()
 {
     try
     {
         Database.SetInitializer(new MigrateDatabaseToLatestVersion <DataContext, Configuration>());
         var migrator = new System.Data.Entity.Migrations.DbMigrator(new Configuration());
         if (migrator.GetPendingMigrations().Any())
         {
             migrator.Update();
         }
     }
     catch (System.Exception ex)
     {
     }
 }
Exemple #16
0
        private static void InitData(IUnityContainer container)
        {
            Database.SetInitializer(
                new MigrateDatabaseToLatestVersion <ShortenerContext,
                                                    MirationConfiguration>()
                );

            var configuration = new MirationConfiguration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }
        }
        public static void Init()
        {
            //configure app domain
            AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory);

            //create or update db with lates migrations
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <FuhrerContext, Migrations.Configuration>());

            var configuration = new Migrations.Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }
        }
Exemple #18
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new Migrations.Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            migrator.Update();

            AutoMapperLimbsConfig.Configure();

            ConfigureLocalization();
            ConfigureAuth(app);
            ConfigureServices(app);

            FullStorageInitializer.Initialize();
            MailTemplatesRegistration.Initialize();
        }
Exemple #19
0
        private void InitializeDataStore()
        {
            if (V4SchemaUpdateRequired)
            {
                DbManager.ChangeNamespaceForVersion4Upgrade(ProviderDataStore, V4SchemaUpdateRequiredFilePath);
            }

            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GalleryDb, GalleryDbMigrationConfiguration>());

            var configuration = new GalleryDbMigrationConfiguration(ProviderDataStore);
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
                Factory.ValidateGalleries();
            }
        }
Exemple #20
0
        private static void InitializeDataStore()
        {
            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <FlightAvailability.Models.FlightContext,
                                                                                                              FlightAvailability.Migrations.Configuration>());

            var configuration = new FlightAvailability.Migrations.Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                System.Diagnostics.Debug.WriteLine("Running migrations against database");
                migrator.Update();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("There no database schema changes");
            }
        }
Exemple #21
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            using (var db = new MOE.Common.Models.SPM())
            {
                if (!db.Database.Exists())
                {
                    db.Database.Initialize(true);
                    var config   = new MOE.Common.Migrations.Configuration();
                    var migrator = new System.Data.Entity.Migrations.DbMigrator(config);
                    migrator.Update();
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var migrator = new System.Data.Entity.Migrations.DbMigrator(new Migrations.Configuration());

            migrator.Update();

            string yolo = Request.QueryString["yolo"];

            if (yolo == "hi")

            {
                throw new Exception();
            }

            var cid = -1;

            if (Page.IsPostBack)
            {
                cid = int.Parse(CustomerId.Value);
            }
            using (var ctx = new ContextDB())
            {
                var orders = ctx.Orders
                             .Take(5)
                             .ToList();

                orderList.DataSource = orders;
                orderList.DataBind();

                if (cid == -1)
                {
                    var defaultCustomer = ctx.Customers.FirstOrDefault();
                    MapCustomer(defaultCustomer);
                }
                else
                {
                    var customer = ctx.Customers.Single(c => c.CustomerId == cid);
                    MapCustomer(customer);
                }
            }

            lblCheckbox.Attributes.Add("for", EnrollCheckbox.ClientID);
        }
Exemple #23
0
        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 XamarinLOBFormInitializer());

            #region 這裡是自行修正的程式碼
            // Use Entity Framework Code First to create database tables based on your DbContext
            // 請註解底下這行程式碼,因為,我們要使用接下來的兩行程式碼來取代
            //Database.SetInitializer(new XamarinLOBFormInitializer());

            var migrator = new System.Data.Entity.Migrations.DbMigrator(new Migrations.Configuration());
            migrator.Update();
            #endregion

            // To prevent Entity Framework from modifying your database schema, use a null database initializer
            // Database.SetInitializer<XamarinLOBFormContext>(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);
        }
Exemple #24
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DSEntities, MonlithDS.DAL.Migrations.Configuration>());

            //Update the DB as required
            var configuration = new MonlithDS.DAL.Migrations.Configuration();
            var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }

            //Database.SetInitializer<DSEntities>(null);
            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());
        }
Exemple #25
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer(new MigrateDatabaseToLatestVersion <DSEntities, MonlithDS.DAL.Migrations.Configuration>());

            //Update the DB as required
            var configuration = new MonlithDS.DAL.Migrations.Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }

            //Database.SetInitializer<DSEntities>(null);
            ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());
        }
Exemple #26
0
        /// <summary>
        /// Migrates the database.
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public bool MigrateDatabase(RockContext rockContext)
        {
            bool result = false;

            var fileInfo = new FileInfo(Server.MapPath("~/App_Data/Run.Migration"));

            if (fileInfo.Exists)
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion <Rock.Data.RockContext, Rock.Migrations.Configuration>());

                // explictly check if the database exists, and force create it if doesn't exist
                if (!rockContext.Database.Exists())
                {
                    // If database did not exist, initialize a database (which runs existing Rock migrations)
                    rockContext.Database.Initialize(true);
                    result = true;
                }
                else
                {
                    // If database does exist, run any pending Rock migrations
                    var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
                    if (migrator.GetPendingMigrations().Any())
                    {
                        LogMessage(APP_LOG_FILENAME, "Migrating Database...");

                        migrator.Update();
                        result = true;
                    }
                }

                fileInfo.Delete();
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer <Rock.Data.RockContext>(null);
            }

            return(result);
        }
Exemple #27
0
 public static void AfterTestRun()
 {
     var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new MeAnota.Migrations.Configuration());
     dbMigrator.Update("ModeloInicial");
 }
Exemple #28
0
        /// <summary>
        /// Migrates the database.
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public bool MigrateDatabase( RockContext rockContext )
        {
            bool result = false;

            var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) );
            if ( fileInfo.Exists )
            {
                Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() );

                // explictly check if the database exists, and force create it if doesn't exist
                if ( !rockContext.Database.Exists() )
                {
                    // If database did not exist, initialize a database (which runs existing Rock migrations)
                    rockContext.Database.Initialize( true );
                    result = true;
                }
                else
                {
                    // If database does exist, run any pending Rock migrations
                    var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                    if ( migrator.GetPendingMigrations().Any() )
                    {
                        migrator.Update();
                        result = true;
                    }
                }

                fileInfo.Delete();
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer<Rock.Data.RockContext>( null );
            }

            // Migrate any plugins that have pending migrations
            List<Type> migrationList = Rock.Reflection.FindTypes( typeof( Migration ) ).Select( a => a.Value ).ToList();

            // If any plugin migrations types were found
            if ( migrationList.Any() )
            {
                // Create EF service for plugin migrations
                var pluginMigrationService = new PluginMigrationService( rockContext );

                // Get the current rock version
                var rockVersion = new Version( Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );

                // Create dictionary for holding migrations specific to an assembly
                var assemblies = new Dictionary<string, Dictionary<int, Type>>();

                // Iterate plugin migrations
                foreach ( var migrationType in migrationList )
                {
                    // Get the MigrationNumberAttribute for the migration
                    var migrationNumberAttr = System.Attribute.GetCustomAttribute( migrationType, typeof( MigrationNumberAttribute ) ) as MigrationNumberAttribute;
                    if ( migrationNumberAttr != null )
                    {
                        // If the migration's minimum Rock version is less than or equal to the current rock version, add it to the list
                        var minRockVersion = new Version( migrationNumberAttr.MinimumRockVersion );
                        if ( minRockVersion.CompareTo( rockVersion ) <= 0 )
                        {
                            string assemblyName = migrationType.Assembly.GetName().Name;
                            if ( !assemblies.ContainsKey( assemblyName ) )
                            {
                                assemblies.Add( assemblyName, new Dictionary<int, Type>() );
                            }
                            assemblies[assemblyName].Add( migrationNumberAttr.Number, migrationType );
                        }
                    }
                }

                var configConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RockContext"];
                if ( configConnectionString != null )
                {
                    string connectionString = configConnectionString.ConnectionString;
                    if ( !string.IsNullOrWhiteSpace( connectionString ) )
                    {
                        using ( SqlConnection con = new SqlConnection( connectionString ) )
                        {
                            con.Open();

                            // Iterate each assembly that contains plugin migrations
                            foreach ( var assemblyMigrations in assemblies )
                            {
                                try
                                {
                                    // Get the versions that have already been installed
                                    var installedVersions = pluginMigrationService.Queryable()
                                        .Where( m => m.PluginAssemblyName == assemblyMigrations.Key )
                                        .ToList();

                                    // Iterate each migration in the assembly in MigrationNumber order
                                    foreach ( var migrationType in assemblyMigrations.Value.OrderBy( t => t.Key ) )
                                    {
                                        // Check to make sure migration has not already been run
                                        if ( !installedVersions.Any( v => v.MigrationNumber == migrationType.Key ) )
                                        {
                                            using ( var sqlTxn = con.BeginTransaction() )
                                            {
                                                bool transactionActive = true;
                                                try
                                                {
                                                    // Create an instance of the migration and run the up migration
                                                    var migration = Activator.CreateInstance( migrationType.Value ) as Rock.Plugin.Migration;
                                                    migration.SqlConnection = con;
                                                    migration.SqlTransaction = sqlTxn;
                                                    migration.Up();
                                                    sqlTxn.Commit();
                                                    transactionActive = false;

                                                    // Save the plugin migration version so that it is not run again
                                                    var pluginMigration = new PluginMigration();
                                                    pluginMigration.PluginAssemblyName = assemblyMigrations.Key;
                                                    pluginMigration.MigrationNumber = migrationType.Key;
                                                    pluginMigration.MigrationName = migrationType.Value.Name;
                                                    pluginMigrationService.Add( pluginMigration );
                                                    rockContext.SaveChanges();

                                                    result = true;
                                                }
                                                catch ( Exception ex )
                                                {
                                                    if ( transactionActive )
                                                    {
                                                        sqlTxn.Rollback();
                                                    }
                                                    throw new Exception( string.Format( "Plugin Migration error occurred in {0}, {1}",
                                                        assemblyMigrations.Key, migrationType.Value.Name ), ex );
                                                }
                                            }
                                        }
                                    }
                                }
                                catch ( Exception ex )
                                {
                                    // If an exception occurs in an an assembly, log the error, and continue with next assembly
                                    LogError( ex, null );
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
        private void InitDatabases()
        {
            //debug
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            var test = Devart.Data.MySql.Entity.MySqlEntityProviderServices.Instance;

            System.Data.Entity.DbConfiguration.Loaded +=
                (sender, e) =>
                e.ReplaceService <System.Data.Entity.Core.Common.DbProviderServices>(
                    (services, o) =>
                    Devart.Data.MySql.Entity.MySqlEntityProviderServices.Instance
                    );

            try
            {
                LogHelper.Info("Start Code First Upgrade Database to latest......");

                //必须留下下面这行,配置使用Devart数据生成MySQL的脚本
                System.Data.Entity.Database.SetInitializer(
                    //new System.Data.Entity.DropCreateDatabaseIfModelChanges<AtlanticDXContext>());
                    new DevartDbMigrationInitializer());

                var config = new Migrations.Configuration();

                using (AtlanticDXContext context = new AtlanticDXContext())
                {
                    System.Data.Entity.Migrations.DbMigrator migrator
                        = new System.Data.Entity.Migrations.DbMigrator(config);
                    config.TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(
                        context.Database.Connection.ConnectionString, "Devart.Data.MySql");
                    var migrationsss = migrator.GetDatabaseMigrations();
                    var temp11       = migrator.GetLocalMigrations();
                    var temp22       = migrator.GetPendingMigrations();

                    temp22 = temp22.Except(migrationsss);

                    if (temp22 != null && temp22.Count() > 0)
                    {
                        LogHelper.Info(string.Format("Start Code First force default migrations......"));
                        migrator.Update();
                        LogHelper.Info("Finish Code First default migration. ");
                    }
                    else if (this.GetForceExternalSeedingFromConfig())
                    {//20150120 liangdawen: force to seed!
                        LogHelper.Info(string.Format("Start Code First force Seeding external......"));
                        migrator.Update();
                        LogHelper.Info("Finish Code First force Seeding external. ");
                    }

                    //20150131 custom migration seeding
                    string[] upgrades = GetUpgradesFromConfig();
                    if (upgrades != null && upgrades.Length > 0)
                    {
                        LogHelper.Info(string.Format("Start Code First force custom seeds......"));
                        foreach (var key in upgrades)
                        {
                            this.CustomMigration(key, migrator, config, context);
                            LogHelper.Info(string.Format("Finish Code First custom seed: {0} .", key));
                        }
                        LogHelper.Info("Finish Code First force custom seeds. ");
                    }

                    LogHelper.Info(string.Format("Code First Upgrade Database to latest completed."));
                }
            }
            catch (Exception e)
            {
                string errMsg = "Start Code First Upgrade Database to latest Exception: "
                                + e.Message + "\t\t" + e.StackTrace;
                if (e.InnerException != null)
                {
                    errMsg += "\r\nInnerException: " + e.InnerException.Message + "\t\t"
                              + e.InnerException.StackTrace;
                }

                LogHelper.Error(errMsg);
            }
        }
Exemple #30
0
        /// <summary>
        /// Migrates the database.
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public bool MigrateDatabase( RockContext rockContext )
        {
            bool result = false;

            // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so it doesn't try to do anything special
            Database.SetInitializer<Rock.Data.RockContext>( null );

            var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) );
            if ( fileInfo.Exists )
            {
                // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration
                var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a);
                if ( pendingMigrations.Any() )
                {
                    LogMessage( APP_LOG_FILENAME, "Migrating Database..." );

                    var lastMigration = pendingMigrations.Last();

                    // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes
                    migrator.Update( lastMigration );
                    result = true;
                }

                fileInfo.Delete();
            }

            return result;
        }
Exemple #31
0
        private static System.Data.Entity.Migrations.DbMigrator GetDbMigrator()
        {
            var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new Migrations.Configuration());

            return(dbMigrator);
        }
Exemple #32
0
        /// <summary>
        /// Handles the Start event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Application_Start(object sender, EventArgs e)
        {
            if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
            {
                HttpInternals.RockWebFileChangeMonitor();
            }

            // Check if database should be auto-migrated for the core and plugins
            bool autoMigrate = true;

            if (!Boolean.TryParse(ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate))
            {
                autoMigrate = true;
            }

            if (autoMigrate)
            {
                try
                {
                    Database.SetInitializer(new MigrateDatabaseToLatestVersion <Rock.Data.RockContext, Rock.Migrations.Configuration>());

                    // explictly check if the database exists, and force create it if doesn't exist
                    Rock.Data.RockContext rockContext = new Rock.Data.RockContext();
                    if (!rockContext.Database.Exists())
                    {
                        rockContext.Database.Initialize(true);
                    }
                    else
                    {
                        var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List <Type> configurationTypeList = Rock.Reflection.FindTypes(typeof(System.Data.Entity.Migrations.DbMigrationsConfiguration)).Select(a => a.Value).ToList();

                    foreach (var configType in configurationTypeList)
                    {
                        if (configType != typeof(Rock.Migrations.Configuration))
                        {
                            var config = Activator.CreateInstance(configType) as System.Data.Entity.Migrations.DbMigrationsConfiguration;
                            System.Data.Entity.Migrations.DbMigrator pluginMigrator = Activator.CreateInstance(typeof(System.Data.Entity.Migrations.DbMigrator), config) as System.Data.Entity.Migrations.DbMigrator;
                            pluginMigrator.Update();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // if migrations fail, log error and attempt to continue
                    LogError(ex, -1, string.Empty, HttpContext.Current);
                }
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer <Rock.Data.RockContext>(null);
            }

            // Preload the commonly used objects
            LoadCacheObjects();

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);

            if (runJobsInContext)
            {
                ISchedulerFactory sf;

                // create scheduler
                sf    = new StdSchedulerFactory();
                sched = sf.GetScheduler();

                // get list of active jobs
                ServiceJobService jobService = new ServiceJobService();
                foreach (ServiceJob job in jobService.GetActiveJobs().ToList())
                {
                    try
                    {
                        IJobDetail jobDetail  = jobService.BuildQuartzJob(job);
                        ITrigger   jobTrigger = jobService.BuildQuartzTrigger(job);

                        sched.ScheduleJob(jobDetail, jobTrigger);
                    }
                    catch (Exception ex)
                    {
                        // create a friendly error message
                        string message = string.Format("Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message);
                        job.LastStatusMessage = message;
                        job.LastStatus        = "Error Loading Job";

                        jobService.Save(job, null);
                    }
                }

                // set up the listener to report back from jobs as they complete
                sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs());

                // start the scheduler
                sched.Start();
            }

            // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
            AddCallBack();

            RegisterFilters(GlobalConfiguration.Configuration.Filters);

            RegisterRoutes(RouteTable.Routes);

            Rock.Security.Authorization.Load();

            AddEventHandlers();

            new EntityTypeService().RegisterEntityTypes(Server.MapPath("~"));
            new FieldTypeService().RegisterFieldTypes(Server.MapPath("~"));

            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
		private static System.Data.Entity.Migrations.DbMigrator GetDbMigrator() {
			var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new Migrations.Configuration());
			return dbMigrator;
		}
Exemple #34
0
        private void InitializeDataStore()
        {
            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>());

            var configuration = new GalleryDbMigrationConfiguration(ProviderDataStore);
            var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }
        }
Exemple #35
0
        /// <summary>
        /// Migrates the database.
        /// </summary>
        public void MigrateDatabase()
        {
            // Check if database should be auto-migrated for the core and plugins
            if (ConfigurationManager.AppSettings["AutoMigrateDatabase"].AsBoolean(true))
            {
                try
                {
                    Database.SetInitializer(new MigrateDatabaseToLatestVersion <Rock.Data.RockContext, Rock.Migrations.Configuration>());

                    var rockContext = new RockContext();

                    // explictly check if the database exists, and force create it if doesn't exist
                    if (!rockContext.Database.Exists())
                    {
                        // If database did not exist, initialize a database (which runs existing Rock migrations)
                        rockContext.Database.Initialize(true);
                    }
                    else
                    {
                        // If database does exist, run any pending Rock migrations
                        var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List <Type> migrationList = Rock.Reflection.FindTypes(typeof(Migration)).Select(a => a.Value).ToList();

                    // If any plugin migrations types were found
                    if (migrationList.Any())
                    {
                        // Create EF service for plugin migrations
                        var pluginMigrationService = new PluginMigrationService(rockContext);

                        // Get the current rock version
                        var rockVersion = new Version(Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());

                        // Create dictionary for holding migrations specific to an assembly
                        var assemblies = new Dictionary <string, Dictionary <int, Type> >();

                        // Iterate plugin migrations
                        foreach (var migrationType in migrationList)
                        {
                            // Get the MigrationNumberAttribute for the migration
                            var migrationNumberAttr = System.Attribute.GetCustomAttribute(migrationType, typeof(MigrationNumberAttribute)) as MigrationNumberAttribute;
                            if (migrationNumberAttr != null)
                            {
                                // If the migration's minimum Rock version is less than or equal to the current rock version, add it to the list
                                var minRockVersion = new Version(migrationNumberAttr.MinimumRockVersion);
                                if (minRockVersion.CompareTo(rockVersion) <= 0)
                                {
                                    string assemblyName = migrationType.Assembly.GetName().Name;
                                    if (!assemblies.ContainsKey(assemblyName))
                                    {
                                        assemblies.Add(assemblyName, new Dictionary <int, Type>());
                                    }
                                    assemblies[assemblyName].Add(migrationNumberAttr.Number, migrationType);
                                }
                            }
                        }

                        // Iterate each assembly that contains plugin migrations
                        foreach (var assemblyMigrations in assemblies)
                        {
                            try
                            {
                                // Get the versions that have already been installed
                                var installedVersions = pluginMigrationService.Queryable()
                                                        .Where(m => m.PluginAssemblyName == assemblyMigrations.Key)
                                                        .ToList();

                                // Wrap the migrations for each assembly in a transaction so that if an error with one migration, none of the migrations are persisted
                                RockTransactionScope.WrapTransaction(() =>
                                {
                                    // Iterate each migration in the assembly in MigrationNumber order
                                    foreach (var migrationType in assemblyMigrations.Value.OrderBy(t => t.Key))
                                    {
                                        // Check to make sure migration has not already been run
                                        if (!installedVersions.Any(v => v.MigrationNumber == migrationType.Key))
                                        {
                                            try
                                            {
                                                // Create an instance of the migration and run the up migration
                                                var migration = Activator.CreateInstance(migrationType.Value) as Rock.Plugin.Migration;
                                                migration.Up();

                                                // Save the plugin migration version so that it is not run again
                                                var pluginMigration = new PluginMigration();
                                                pluginMigration.PluginAssemblyName = assemblyMigrations.Key;
                                                pluginMigration.MigrationNumber    = migrationType.Key;
                                                pluginMigration.MigrationName      = migrationType.Value.Name;
                                                pluginMigrationService.Add(pluginMigration);
                                                rockContext.SaveChanges();
                                            }
                                            catch (Exception ex)
                                            {
                                                throw new Exception(string.Format("Plugin Migration error occurred in {0}, {1}",
                                                                                  assemblyMigrations.Key, migrationType.Value.Name), ex);
                                            }
                                        }
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                // If an exception occurs in an an assembly, log the error, and continue with next assembly
                                LogError(ex, null);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // if migrations fail, log error and attempt to continue
                    LogError(ex, null);
                }
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer <Rock.Data.RockContext>(null);
            }
        }
        /// <summary>
        /// Migrates the database.
        /// </summary>
        public void MigrateDatabase()
        {
            // Check if database should be auto-migrated for the core and plugins
            if ( ConfigurationManager.AppSettings["AutoMigrateDatabase"].AsBoolean( true ) )
            {
                try
                {
                    Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() );

                    var rockContext = new RockContext();

                    // explictly check if the database exists, and force create it if doesn't exist
                    if ( !rockContext.Database.Exists() )
                    {
                        // If database did not exist, initialize a database (which runs existing Rock migrations)
                        rockContext.Database.Initialize( true );
                    }
                    else
                    {
                        // If database does exist, run any pending Rock migrations
                        var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List<Type> migrationList = Rock.Reflection.FindTypes( typeof( Migration ) ).Select( a => a.Value ).ToList();

                    // If any plugin migrations types were found
                    if ( migrationList.Any() )
                    {
                        // Create EF service for plugin migrations
                        var pluginMigrationService = new PluginMigrationService( rockContext );

                        // Get the current rock version
                        var rockVersion = new Version( Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );

                        // Create dictionary for holding migrations specific to an assembly
                        var assemblies = new Dictionary<string, Dictionary<int, Type>>();

                        // Iterate plugin migrations
                        foreach ( var migrationType in migrationList )
                        {
                            // Get the MigrationNumberAttribute for the migration
                            var migrationNumberAttr = System.Attribute.GetCustomAttribute( migrationType, typeof( MigrationNumberAttribute ) ) as MigrationNumberAttribute;
                            if ( migrationNumberAttr != null )
                            {
                                // If the migration's minimum Rock version is less than or equal to the current rock version, add it to the list
                                var minRockVersion = new Version( migrationNumberAttr.MinimumRockVersion );
                                if ( minRockVersion.CompareTo( rockVersion ) <= 0 )
                                {
                                    string assemblyName = migrationType.Assembly.GetName().Name;
                                    if ( !assemblies.ContainsKey( assemblyName ) )
                                    {
                                        assemblies.Add( assemblyName, new Dictionary<int, Type>() );
                                    }
                                    assemblies[assemblyName].Add( migrationNumberAttr.Number, migrationType );
                                }
                            }
                        }

                        // Iterate each assembly that contains plugin migrations
                        foreach ( var assemblyMigrations in assemblies )
                        {
                            try
                            {
                                // Get the versions that have already been installed
                                var installedVersions = pluginMigrationService.Queryable()
                                    .Where( m => m.PluginAssemblyName == assemblyMigrations.Key )
                                    .ToList();

                                // Wrap the migrations for each assembly in a transaction so that if an error with one migration, none of the migrations are persisted
                                RockTransactionScope.WrapTransaction( () =>
                                {
                                    // Iterate each migration in the assembly in MigrationNumber order
                                    foreach ( var migrationType in assemblyMigrations.Value.OrderBy( t => t.Key ) )
                                    {
                                        // Check to make sure migration has not already been run
                                        if ( !installedVersions.Any( v => v.MigrationNumber == migrationType.Key ) )
                                        {
                                            try
                                            {
                                                // Create an instance of the migration and run the up migration
                                                var migration = Activator.CreateInstance( migrationType.Value ) as Rock.Plugin.Migration;
                                                migration.Up();

                                                // Save the plugin migration version so that it is not run again
                                                var pluginMigration = new PluginMigration();
                                                pluginMigration.PluginAssemblyName = assemblyMigrations.Key;
                                                pluginMigration.MigrationNumber = migrationType.Key;
                                                pluginMigration.MigrationName = migrationType.Value.Name;
                                                pluginMigrationService.Add( pluginMigration );
                                                rockContext.SaveChanges();
                                            }
                                            catch ( Exception ex )
                                            {
                                                throw new Exception( string.Format( "Plugin Migration error occurred in {0}, {1}",
                                                    assemblyMigrations.Key, migrationType.Value.Name ), ex );
                                            }
                                        }
                                    }
                                } );
                            }
                            catch ( Exception ex )
                            {
                                // If an exception occurs in an an assembly, log the error, and continue with next assembly
                                LogError( ex, null );
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    // if migrations fail, log error and attempt to continue
                    LogError( ex, null );
                }

            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer<Rock.Data.RockContext>( null );
            }
        }
Exemple #37
0
        protected void Application_Start()
        {
            //Database.SetInitializer(new DbInitializer());
            // new GmailBotDbContext().Database.Initialize(true);

            Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GmailBotDbContext, Configuration>());

            var configuration = new Configuration();
            var migrator      = new System.Data.Entity.Migrations.DbMigrator(configuration);

            if (migrator.GetPendingMigrations().Any())
            {
                migrator.Update();
            }

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            LogMaker.NewMessage += LogMaker_NewMessage;
#pragma warning disable 618
#if !DEBUG && !WEBHOOK
            string clientSecretsStr = Encoding.UTF8.GetString(App_LocalResources.Tokens.client_secret);
#else
            string clientSecretsStr = Encoding.UTF8.GetString(App_LocalResources.TokensTest.client_secret_debug);
#endif
            var botSettings        = new BotSettings();
            var clienSecretsJtoken = JsonConvert.DeserializeObject <JToken>(clientSecretsStr);
            var clientSecrets      = JsonConvert.DeserializeObject <Secrets>(clienSecretsJtoken["web"].ToString());

#if !DEBUG && !WEBHOOK
            botSettings.BotName               = System.Configuration.ConfigurationSettings.AppSettings["Botname"];
            botSettings.Token                 = App_LocalResources.Tokens.BotToken;
            botSettings.Topic                 = App_LocalResources.Tokens.TopicName;
            botSettings.ClientSecrets         = clientSecrets;
            botSettings.Subscription          = App_LocalResources.Tokens.Subscription;
            botSettings.ImagesPath            = System.Configuration.ConfigurationSettings.AppSettings["ImagesPath"];
            botSettings.DomainName            = App_LocalResources.Tokens.DomainName;
            botSettings.AttachmentsTempFolder = Path.Combine(HttpRuntime.AppDomainAppPath,
                                                             System.Configuration.ConfigurationSettings.AppSettings["AttachmentsTemp"]);
            botSettings.MaxAttachmentSize =
                int.Parse(System.Configuration.ConfigurationSettings.AppSettings["MaxAttachmentSize"]);
            botSettings.BotVersion      = ReturnBotVersion();
            botSettings.GmnbApiKey      = App_LocalResources.Tokens.gmnbAPIKey;
            botSettings.ApplicationName = App_LocalResources.Tokens.ApplicationName;
#else
            botSettings.BotName               = System.Configuration.ConfigurationSettings.AppSettings["Botname"];
            botSettings.Token                 = App_LocalResources.TokensTest.BotToken;
            botSettings.Topic                 = App_LocalResources.TokensTest.TopicName;
            botSettings.ClientSecrets         = clientSecrets;
            botSettings.Subscription          = App_LocalResources.TokensTest.Subscription;
            botSettings.ImagesPath            = System.Configuration.ConfigurationSettings.AppSettings["ImagesPath"];
            botSettings.DomainName            = App_LocalResources.TokensTest.DomainName;
            botSettings.AttachmentsTempFolder = Path.Combine(HttpRuntime.AppDomainAppPath,
                                                             System.Configuration.ConfigurationSettings.AppSettings["AttachmentsTemp"]);
            botSettings.MaxAttachmentSize =
                int.Parse(System.Configuration.ConfigurationSettings.AppSettings["MaxAttachmentSize"]);
            botSettings.BotVersion      = ReturnBotVersion();
            botSettings.GmnbApiKey      = App_LocalResources.TokensTest.gmnbAPIKey;
            botSettings.ApplicationName = App_LocalResources.TokensTest.ApplicationName;
#endif

            _botInitializer = BotInitializer.GetInstance(botSettings);
#if DEBUG
            _botInitializer.InitializeUpdates();
#else
            _botInitializer.InitializeUpdates(true);
#endif
            _botInitializer.InitializeUpdatesHandler();
            _botInitializer.InitializeAuthotizer();
            _botInitializer.InitializeServiceFactory();
            _botInitializer.InitializeMessageHandler();
            _botInitializer.InitializeCallbackQueryHandler();
            _botInitializer.InitializeInlineQueryHandler();
            _botInitializer.InitializeChosenInlineResultHandler();
#if (!WEBHOOK)
            _botInitializer.InitializeNotifyHandler();
#endif
#if !DEBUG && !WEBHOOK
            _botInitializer.InitializePushNotificationWatchesAsync(initializeDelay);
            _botInitializer.InitializePushNotificationWatchTimer(_updatePeriod);
#endif
#pragma warning restore 618
        }
Exemple #38
0
 public static void BeforeTestRun()
 {
     var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new MeAnota.Migrations.Configuration());
     dbMigrator.Update();
     WebSecurity.InitializeDatabaseConnection("MeAnotaConnString", "Usuario", "Id", "Email", autoCreateTables: true);
 }
Exemple #39
0
 public void ReiniciaBanco()
 {
     var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new MeAnota.Migrations.Configuration());
     dbMigrator.Update("ModeloInicial");
     dbMigrator.Update();
 }
        /// <summary>
        /// Migrates the database.
        /// </summary>
        /// <returns>True if at least one migration was run</returns>
        public bool MigrateDatabase( RockContext rockContext )
        {
            bool result = false;

            var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) );
            if ( fileInfo.Exists )
            {
                Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() );

                // explictly check if the database exists, and force create it if doesn't exist
                if ( !rockContext.Database.Exists() )
                {
                    // If database did not exist, initialize a database (which runs existing Rock migrations)
                    rockContext.Database.Initialize( true );
                    result = true;
                }
                else
                {
                    // If database does exist, run any pending Rock migrations
                    var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                    if ( migrator.GetPendingMigrations().Any() )
                    {
                        LogMessage( APP_LOG_FILENAME, "Migrating Database..." );

                        migrator.Update();
                        result = true;
                    }
                }

                fileInfo.Delete();
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer<Rock.Data.RockContext>( null );
            }

            return result;
        }
Exemple #41
0
        /// <summary>
        /// Handles the Start event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Application_Start( object sender, EventArgs e )
        {
            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                System.Diagnostics.Debug.WriteLine( string.Format( "Application_Start: {0}", DateTime.Now.ToString("hh:mm:ss.FFF" ) ));
            }

            // Check if database should be auto-migrated for the core and plugins
            bool autoMigrate = true;
            if ( !Boolean.TryParse( ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate ) )
            {
                autoMigrate = true;
            }

            if ( autoMigrate )
            {
                try
                {

                    Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() );

                    // explictly check if the database exists, and force create it if doesn't exist
                    Rock.Data.RockContext rockContext = new Rock.Data.RockContext();
                    if ( !rockContext.Database.Exists() )
                    {
                        rockContext.Database.Initialize( true );
                    }
                    else
                    {
                        var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List<Type> configurationTypeList = Rock.Reflection.FindTypes( typeof( System.Data.Entity.Migrations.DbMigrationsConfiguration ) ).Select( a => a.Value ).ToList();

                    foreach ( var configType in configurationTypeList )
                    {
                        if ( configType != typeof( Rock.Migrations.Configuration ) )
                        {
                            var config = Activator.CreateInstance( configType ) as System.Data.Entity.Migrations.DbMigrationsConfiguration;
                            System.Data.Entity.Migrations.DbMigrator pluginMigrator = Activator.CreateInstance( typeof( System.Data.Entity.Migrations.DbMigrator ), config ) as System.Data.Entity.Migrations.DbMigrator;
                            pluginMigrator.Update();
                        }
                    }

                }
                catch ( Exception ex )
                {
                    // if migrations fail, log error and attempt to continue
                    LogError( ex, null );
                }

            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer<Rock.Data.RockContext>( null );
            }

            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                new AttributeService().Get( 0 );
                System.Diagnostics.Debug.WriteLine( string.Format( "ConnectToDatabase - Connected: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) );
            }

            // Preload the commonly used objects
            LoadCacheObjects();
            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                System.Diagnostics.Debug.WriteLine( string.Format( "LoadCacheObjects - Done: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) );
            }

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean( ConfigurationManager.AppSettings["RunJobsInIISContext"] );
            if ( runJobsInContext )
            {

                ISchedulerFactory sf;

                // create scheduler
                sf = new StdSchedulerFactory();
                sched = sf.GetScheduler();

                // get list of active jobs
                ServiceJobService jobService = new ServiceJobService();
                foreach ( ServiceJob job in jobService.GetActiveJobs().ToList() )
                {
                    try
                    {
                        IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                        ITrigger jobTrigger = jobService.BuildQuartzTrigger( job );

                        sched.ScheduleJob( jobDetail, jobTrigger );
                    }
                    catch ( Exception ex )
                    {
                        // create a friendly error message
                        string message = string.Format( "Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message );
                        job.LastStatusMessage = message;
                        job.LastStatus = "Error Loading Job";

                        jobService.Save( job, null );
                    }
                }

                // set up the listener to report back from jobs as they complete
                sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() );

                // start the scheduler
                sched.Start();
            }

            // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
            AddCallBack();

            RegisterFilters( GlobalConfiguration.Configuration.Filters );

            RegisterRoutes( RouteTable.Routes );

            Rock.Security.Authorization.Load();

            AddEventHandlers();

            new EntityTypeService().RegisterEntityTypes( Server.MapPath( "~" ) );
            new FieldTypeService().RegisterFieldTypes( Server.MapPath( "~" ) );

            BundleConfig.RegisterBundles( BundleTable.Bundles );
        }
Exemple #42
0
        /// <summary>
        /// Migrates the database.
        /// </summary>
        private static void MigrateDatabase()
        {
            var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());

            migrator.Update();
        }