예제 #1
0
        private static bool RunMigrations(Creatures3DbContext db)
        {
            var upgradeDescription = MigrationHelper.MigrationDescription(db);
            var pwd = AskForUpgradePassword(upgradeDescription);

            if (pwd != "cat")
            {
                return(false);
            }
            try
            {
                //http://stackoverflow.com/questions/34699283/ef6-1-3-expects-createdon-field-in-migrationhistory-table-when-database-setiniti
                //MessageBox.Show(
                //    "You might need to the following SQL First /n/p " +
                //    "ALTER TABLE dbo.__MigrationHistory ADD CreatedOn DateTime Default GETDATE() /n/p" + "GO /n/p" +
                //    "UPDATE dbo.__MigrationHistory SET CreatedOn = GETDATE()");
                MigrationHelper.RunMigrations(db);
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(true);
            }
        }
예제 #2
0
        public NHibernateFactory(ConnectionConfig connectionConfig)
        {
            if (connectionConfig.RunMigrations)
            {
                MigrationHelper.Run(connectionConfig.Business, connectionConfig.ConnectionString);
            }

            try
            {
                var dll = AssemblyHelper.GetAssemblyByName(connectionConfig.Business);
                var persistenceConfigurer = GetDatabase(connectionConfig.DatabaseType, connectionConfig.ConnectionString);

                var fluentyConfigure = Fluently.Configure()
                                       .Database(persistenceConfigurer)
                                       .Mappings(m => m.FluentMappings.AddFromAssembly(dll));

                SessionFactory = fluentyConfigure
                                 .ExposeConfiguration(cfg => new SchemaExport(cfg).Execute(false, false, false))
                                 .BuildConfiguration()
                                 .BuildSessionFactory();

                Console.WriteLine("Connection established successfully");
            }
            catch (HibernateException exception)
            {
                throw new Exception("Error when trying to establish database connection :", exception);
            }
        }
