BF2Statistics.Database.GamespyDatabase.MigrateTables C# (CSharp) Method

MigrateTables() public method

If there is any table updates that need to be applied, calling this method will apply each update until the current database version is up to date
public MigrateTables ( ) : void
return void
        public void MigrateTables()
        {
            // If we dont need updated, what are we doing here?
            if (!NeedsUpdated) return;

            // MD5 Hash Update, only update to date so i will make this better in the future
            if(Version.Major == 2 && Version.Minor == 0)
            {
                // In this update, we hash all of the passwords to MD5!
                using (DbTransaction Transaction = base.BeginTransaction())
                {
                    try
                    {
                        // Set the column length to 32, since this is the MD5 hash length
                        if (base.DatabaseEngine == DatabaseEngine.Mysql)
                            base.Execute("ALTER TABLE accounts MODIFY COLUMN password VARCHAR(32) NOT NULL");

                        // Here we use the QueryReader method to pull 1 row at a time, using memory efficiently
                        foreach (Dictionary<string, object> Row in base.Query("SELECT id, password FROM accounts"))
                        {
                            base.Execute("UPDATE accounts SET password=@P0 WHERE id=@P1",
                                Row["password"].ToString().GetMD5Hash(false),
                                Row["id"]
                            );
                        }

                        // Delete old version data
                        base.Execute("DELETE FROM _version");

                        // Run the alter table command on MySql, SQLite does not support this
                        if (base.DatabaseEngine == DatabaseEngine.Mysql)
                        {
                            base.Execute("ALTER TABLE _version MODIFY dbver VARCHAR(4)");
                        }
                        else
                        {
                            base.Execute("DROP TABLE IF EXISTS \"main\".\"_version\"");
                            base.Execute("CREATE TABLE \"main\".\"_version\"(\"dbver\" TEXT NOT NULL DEFAULT 0, \"dbdate\" INT NOT NULL DEFAULT 0, PRIMARY KEY (\"dbver\"));");
                        }

                        // Insert New Data
                        base.Execute("INSERT INTO _version(dbver, dbdate) VALUES (@P0, @P1)", "2.1", DateTime.UtcNow.ToUnixTimestamp());
                        Transaction.Commit();

                        // Set new version
                        Version = new Version(2, 1);
                    }
                    catch
                    {
                        Transaction.Rollback();
                        throw;
                    }
                }
            }
        }

Usage Example

        /// <summary>
        /// Starts the Login Server listeners, and begins accepting new connections
        /// </summary>
        public static void Start()
        {
            // Make sure we arent already running!
            if (bIsRunning) return;

            // Start the DB Connection
            using (GamespyDatabase Database = new GamespyDatabase())
            {
                // First, make sure our account table exists
                if (!Database.TablesExist)
                {
                    string message = "In order to use the Gamespy Emulation feature of this program, we need to setup a database. "
                    + "You may choose to do this later by clicking \"Cancel\". Would you like to setup the database now?";
                    DialogResult R = MessageBox.Show(message, "Gamespy Database Setup", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (R == DialogResult.Yes)
                        SetupManager.ShowDatabaseSetupForm(DatabaseMode.Gamespy, MainForm.Instance);

                    // Call the stoOnShutdown event to Re-enable the main forms buttons
                    Stopped();
                    return;
                }
                else if (Database.NeedsUpdated)
                {
                    // We cannot run an outdated database
                    DialogResult R = MessageBox.Show(
                        String.Format(
                            "The Gamespy database tables needs to be updated to version {0} before using this feature. Would you like to do this now?",
                            GamespyDatabase.LatestVersion
                        ) + Environment.NewLine.Repeat(1) +
                        "NOTE: You should backup your gamespy account table if you are unsure as this update cannot be undone!",
                        "Gamespy Database Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question
                    );

                    // If the user doesnt migrate the database tables, quit
                    if (R != DialogResult.Yes)
                    {
                        // Call the stoOnShutdown event to Re-enable the main forms buttons
                        Stopped();
                        return;
                    }

                    // Do table migrations
                    Database.MigrateTables();
                }
            }

            // Bind gpcm server on port 29900
            int port = 29900;

            // Setup the DebugLog
            DebugLog.LoggingEnabled = Program.Config.GamespyServerDebug;
            if (Program.Config.GamespyServerDebug)
                DebugLog.ClearLog();

            try
            {
                // Begin logging
                DebugLog.Write("=== Gamespy Emulator Initializing ===");
                DebugLog.Write("Starting Client Manager");

                // Start the client manager
                ClientManager = new GpcmServer();

                // Begin logging
                DebugLog.Write("Bound to TCP port: " + port);
                DebugLog.Write("Starting Account Service Provider");

                // Start search provider server
                port++;
                SearchProvider = new GpspServer();

                // Begin logging
                DebugLog.Write("Bound to TCP port: " + port);
                DebugLog.Write("Starting Master Server");

                // Start then Master Server
                MasterServer = new MasterServer(ref port, DebugLog);

                // Start CDKey Server
                port = 29910;
                DebugLog.Write("Starting Cdkey Server");
                CDKeyServer = new CDKeyServer(DebugLog);

                // Begin logging
                DebugLog.Write("=== Gamespy Emulator Initialized ===");
            }
            catch (Exception E)
            {
                Notify.Show(
                    "Failed to Start Gamespy Servers!",
                    "Error binding to port " + port + ": " + Environment.NewLine + E.Message,
                    AlertType.Warning
                );

                // Append log
                if (DebugLog != null)
                {
                    DebugLog.Write("=== Failed to Start Emulator Servers! ===");
                    DebugLog.Write("Error binding to port " + port + ": " + E.Message);
                }

                // Shutdown all started servers
                if (ClientManager != null && ClientManager.IsListening) ClientManager.Shutdown();
                if (SearchProvider != null && SearchProvider.IsListening) SearchProvider.Shutdown();
                if (MasterServer != null && MasterServer.IsRunning) MasterServer.Shutdown();
                // Cdkey server must have throwm the exception at this point, since it starts last

                // Throw excpetion to parent
                throw;
            }

            // Let the client know we are ready for connections
            bIsRunning = true;
            Started();
        }