public void TestImplementationExists()
 {
     Assert.Throws(typeof(ArgumentNullException), () =>
     {
         DatabaseMigration migration = new DatabaseMigration(null);
     });
 }
        public void TestApplicationParameters()
        {
            // First Migrations
            DatabaseMigration migration = Initialize();

            migration.DatabaseScripts = "./DatabaseMigrations/TestParameter/";
            migration.ScriptParameters
            .Add("user", DbType.String, (script, parameter) => "SuperUser");

            migration.ScriptParameters
            .Add("TestApplicationName", DbType.String, (script, parameter) => ConfigurationManager.AppSettings["TestApplicationName"]);

            migration.ScriptLogParameters
            .Add("user", DbType.String, (script, parameter) => "SuperUser");

            migration.ScriptLogParameters
            .Add("TestApplicationName", DbType.String, (script, parameter) => ConfigurationManager.AppSettings["TestApplicationName"]);

            migration.ScriptLogInsert = "INSERT INTO ScriptLog (ScriptName, ScriptDate, Status, DomainUser) VALUES (@name,GETDATE(),'DONE',@user);";
            migration.Synchronize();

            using (IDbConnection connection = InitializeConnectionForTests())
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM ScriptLog WHERE DomainUser IS NOT NULL";
                var count = (int)command.ExecuteScalar();
                Assert.Greater(count, 0, "The entries with a not null user should exist in the database");

                command             = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM Mytable WHERE GoodTable = 'SuperUser'";
                count = (int)command.ExecuteScalar();
                Assert.AreEqual(1, count, "Mytable should have an entry with a dynamic parameter user (GoodTable column) resolved to 'SuperUser'");
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 検索処理の実行
        /// </summary>
        /// <returns></returns>
        private async Task ExecuteSearch()
        {
            try
            {
                EnableProcessingMode();

                // DBが古い場合はアップグレードする
                if (DatabaseMigration.GetCurrentVersion() < DatabaseContext.Version)
                {
                    DatabaseMigration.UpgradeDatabase();
                }

                var parameter = new ActivityLogSearchParameter
                {
                    IsJoinedRoom                    = joinCheckBox.IsChecked ?? false,
                    IsMetPlayer                     = meetCheckBox.IsChecked ?? false,
                    IsSendInvite                    = sendInvCheckBox.IsChecked ?? false,
                    IsSendRequestInvite             = sendReqInvCheckBox.IsChecked ?? false,
                    IsReceivedInvite                = recvInvCheckBox.IsChecked ?? false,
                    IsReceivedRequestInvite         = recvReqInvCheckBox.IsChecked ?? false,
                    IsSendFriendRequest             = sendFriendReqCheckBox.IsChecked ?? false,
                    IsReceivedFriendRequest         = recvFriendReqCheckBox.IsChecked ?? false,
                    IsAcceptFriendRequest           = acptFriendReqCheckBox.IsChecked ?? false,
                    FromDateTime                    = fromDatePicker.SelectedDate,
                    UntilDateTime                   = untilDatePicker.SelectedDate?.AddDays(1),
                    IsReceivedInviteResponse        = recvInvResCheckBox.IsChecked ?? false,
                    IsReceivedRequestInviteResponse = recvReqInvResCheckBox.IsChecked ?? false,
                    IsPlayedVideo                   = videoCheckBox.IsChecked ?? false,
                };
                var activityLogs = await VRChatActivityLogModel.SearchActivityLogs(parameter);

                var keywords = keywordBox.Text.Split(' ').Where(s => s != string.Empty).ToArray();

                ActivityLogGridModelCollection.Clear();

                foreach (var activityLog in activityLogs)
                {
                    var gridModel = new ActivityLogGridModel(activityLog);

                    if (keywords.Any())
                    {
                        var contained = keywords.All(k => gridModel.Content?.Contains(k, StringComparison.CurrentCultureIgnoreCase) ?? false);
                        if (!contained)
                        {
                            continue;
                        }
                    }

                    ActivityLogGridModelCollection.Add(gridModel);
                }

                DisableProcessingMode();
            }
            catch (Exception)
            {
                MessageBox.Show("エラーが発生しました。プログラムを終了します。", "VRChatActivityLogViewer", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }
        }
Exemplo n.º 4
0
 //[Fact]
 public void automatic_a_test()
 {
     DatabaseMigration.ConfigureFor(_db)
     .WithLogger(new ConsoleLogger())
     //.WithResolver(ActivatorContainer.Instance)
     .SearchAssemblyOf <AutomaticMigrationTests>()
     .PerformAutomaticMigrations();
 }
Exemplo n.º 5
0
 IManageMigrations BuildManager()
 {
     return(DatabaseMigration.ConfigureFor(_db)
            .SearchAssembly(Assembly.GetExecutingAssembly())
            .WithLogger(new ConsoleLogger())
            .WithResolver(ActivatorContainer.Instance)
            .Build());
 }
Exemplo n.º 6
0
 public void missing_migrations_throws()
 {
     Assert.Throws <MigrationNotFoundException>(
         () => DatabaseMigration.ConfigureFor(_db)
         .SearchAssembly(Assembly.GetCallingAssembly())
         .WithLogger(new ConsoleLogger())
         .WithResolver(ActivatorContainer.Instance)
         .Build());
 }
Exemplo n.º 7
0
        public void TestMigratingOldDatabase()
        {
            string tmpPath        = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string homePath       = Path.Combine(tmpPath, "LongoMatch");
            string dbPath         = Path.Combine(homePath, "db");
            string lmdbPath       = Path.Combine(dbPath, "longomatch.ldb");
            string teamsPath      = Path.Combine(dbPath, "teams");
            string dashboardsPath = Path.Combine(dbPath, "analysis");

            Directory.CreateDirectory(tmpPath);
            Directory.CreateDirectory(homePath);
            Directory.CreateDirectory(dbPath);
            Directory.CreateDirectory(lmdbPath);
            Directory.CreateDirectory(teamsPath);
            Directory.CreateDirectory(dashboardsPath);

            Utils.SaveResource("spain.ltt", teamsPath);
            Utils.SaveResource("france.ltt", teamsPath);
            Utils.SaveResource("basket.lct", dashboardsPath);
            Utils.SaveResource("spain_france_test.lgm", lmdbPath);

            // Create an empty project file that shouldn't be converter
            File.Open(Path.Combine(lmdbPath, "empty.lgm"), FileMode.Create);

            Directory.CreateDirectory(tmpPath);
            Environment.SetEnvironmentVariable("LONGOMATCH_HOME", tmpPath);
            Environment.SetEnvironmentVariable("LGM_UNINSTALLED", "1");
            App.Init();
            CoreServices.Init();
            App.Current.LicenseManager            = mockLicenseManager.Object;
            App.Current.LicenseLimitationsService = mockLicenseLimitationService.Object;
            App.Current.PreviewService            = new Mock <IPreviewService> ().Object;
            CoreServices.Start(guiToolkitMock.Object, multimediaToolkitMock.Object);

            Assert.AreEqual(0, App.Current.DatabaseManager.ActiveDB.Count <LMProject> ());
            Assert.AreEqual(2, App.Current.TeamTemplatesProvider.Templates.Count);
            Assert.AreEqual(1, App.Current.CategoriesTemplatesProvider.Templates.Count);

            DatabaseMigration dbMigration = new DatabaseMigration(Mock.Of <IProgressReport> ());

            dbMigration.Start();

            App.Current.DatabaseManager.SetActiveByName("longomatch");
            Assert.AreEqual(4, App.Current.TeamTemplatesProvider.Templates.Count);
            Assert.AreEqual(2, App.Current.CategoriesTemplatesProvider.Templates.Count);
            Assert.AreEqual(1, App.Current.DatabaseManager.ActiveDB.Count <LMProject> ());

            Assert.IsTrue(File.Exists(Path.Combine(dbPath, "templates", "backup", "spain.ltt")));
            Assert.IsTrue(File.Exists(Path.Combine(dbPath, "templates", "backup", "france.ltt")));
            Assert.IsTrue(File.Exists(Path.Combine(dbPath, "templates", "backup", "basket.lct")));
            Assert.IsTrue(File.Exists(Path.Combine(dbPath, "old", "longomatch.ldb", "spain_france_test.lgm")));

            CoreServices.Stop();
        }
 public static void RunMigrations(string connectionString)
 {
     using (var db = new SqlFuConnection(connectionString))
     {
         DatabaseMigration <SqlFuConnection>
         .ConfigureFor(db)
         .SearchAssemblyOf <SqlFuMigration1>()
         .WithAutomaticMigrationRepository(new SqlFuAutomaticMigrationRepo(db))
         .WithUnitOfWorkCreator(new DatabaseTransactionManager())
         .PerformAutomaticMigrations();
     }
 }
        public void TestConfiguration()
        {
            DatabaseMigration migration = Initialize();

            Assert.AreEqual(ConfigurationManager.AppSettings["SqlForward.DatabaseScripts"],
                            migration.DatabaseScripts,
                            "Expected that the DatabaseScripts property will be equal to the Application Config SqlForward.DatabaseScripts");

            migration.DatabaseScripts = "DatabaseMigrations/TestInitialization";
            Assert.AreEqual("DatabaseMigrations/TestInitialization",
                            migration.DatabaseScripts,
                            "Expected that the DatabaseScripts property will be equal to what it is explicitly set to it.");
        }
        public void TestInitialization()
        {
            DatabaseMigration migration = Initialize();

            migration.DatabaseScripts = "./DatabaseMigrations/TestInitialization/";
            migration.Synchronize();

            using (IDbConnection connection = InitializeConnectionForTests())
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM ScriptLog";
                var count = (int)command.ExecuteScalar();
                Assert.Greater(count, 0, "There is no ScriptLog entries, but it should have at least the initialization script");
            }
        }
        public static void RunMigrations(string connectionString)
        {
            var connection = new AzureSearchConnection();

            connection.ConnectionString = ConfigurationManager.ConnectionStrings[connectionString].ConnectionString;

            using (var db = ApiConnection.Create(connection.Service, connection.Key))
            {
                DatabaseMigration <ApiConnection>
                .ConfigureFor(db)
                .SearchAssemblyOf <SqlFuMigration1>()
                .WithAutomaticMigrationRepository(new AzureSearchAutomaticMigrationRepo(db))
                .PerformAutomaticMigrations();
            }
        }
Exemplo n.º 12
0
        public void TestNoOldDatabaseToMigrate()
        {
            string tmpPath        = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string homePath       = Path.Combine(tmpPath, "LongoMatch");
            string dbPath         = Path.Combine(homePath, "db");
            string lmdbPath       = Path.Combine(dbPath, "longomatch.ldb");
            string teamsPath      = Path.Combine(dbPath, "teams");
            string dashboardsPath = Path.Combine(dbPath, "analysis");

            Directory.CreateDirectory(tmpPath);
            Directory.CreateDirectory(homePath);

            Environment.SetEnvironmentVariable("LONGOMATCH_HOME", tmpPath);
            Environment.SetEnvironmentVariable("LGM_UNINSTALLED", "1");
            App.Init();
            CoreServices.Init();
            App.Current.LicenseManager            = mockLicenseManager.Object;
            App.Current.LicenseLimitationsService = mockLicenseLimitationService.Object;
            App.Current.PreviewService            = new Mock <IPreviewService> ().Object;
            CoreServices.Start(guiToolkitMock.Object, multimediaToolkitMock.Object);

            Assert.AreEqual(0, App.Current.DatabaseManager.ActiveDB.Count <LMProject> ());
            Assert.AreEqual(2, App.Current.TeamTemplatesProvider.Templates.Count);
            Assert.AreEqual(1, App.Current.CategoriesTemplatesProvider.Templates.Count);

            DatabaseMigration dbMigration = new DatabaseMigration(Mock.Of <IProgressReport> ());

            dbMigration.Start();

            Assert.AreEqual(0, App.Current.DatabaseManager.ActiveDB.Count <LMProject> ());
            Assert.AreEqual(2, App.Current.TeamTemplatesProvider.Templates.Count);
            Assert.AreEqual(1, App.Current.CategoriesTemplatesProvider.Templates.Count);

            // Directory exists but it's empty
            Directory.CreateDirectory(dbPath);
            Directory.CreateDirectory(lmdbPath);
            Directory.CreateDirectory(teamsPath);
            Directory.CreateDirectory(dashboardsPath);

            dbMigration = new DatabaseMigration(Mock.Of <IProgressReport> ());
            dbMigration.Start();

            Assert.AreEqual(0, App.Current.DatabaseManager.ActiveDB.Count <LMProject> ());
            Assert.AreEqual(2, App.Current.TeamTemplatesProvider.Templates.Count);
            Assert.AreEqual(1, App.Current.CategoriesTemplatesProvider.Templates.Count);

            CoreServices.Stop();
        }
Exemplo n.º 13
0
        private void BtnTransferFIle_Click(object sender, EventArgs e)
        {
            DatabaseMigration DM = new DatabaseMigration();

            //DM.Interface(TextLog);
            DM.SetConfig();
            Task task = new Task(() =>
            {
                DM.Detach(TextLog);
                DM.TransferFile(TextLog);
                DM.Attach(TextLog);
                DM.SetText(TextLog, "---------------------------------------------------\r\n");
            });

            task.Start();
        }
Exemplo n.º 14
0
        public async Task <DatabaseMigration> CreateAsync(CreateDatabaseMigrationRequest request)
        {
            Ensure.NotNull(request, nameof(request));

            var id = await DatabaseMigrationId.NextAsync(db.Context, request.DatabaseId);

            var migration = new DatabaseMigration(
                id: id,
                schemaName: request.SchemaName,
                commands: request.Commands,
                description: request.Description
                );

            await db.DatabaseMigrations.InsertAsync(migration);

            return(migration);
        }
Exemplo n.º 15
0
        protected override void OnStartup(StartupEventArgs e)
        {
            DatabaseMigration dbMigration = new DatabaseMigration();

            dbMigration.MigrationController();


            Process current = Process.GetCurrentProcess();

            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            if (processes.Count() > 1)
            {
                this.Shutdown();
            }
            string fontFolderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts);

            Shell32.Folder fontFolder  = GetShell32NameSpaceFolder(fontFolderPath);
            string         base_folder = System.AppDomain.CurrentDomain.BaseDirectory + "in\\";
            string         segueUi     = "segoeui.ttf";
            string         sarabunBold = "THSarabun Bold.ttf";
            string         sarabun     = "THSarabun.ttf";

            if (fontFolder != null)
            {
                string fontSegoeUI = base_folder + segueUi;
                if (!File.Exists(fontFolderPath + "\\" + segueUi))
                {
                    fontFolder.CopyHere(fontSegoeUI, 4);
                }

                string fontSarabunBold = base_folder + sarabunBold;
                if (!File.Exists(fontFolderPath + "\\" + sarabunBold))
                {
                    fontFolder.CopyHere(fontSarabunBold, 4);
                }


                string fontSarabun = base_folder + sarabun;
                if (!File.Exists(fontFolderPath + "\\" + sarabun))
                {
                    fontFolder.CopyHere(fontSarabun, 4);
                }
            }
        }
        protected DatabaseMigration Initialize(bool cleanup = true)
        {
            if (cleanup && ConfigurationManager.AppSettings["SqlForward.Test.Cleanup"] != null)
            {
                using (var connection = InitializeConnectionForTests())
                {
                    connection.ChangeDatabase("master");
                    var cleanCommand = connection.CreateCommand();
                    cleanCommand.CommandText = ConfigurationManager.AppSettings["SqlForward.Test.Cleanup"];
                    cleanCommand.ExecuteNonQuery();
                }
            }

            DatabaseMigration migration = new DatabaseMigration(InitializeConnectionForTests);

            migration.Changed += (o, e) => System.Console.WriteLine(e.Message);
            return(migration);
        }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            DatabaseMigration.MigrateToLatest(app);