예제 #3
0
        private bool TruncateTables()
        {
            if (TruncateTableCheckBox.IsChecked == false)
            {
                return(true);
            }

            if (CashVoucherCheckBox.IsChecked == true)
            {
                if (!MigrationHelper.TruncateTable("cv"))
                {
                    return(false);
                }
            }
            if (JournalVoucherCheckBox.IsChecked == true)
            {
                if (!MigrationHelper.TruncateTable("jv"))
                {
                    return(false);
                }
            }
            if (OfficialReceiptCheckBox.IsChecked == true)
            {
                if (!MigrationHelper.TruncateTable("or"))
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #4
0
 internal static void StartJob(Task task, MigrationBatchDataProvider batchProvider, MigrationJob job, MultiValuedProperty <SmtpAddress> notificationEmails, MigrationBatchFlags batchFlags)
 {
     MigrationHelper.RunUpdateOperation(delegate
     {
         job.StartJob(batchProvider.MailboxProvider, notificationEmails, batchFlags, null);
     });
 }
예제 #5
0
        public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
                                               CancellationToken cancellationToken)
        {
            _telegramService = new TelegramService(context);
            var isSudoer = _telegramService.IsSudoer();

            if (!isSudoer)
            {
                return;
            }

            var param1 = _telegramService.Message.Text.Split(" ").ValueOfIndex(1);

            switch (param1)
            {
            case "migrate":
                await _telegramService.SendTextAsync("Migrating ")
                .ConfigureAwait(false);

                MigrationHelper.MigrateMysql();
                MigrationHelper.MigrateSqlite();
                await _telegramService.SendTextAsync("Migrate complete ")
                .ConfigureAwait(false);

                break;
            }
        }
예제 #6
0
        /// <summary>
        /// Migrate database to latest and seed data
        /// </summary>
        /// <typeparam name="TDbContext">Type of cache manager dbContext</typeparam>
        /// <param name="serviceProvider">serviceProvider</param>
        public static void MigrateAndSeedData <TDbContext>(this IServiceProvider serviceProvider)
            where TDbContext : DbContext
        {
            serviceProvider.NotNull(nameof(serviceProvider));
            using (var scope = serviceProvider.CreateScope())
            {
                using (var dbContext = scope.ServiceProvider.GetRequiredService <TDbContext>())
                {
                    //Auto migrate dbContext to the latest version of model changes on the fly
                    if (dbContext.Database.IsSqlServer())
                    {
                        MigrationHelper.ForSqlServer(dbContext).Migrate();
                    }

                    //Seed initial data
                    var cacheSettingStore = scope.ServiceProvider.GetRequiredService <IGenericStore <CacheSetting> >();
                    if (!cacheSettingStore.Table.Any())
                    {
                        cacheSettingStore.Add(new CacheSetting
                        {
                            MinSearchDiffHours      = 1 * 24,  //24 (1 day)
                            MaxSearchDiffHours      = 30 * 24, //720 (30 day)
                            MinCacheMinutes         = 5,
                            MaxCacheMinutes         = 24 * 60, //1440 (1 day)
                            OverSearchDiffHours     = 90 * 24, //2160 (90 day)
                            RecentSearchMinimumRPM  = 1,
                            RecentSearchMaxmimumRPM = 20,
                            RpmDurationMinutes      = 2,
                            SupplierType            = null,
                        });
                    }
                }
            }
        }
예제 #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(options => options.AddProvider(new CustomDebugLoggerProvider()));

            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            if (MigrationHelper.IsActive)
            {
                MigrationHelper.ConvertToIntegratedSecurity(ref connectionString);
            }

            services.AddDbContext <FRSContext>(options => options
                                               .UseSqlServer(connectionString)
                                               .EnableSensitiveDataLogging());

            // Accept All HTTP Request Methods from all origins
            //services.AddCors();

            // Maintain property names during serialization. See:
            // https://github.com/aspnet/Announcements/issues/194
            services
            .AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            // Add Kendo UI services to the services container
            services.AddKendo();

            services.AddScoped <DbContext, FRSContext>();
            services.AddTransient <ICacheProvider, CacheProvider>();
            services.AddTransient <IProductsService, ProductsService>();
            services.AddTransient <IUsersService, UsersService>();
        }
예제 #8
0
        public static void Main(String[] args)
        {
            var webHost = CreateHostBuilder(args).Build();

            MigrationHelper.SeedAndMigrate(webHost);
            webHost.Run();
        }
        protected override void InternalProcessRecord()
        {
            MigrationBatchDataProvider batchProvider = (MigrationBatchDataProvider)base.DataSession;

            try
            {
                MigrationHelper.RunUpdateOperation(delegate
                {
                    if (this.Force)
                    {
                        batchProvider.MigrationJob.Delete(batchProvider.MailboxProvider, true);
                        return;
                    }
                    if (batchProvider.MigrationJob.IsPAW)
                    {
                        batchProvider.MigrationJob.SetMigrationFlags(batchProvider.MailboxProvider, MigrationFlags.Remove);
                        return;
                    }
                    batchProvider.MigrationJob.RemoveJob(batchProvider.MailboxProvider);
                });
            }
            catch (ObjectNotFoundException ex)
            {
                MigrationObjectTaskBase <MigrationBatchIdParameter> .WriteJobNotFoundError(this, this.Identity.RawIdentity, ex);
            }
            batchProvider.MigrationJob.ReportData.Append(Strings.MigrationReportJobRemoved(base.ExecutingUserIdentityName));
            MigrationObjectTaskBase <MigrationBatchIdParameter> .RegisterMigrationBatch(this, batchProvider.MailboxSession, base.CurrentOrganizationId, false, false);

            base.InternalProcessRecord();
        }
예제 #10
0
 static void Main()
 {
     MigrationHelper.Migrate();
     Application.SetHighDpiMode(HighDpiMode.SystemAware);
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainMenuForm());
 }
예제 #11
0
파일: App.cs 프로젝트: curcas/DynamicList
        protected override void OnStart()
        {
            // Handle when your app starts
            DependencyService.Get <ISQLite> ().DropDatabase();
            var migrationHelper = new MigrationHelper();

            migrationHelper.Migrate();
        }
예제 #12
0
 /// <summary>
 /// The seed.
 /// </summary>
 /// <param name="modelBuilder">
 /// The model builder.
 /// </param>
 public void Seed(ModelBuilder modelBuilder)
 {
     MigrationHelper.AddCountries(modelBuilder);
     MigrationHelper.AddProducts(modelBuilder);
     MigrationHelper.AddCustomers(modelBuilder);
     MigrationHelper.AddBanking(modelBuilder);
     MigrationHelper.AddOrders(modelBuilder);
 }
예제 #13
0
 private void RemoveSeriesRows(int seriesId)
 {
     MigrationHelper.ExecuteNonQuery("DELETE FROM Series WHERE Id = {0}", seriesId.ToString());
     MigrationHelper.ExecuteNonQuery("DELETE FROM Episodes WHERE SeriesId = {0}", seriesId.ToString());
     MigrationHelper.ExecuteNonQuery("DELETE FROM Seasons WHERE SeriesId = {0}", seriesId.ToString());
     MigrationHelper.ExecuteNonQuery("DELETE FROM History WHERE SeriesId = {0}", seriesId.ToString());
     MigrationHelper.ExecuteNonQuery("DELETE FROM EpisodeFiles WHERE SeriesId = {0}", seriesId.ToString());
 }
        public AppDbTestContext CreateContext()
        {
            AppDbTestContext db = new AppDbTestContext(ConnectionString);

            // db.Database.EnsureCreated();
            MigrationHelper.ForSqlServer(db).Migrate();
            Seed(db);
            return(db);
        }
예제 #15
0
        //[Test]
        public void Can_Upgrade_VersionOneZeroOne_ToVersionOneoneZero_A_Database()
        {
            var worker   = new DbPreTestDataWorker();
            var database = worker.Database;

            var migrationHelper = new MigrationHelper(database);

            migrationHelper.UpgradeTargetVersionOneOneZero();
        }
        public ProductDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder <ProductDbContext>();

            var connectionString = MigrationHelper.GetConfiguration().GetConnectionString("DefaultConnection");

            DbContextConfigurer.Configure(builder, connectionString);

            return(new ProductDbContext(builder.Options));
        }
        private static async Task Seed(RecipeBookDbContext context, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager)
        {
            Type[] migrationTypes = MigrationHelper.GetMigrationTypes();

            IRoleDataMigration addDefaultRolesMigration = MigrationHelper.GetMigration <AddDefaultRolesMigration>(migrationTypes);
            await addDefaultRolesMigration.SeedAsync(context, roleManager);

            IUserDataMigration createAdminUserDataMigration = MigrationHelper.GetMigration <CreateTechAdminUserMigration>(migrationTypes);
            await createAdminUserDataMigration.SeedAsync(context, userManager);
        }
        static void Main(string[] args)
        {
            DbContextOptionsBuilder <ERPContext> options = new DbContextOptionsBuilder <ERPContext>();

            options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ERPModel;Trusted_Connection=True;MultipleActiveResultSets=true");

            using (var db = new ERPContext(options.Options)) {
                MigrationHelper.ForSqlServer(db).Migrate();
            }
        }