#if BLAZOR_SERVER
            app.Map("/blazorserver", appBuilder => ConfigureBlazor(appBuilder, env, false));
#endif
#if BLAZOR_CLIENT
            app.Map("/blazorclient", appBuilder => ConfigureBlazor(appBuilder, env, true));
#endif

            app.RegisterSwaggerMiddleware();
            app.RegisterSwaggerUI();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            if (!env.IsDevelopment())
            {
                app.UseHttpsRedirection();
            }

            UseLaterListStaticFiles(app, env);
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapGet("/index.html", r =>
                {
                    r.Response.Redirect("/");
                    return(Task.CompletedTask);
                });
                endpoints.MapFallbackToPage("/Project");
                endpoints.MapControllers();
            });
        }
        public void TestSuccessStory()
        {
            // First Migrations
            int events = 0;
            DatabaseMigration migration = Initialize();

            migration.DatabaseScripts = "./DatabaseMigrations/TestSuccessStory/";
            migration.Changed        += (o, e) => events++;
            migration.Synchronize();

            using (IDbConnection connection = InitializeConnectionForTests())
            {
                //Assert.AreEqual(5, events, "Expected events: Started, Initialization, Migration x 2, Finished")

                IDbCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM ScriptLog";
                var count = (int)command.ExecuteScalar();
                Assert.AreEqual(3, count, "Rev001, Rev002 seem to be not executed.");

                command             = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM Mytable";
                count = (int)command.ExecuteScalar();
                Assert.AreEqual(4, count, "Mytable doesn't have the correct number of entries. ");
            }

            //Second Migrations
            migration = Initialize(false);
            migration.DatabaseScripts = "./DatabaseMigrations/TestSuccessStorySecondGo/";
            migration.Synchronize();

            using (IDbConnection connection = InitializeConnectionForTests())
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM ScriptLog";
                var count = (int)command.ExecuteScalar();
                Assert.AreEqual(5, count, "Rev003, Rev004 seem to be not executed.");

                command             = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM MySecondTable";
                count = (int)command.ExecuteScalar();
                Assert.AreEqual(5, count, "MySecondTable doesn't have the correct number of entries. ");
            }
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Building configuration");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true)
                                           .Build();

            if (string.IsNullOrWhiteSpace(configuration["DatabaseConnection"]))
            {
                throw new Exception("Database name is null");
            }

            Console.WriteLine("Done building configuration");
            Console.WriteLine("Updating database");

            DatabaseMigration migration = new DatabaseMigration(new DatabaseMigrationConfig(configuration["DatabaseConnection"]));

            migration.Update();

            Console.WriteLine("Done updating database");
        }
        public void TestFailureStory()
        {
            // First Migrations
            DatabaseMigration migration = Initialize();

            migration.DatabaseScripts = "./DatabaseMigrations/TestFailureStory/";
            bool hadErrorOnRev2 = false;

            migration.Changed += (o, e) =>
            {
                if (e.CurrentStage == DatabaseMigrationStage.Migrating &&
                    e.CurrentMigration != null && e.CurrentMigration.StartsWith("Rev002"))
                {
                    if (e.Exception != null)
                    {
                        hadErrorOnRev2 = true;
                    }
                }
            };
            Assert.Throws <System.Data.SqlClient.SqlException>(() => migration.Synchronize());

            Assert.IsTrue(hadErrorOnRev2, "There should be at least one error shown on this migration (Rev002)");


            using (IDbConnection connection = InitializeConnectionForTests())
            {
                IDbCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM ScriptLog";
                var count = (int)command.ExecuteScalar();
                Assert.AreEqual(2, count, "There should be the initialization script, Rev001 only!");

                command             = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM Mytable";
                count = (int)command.ExecuteScalar();
                Assert.AreEqual(1, count, "Mytable should have only one entry, because Rev003 shouldn't be executed if Rev002 failed..");
            }
        }