예제 #19
0
        private async void btnStartMigration_Click(object sender, EventArgs e)
        {
            completedProcesses         = 0;
            progressBarMigration.Value = 0;
            progressBarMigration.Show();
            progressBarMigration.Maximum = totalProcesses;
            lblInfo.Hide();
            lblInfo.Text    = "";
            txtDetails.Text = "";


            lblInfo.Show();
            lblDetails.Show();

            jiraClient = new JiraApi(jiraUrl, jiraUsername, jiraPassword);
            vsoClient  = new VSOApi(vsoUrl, vsoUsername, vsoPassword);
            migration  = new MigrationHelper(jiraClient, vsoClient);
            if (cbProjects.Checked)
            {
                lblInfo.Text     = "Migrating projects...";
                txtDetails.Text += await migration.MigrateProjects();

                progressBarMigration.Value++;
            }
            if (cbSprints.Checked)
            {
                lblInfo.Text     = "Migrating sprints...";
                txtDetails.Text += await migration.MigrateSprints();

                progressBarMigration.Value++;
            }
            if (cbStories.Checked)
            {
                lblInfo.Text     = "Migrating stories...";
                txtDetails.Text += await migration.MigrateStories();

                progressBarMigration.Value++;
            }
            if (cbSprintStories.Checked)
            {
                lblInfo.Text     = "Migrating sprint stories...";
                txtDetails.Text += await migration.MigrateSprintsStories();

                progressBarMigration.Value++;
            }
            if (totalProcesses == 0)
            {
                lblInfo.Text = "Nothing to Migrate";
            }
            if (totalProcesses == progressBarMigration.Value && totalProcesses != 0)
            {
                lblInfo.Text = "Migration Finished, see details >>";
            }
        }
예제 #20
0
        private static async Task SeedAsync(ParkingAppDbContext context)
        {
            Type[] migrationTypes = MigrationHelper.GetMigrationTypes();

            IReadOnlySet <IDataMigration> dataMigrations = GetIDataMigrations(migrationTypes);

            foreach (IDataMigration dataMigration in dataMigrations)
            {
                await dataMigration.SeedAsync(context);
            }
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // get the configured timeout, or default to 60 minutes if it is blank
            var commandTimeout  = dataMap.GetString(AttributeKey.CommandTimeout).AsIntegerOrNull() ?? 3600;
            var migrationHelper = new MigrationHelper(new JobMigration(commandTimeout));

            migrationHelper.CreateIndexIfNotExists("InteractionSession", new[] { "InteractionSessionLocationId" }, new string[0]);

            ServiceJobService.DeleteJob(context.GetJobId());
        }
예제 #22
0
        private void RemoveDuplicateSeries <T>(string field)
        {
            var duplicatedSeries = MigrationHelper.GetDuplicates <T>("Series", field);

            foreach (var duplicate in duplicatedSeries)
            {
                foreach (var seriesId in duplicate.OrderBy(c => c.Key).Skip(1).Select(c => c.Key))
                {
                    RemoveSeriesRows(seriesId);
                }
            }
        }
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            Down(migrationBuilder);

            var sql1 = MigrationHelper.GetSqlFromEmbeddedStoredProcedure("20210126-sp-language-domain-report.sql");

            migrationBuilder.Sql($"EXEC('{sql1}')");

            var sql2 = MigrationHelper.GetSqlFromEmbeddedStoredProcedure("20210126-sp-language-page-report.sql");

            migrationBuilder.Sql($"EXEC('{sql2}')");
        }
        protected override void Generate(
            MigrationOperation operation,
            IModel model,
            MigrationCommandListBuilder builder)
        {
            var oldCmds = builder.GetCommandList().ToList();

            base.Generate(operation, model, builder);
            var newCmds = builder.GetCommandList().ToList();
            var addCmds = newCmds.Where(x => !oldCmds.Contains(x)).ToList();

            MigrationHelper.Generate(operation, builder, Dependencies.SqlGenerationHelper, addCmds);
        }
예제 #25
0
        public static void Main(string[] args)
        {
            MigrationHelper.ReadArguments(ref args);

            var webHost = BuildWebHost(args);

            if (MigrationHelper.IsActive)
            {
                MigrationHelper.Run();
                return;
            }

            webHost.Run();
        }