Exemplo n.º 21
0
        public static void AddAndStartDatabaseMigration(this IServiceCollection serviceCollection, IConfiguration configuration)
        {
            DatabaseMigration migration = new DatabaseMigration(new DatabaseMigrationConfig(configuration["DatabaseConnection"]));

            migration.Update();
        }
Exemplo n.º 22
0
        /// <summary>
        /// 処理を実行します。
        /// </summary>
        /// <returns></returns>
        public int Run()
        {
            var logger = Logger.GetLogger();

            try
            {
                ClearErrorInfoFile();

                // ログ解析
                var activityLogs = new List <ActivityLog>();
                foreach (var file in Directory.EnumerateFiles(VRChatLogFilePath, "output_log_*"))
                {
                    logger.Debug("ログを解析中 " + file);
                    activityLogs.AddRange(ParseVRChatLog(file));
                }
                activityLogs = activityLogs.OrderBy(a => a.Timestamp).ToList();

                // DBファイルチェック
                if (!File.Exists(DatabaseContext.DBFilePath))
                {
                    logger.Info("データベースファイルが見つかりませんでした。新しく作成します。");

                    DatabaseMigration.CreateDatabase();

                    logger.Info("データベースファイルを作成しました。");
                }

                // DBバージョンチェック
                var currentVersion = DatabaseMigration.GetCurrentVersion();

                if (currentVersion < DatabaseContext.Version)
                {
                    logger.Info("古いバージョンのデータベースを使用しています。データベースのアップグレードを行います。");

                    DatabaseMigration.UpgradeDatabase();

                    logger.Info("データベースをアップグレードしました。");
                }
                else if (DatabaseContext.Version < currentVersion)
                {
                    throw new InvalidOperationException("新しいバージョンのアプリで作成されたデータベースが存在するため、処理を中断します。");
                }

                // DB更新
                using (var db = new DatabaseContext())
                {
                    var lastActivity = db.ActivityLogs.Find(db.ActivityLogs.Max(a => a.ID));
                    if (lastActivity != null)
                    {
                        var idBackup = lastActivity.ID;
                        lastActivity.ID = null;
                        for (int i = 0; i < activityLogs.Count; i++)
                        {
                            if (activityLogs[i].Timestamp == lastActivity.Timestamp)
                            {
                                if (activityLogs[i].Equals(lastActivity))
                                {
                                    activityLogs.RemoveRange(0, i + 1);
                                    break;
                                }
                            }
                        }
                        lastActivity.ID = idBackup;
                    }

                    using (var transaction = db.Database.BeginTransaction())
                    {
                        try
                        {
                            foreach (var activityLog in activityLogs)
                            {
                                db.Add(activityLog);
                                db.SaveChanges();
                            }
                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }

                logger.Info(activityLogs.Count + "件追加しました。");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                WriteErrorInfoFile();
                return(-1);
            }
            return(0);
        }
 public CommandHandler(DatabaseMigration databaseMigration)
 => this._databaseMigration = databaseMigration;