예제 #26
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // get the configured timeout, or default to 60 minutes if it is blank
            var commandTimeout  = dataMap.GetString(AttributeKey.CommandTimeout).AsIntegerOrNull() ?? 3600;
            var migrationHelper = new MigrationHelper(new JobMigration(commandTimeout));

            // Referenced by FK_dbo.Interaction_dbo.InteractionComponent_InteractionComponentId
            // 23-Nov-2021 DMV: No need to drop this index if it is already there, which in some cases it is.
            migrationHelper.CreateIndexIfNotExists("Interaction", new[] { "InteractionComponentId" }, new string[0]);

            ServiceJobService.DeleteJob(context.GetJobId());
        }
예제 #27
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();
            var connectionString   = Configuration.GetConnectionString("DefaultConnection");
            var migrationNamespace = Configuration["ConfigSettings:MigrationNamespace"];

            BaseRepository.ConnectionString = connectionString;
            MigrationHelper.CreateDbIfNoneExists(connectionString);
            MigrationHelper.MigrateUp(connectionString, migrationNamespace);
            MapperHelper.MapAllEntities();
        }
예제 #28
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // get the configured timeout, or default to 60 minutes if it is blank
            var commandTimeout  = dataMap.GetString(AttributeKey.CommandTimeout).AsIntegerOrNull() ?? 3600;
            var migrationHelper = new MigrationHelper(new JobMigration(commandTimeout));

            migrationHelper.DropIndexIfExists("CommunicationRecipient", "IX_Status");

            migrationHelper.CreateIndexIfNotExists("CommunicationRecipient",
                                                   new[] { "Status" },
                                                   new[] { "CommunicationId" });

            ServiceJobService.DeleteJob(context.GetJobId());
        }
예제 #29
0
        protected TestBase()
        {
            Config = new ConfigurationBuilder <Configuration>()
                     .UseAppSettings()
                     .Build();

            var options = new DbContextOptionsBuilder <PoultryDbContext>()
                          .UseSqlServer(Config.ConnectionString)
                          .Options;


            Context    = new PoultryDbContext(options);
            Repository = new PoultryRepository(Context, new UserHandler());

            MigrationHelper = new MigrationHelper <PoultryDbContext>(Context);
        }
예제 #30
0
        protected override void InternalProcessRecord()
        {
            MigrationBatchDataProvider batchProvider = (MigrationBatchDataProvider)base.DataSession;
            bool      isPAW = batchProvider.MigrationJob.IsPAW;
            Exception ex    = null;

            try
            {
                if (isPAW)
                {
                    this.DataObject.CompleteAfter                = new DateTime?(DateTime.MinValue);
                    this.DataObject.CompleteAfterUTC             = new DateTime?(DateTime.MinValue);
                    this.DataObject.SubscriptionSettingsModified = (DateTime)ExDateTime.UtcNow;
                    MigrationHelper.RunUpdateOperation(delegate
                    {
                        batchProvider.MigrationJob.UpdateJob(batchProvider.MailboxProvider, false, this.DataObject);
                    });
                }
                else
                {
                    if (this.DataObject.MigrationType == MigrationType.PublicFolder)
                    {
                        this.VerifyLegacyPublicFolderDatabaseLocked();
                    }
                    MigrationHelper.RunUpdateOperation(delegate
                    {
                        batchProvider.MigrationJob.FinalizeJob(batchProvider.MailboxProvider, this.resolvedNotificationEmails);
                    });
                }
                batchProvider.MigrationJob.ReportData.Append(Strings.MigrationReportJobCompletedByUser(base.ExecutingUserIdentityName));
            }
            catch (InvalidOperationException ex2)
            {
                ex = ex2;
            }
            if (ex != null)
            {
                base.WriteError(new MigrationPermanentException(Strings.MigrationCannotBeCompleted, ex));
            }
            if (isPAW)
            {
                MigrationObjectTaskBase <MigrationBatchIdParameter> .RegisterMigrationBatch(this, batchProvider.MailboxSession, base.CurrentOrganizationId, false, false);
            }
            base.InternalProcessRecord();
        }