Ejemplo n.º 1
0
        private void CreateInitialCompanies(IDbConnection connection)
        {
            string    _path  = Application.StartupPath + "\\Xml\\defaultcompanies.xml";
            DataTable _table = SCMS.XmlToTable(_path);

            if (_table != null)
            {
                Cache.SyncTable(connection, "companies");

                DataTable _cachedtable = Cache.GetCachedTable("companies");
                if (_cachedtable != null)
                {
                    string _query = "";

                    for (int i = 0; i <= (_table.Rows.Count - 1); i++)
                    {
                        DataRow   _row  = _table.Rows[i];
                        DataRow[] _rows = _cachedtable.Select("[Company] LIKE '" + _row["Company"].ToString().ToSqlValidString(true) + "'");
                        if (_rows.Length <= 0)
                        {
                            _query += "INSERT INTO `companies`\n" +
                                      "(`Company`, `Name`, `DateCreated`)\n" +
                                      "VALUES\n" +
                                      "('" + _row["Company"].ToString().ToSqlValidString() + "', '" + _row["Name"].ToString().ToSqlValidString() + "', NOW());\n";

                            DataColumnCollection _cols   = _cachedtable.Columns;
                            object[]             _values = new object[_cols.Count];
                            _values[_cols["Company"].Ordinal]      = _row["Company"];
                            _values[_cols["Name"].Ordinal]         = _row["Name"];
                            _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                            _values[_cols["LastModified"].Ordinal] = DateTime.Now;
                            _cachedtable.Rows.Add(_values);
                        }
                    }

                    if (!String.IsNullOrEmpty(_query.RLTrim()))
                    {
                        QueResult _result = Que.Execute(connection, _query);
                        if (String.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            _cachedtable.AcceptChanges(); Cache.Save();
                        }
                        _result.Dispose(); _result = null; Materia.RefreshAndManageCurrentProcess();
                    }
                }

                _table.Dispose(); _table = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
Ejemplo n.º 2
0
        private void RunRestoration()
        {
            if (!File.Exists(_backupfilename))
            {
                MsgBoxEx.Shout("Could not locate the specified database backup file / restore point.", "Database Restoration"); return;
            }

            btnBrowseDrive.Enabled        = false; btnBrowseRestorePoint.Enabled = false;
            btnRestore.Enabled            = false; btnCancel.BringToFront(); InitializeEventGrid();
            chkCreateRestorePoint.Enabled = false; pctLoad.Show(); pctLoad.BringToFront();
            _isrunning = true; _cancelled = false;

            AddEvent(BackupEvent.Information, "Starting database restoration routines...");
            RestorePointInfo _restorepoint = null;

            if (chkCreateRestorePoint.Checked)
            {
                _restorepoint = MakeRestorePoint();
                if (_restorepoint == null)
                {
                    btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                    btnRestore.Enabled            = true; btnCancel.SendToBack();
                    chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                    _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return;
                }
            }

            string _filename = _backupfilename; int _trycounter = 0;

            if (Path.GetExtension(_filename).ToLower().Replace(".", "").RLTrim() == "scmsiv")
            {
                AddEvent(BackupEvent.Information, "Extracting database backup...");
                _filename = "";

                string _dbtempdir = Application.StartupPath + "\\dbtemp";
                if (!Directory.Exists(_dbtempdir))
                {
                    try { Directory.CreateDirectory(_dbtempdir); }
                    catch (Exception ex)
                    {
                        SCMS.LogError(this.GetType().Name, ex);
                        AddEvent(BackupEvent.Error, "Could not create temporary backup file extraction directory.");

                        btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                        btnRestore.Enabled            = true; btnCancel.SendToBack();
                        chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                        _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return;
                    }
                }

                string _archivedir = _dbtempdir + "\\" + Path.GetFileNameWithoutExtension(_backupfilename);

                Func <string, string, bool> _extractordelegate = new Func <string, string, bool>(Archiver.Decompress);
                IAsyncResult _extractorresult = _extractordelegate.BeginInvoke(_backupfilename, _archivedir, null, _extractordelegate);

                while (!_extractorresult.IsCompleted &&
                       !_cancelled)
                {
                    Thread.Sleep(1); Application.DoEvents();
                }

                if (_cancelled)
                {
                    AddEvent(BackupEvent.Warning, "Cancelling database restoration...");

                    _trycounter = 0;

                    while (Directory.Exists(_archivedir) &&
                           _trycounter <= 30)
                    {
                        try { Directory.Delete(_archivedir, true); }
                        catch { }

                        _trycounter += 1;
                        Thread.Sleep(100); Application.DoEvents();
                    }

                    btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                    btnRestore.Enabled            = true; btnCancel.SendToBack();
                    chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                    _isrunning = false; Materia.RefreshAndManageCurrentProcess();

                    AddEvent(BackupEvent.Information, "Cancelled database restoration.");

                    _trycounter = 0;

                    while (_trycounter < 10)
                    {
                        Thread.Sleep(100); Application.DoEvents();
                        _trycounter += 1;
                    }
                }
                else
                {
                    bool _extracted = _extractordelegate.EndInvoke(_extractorresult);

                    if (_extracted)
                    {
                        if (Directory.Exists(_archivedir))
                        {
                            string[] _files = Directory.GetFiles(_archivedir);
                            foreach (string _file in _files)
                            {
                                if (Path.GetExtension(_file).ToLower().Replace(".", "").RLTrim() == "sql")
                                {
                                    _filename = _file; break;
                                }
                            }

                            if (String.IsNullOrEmpty(_filename.RLTrim()))
                            {
                                AddEvent(BackupEvent.Error, "Could not find any supported database backup file.");

                                _trycounter = 0;

                                while (Directory.Exists(_archivedir) &&
                                       _trycounter <= 30)
                                {
                                    try { Directory.Delete(_archivedir, true); }
                                    catch { }

                                    _trycounter += 1;
                                    Thread.Sleep(100); Application.DoEvents();
                                }

                                btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                                btnRestore.Enabled            = true; btnCancel.SendToBack();
                                chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                                _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return;
                            }
                        }
                        else
                        {
                            AddEvent(BackupEvent.Error, "Could not extract data from database backup.");

                            _trycounter = 0;

                            while (Directory.Exists(_archivedir) &&
                                   _trycounter <= 30)
                            {
                                try { Directory.Delete(_archivedir, true); }
                                catch { }

                                _trycounter += 1;
                                Thread.Sleep(100); Application.DoEvents();
                            }

                            btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                            btnRestore.Enabled            = true; btnCancel.SendToBack();
                            chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                            _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return;
                        }
                    }
                    else
                    {
                        AddEvent(BackupEvent.Error, "Could not extract data from database backup.");

                        _trycounter = 0;

                        while (Directory.Exists(_archivedir) &&
                               _trycounter <= 30)
                        {
                            try { Directory.Delete(_archivedir, true); }
                            catch { }

                            _trycounter += 1;
                            Thread.Sleep(100); Application.DoEvents();
                        }

                        btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                        btnRestore.Enabled            = true; btnCancel.SendToBack();
                        chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                        _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return;
                    }
                }
            }

            if (!String.IsNullOrEmpty(_filename.RLTrim()))
            {
                FileInfo _backupfile = new FileInfo(_filename);
                Func <string, FileInfo, MySqlResult> _restoredelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute);
                IAsyncResult _restoreresult = _restoredelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _backupfile, null, _restoredelegate);

                while (!_restoreresult.IsCompleted &&
                       !_cancelled)
                {
                    Thread.Sleep(1); Application.DoEvents();
                }

                if (_cancelled)
                {
                    AddEvent(BackupEvent.Warning, "Cancelling database restoration...");

                    if (_restorepoint != null)
                    {
                        if (File.Exists(_restorepoint.Filename))
                        {
                            AddEvent(BackupEvent.Information, "Performing roll back from recorded restore point.");
                            FileInfo _restorepointfile = new FileInfo(_restorepoint.Filename);

                            _trycounter = 0;
                            while (_trycounter < 30)
                            {
                                _trycounter += 1;
                                Thread.Sleep(100); Application.DoEvents();
                            }

                            Func <string, FileInfo, MySqlResult> _restorepointdelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute);
                            IAsyncResult _restorepointresult = _restorepointdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _restorepointfile, null, _restorepointdelegate);
                            _restorepointresult.WaitToFinish();

                            MySqlResult _rpresult = _restorepointdelegate.EndInvoke(_restorepointresult);

                            if (_rpresult.Succeeded)
                            {
                                AddEvent(BackupEvent.Success, "Roll back from recorded restore point has been completed.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_rpresult.Error));
                                AddEvent(BackupEvent.Error, "Failed to roll back from restore point.");
                            }
                        }
                    }

                    SCMS.CleanUp();
                    btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                    btnRestore.Enabled            = true; btnCancel.SendToBack();
                    chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                    _isrunning = false; Materia.RefreshAndManageCurrentProcess();

                    AddEvent(BackupEvent.Information, "Cancelled database restoration.");

                    _trycounter = 0;

                    while (_trycounter < 30)
                    {
                        Thread.Sleep(100); Application.DoEvents();
                        _trycounter += 1;
                    }
                }
                else
                {
                    MySqlResult _execresult = _restoredelegate.EndInvoke(_restoreresult);

                    if (_execresult.Succeeded)
                    {
                        AddEvent(BackupEvent.Information, "Finalizing database restoration...");
                        IAsyncResult _logresult   = SCMS.CurrentSystemUser.LogActionAsync(UserAction.RestoreDatabase, "Restored database from file : " + lblPath.Text.ToSqlValidString().Replace("\\\\", "\\") + ".");
                        IAsyncResult _queexresult = Que.BeginExecution(SCMS.ServerConnection.ToString(), "UPDATE `settings` SET `LastRestored` = NOW();");

                        while (!_logresult.IsCompleted &&
                               !_queexresult.IsCompleted)
                        {
                            Thread.Sleep(1); Application.DoEvents();
                        }

                        QueResult _queresult = Que.EndExecution(_queexresult);
                        _queresult.Dispose(QueResultDisposition.WithAssociatedQue);

                        SCMS.CleanUp(); _isrunning = false;

                        AddEvent(BackupEvent.Success, "Database backup restoration has been completed.");

                        _trycounter = 0;

                        while (_trycounter <= 10)
                        {
                            Thread.Sleep(100); Application.DoEvents();
                            _trycounter += 1;
                        }

                        MsgBoxEx.Inform("Application will restart for the restored values to fully take effect.", "Database Backup Restoration");
                        DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                    }
                    else
                    {
                        SCMS.LogError(this.GetType().Name, new Exception(_execresult.Error));
                        AddEvent(BackupEvent.Error, "Failed to complete database restoration from the specified database backup / restore point.");

                        if (_restorepoint != null)
                        {
                            if (File.Exists(_restorepoint.Filename))
                            {
                                AddEvent(BackupEvent.Information, "Performing roll back from recorded restore point.");
                                FileInfo _restorepointfile = new FileInfo(_restorepoint.Filename);

                                _trycounter = 0;
                                while (_trycounter < 15)
                                {
                                    _trycounter += 1;
                                    Thread.Sleep(100); Application.DoEvents();
                                }

                                Func <string, FileInfo, MySqlResult> _restorepointdelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute);
                                IAsyncResult _restorepointresult = _restorepointdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _restorepointfile, null, _restorepointdelegate);
                                _restorepointresult.WaitToFinish();

                                MySqlResult _rpresult = _restorepointdelegate.EndInvoke(_restorepointresult);

                                if (_rpresult.Succeeded)
                                {
                                    AddEvent(BackupEvent.Success, "Roll back from recorded restore point has been completed.");
                                }
                                else
                                {
                                    SCMS.LogError(this.GetType().Name, new Exception(_rpresult.Error));
                                    AddEvent(BackupEvent.Error, "Failed to roll back from restore point.");
                                }
                            }
                        }

                        SCMS.CleanUp();
                        btnBrowseDrive.Enabled        = true; btnBrowseRestorePoint.Enabled = true;
                        btnRestore.Enabled            = true; btnCancel.SendToBack();
                        chkCreateRestorePoint.Enabled = true; pctLoad.Hide();
                        _isrunning = false; Materia.RefreshAndManageCurrentProcess();
                    }
                }
            }
        }
Ejemplo n.º 3
0
        private void CreateInitialUser(IDbConnection connection)
        {
            string    _path  = Application.StartupPath + "\\Xml\\defaultusers.xml";
            DataTable _table = SCMS.XmlToTable(_path);

            if (_table != null)
            {
                DataRow[] _rows = _table.Select("[ComputerName] = '" + Environment.MachineName.ToSqlValidString(true) + "' AND " +
                                                "[UserAccount] = '" + Environment.UserName.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    Cache.SyncTable(connection, "users");
                    bool      _exists      = false;
                    DataTable _cachedtable = Cache.GetCachedTable("users");
                    if (_cachedtable != null)
                    {
                        DataRow[] _exrows = _cachedtable.Select("[Username] LIKE '" + _rows[0]["Username"].ToString().ToSqlValidString(true) + "'");
                        if (_exrows.Length > 0)
                        {
                            _exists = true;
                        }
                    }

                    if (!_exists)
                    {
                        Cache.SyncTable(connection, "departments");
                        Cache.SyncTable(connection, "positions");

                        string _query = "";  _exists = false;

                        DataTable _depttable = Cache.GetCachedTable("departments");
                        if (_depttable != null)
                        {
                            DataRow[] _exrows = _depttable.Select("[Department] LIKE '" + _rows[0]["Department"].ToString().ToSqlValidString(true) + "'");
                            if (_exrows.Length > 0)
                            {
                                _exists = true;
                            }
                        }

                        if (!_exists)
                        {
                            _query += "INSERT INTO `departments`\n" +
                                      "(`Department`, `DateCreated`)\n" +
                                      "VALUES\n" +
                                      "('" + _rows[0]["Department"].ToString().ToSqlValidString() + "', NOW());\n";

                            object[]             _values = new object[_depttable.Columns.Count];
                            DataColumnCollection _cols   = _depttable.Columns;
                            _values[_cols["Department"].Ordinal]   = _rows[0]["Department"];
                            _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                            _values[_cols["LastModified"].Ordinal] = DateTime.Now;

                            _depttable.Rows.Add(_values);
                        }

                        _exists = false;

                        DataTable _postntable = Cache.GetCachedTable("positions");
                        if (_postntable != null)
                        {
                            DataRow[] _exrows = _postntable.Select("[Position] LIKE '" + _rows[0]["Position"].ToString().ToSqlValidString(true) + "'");
                            if (_exrows.Length > 0)
                            {
                                _exists = true;
                            }
                        }

                        if (!_exists)
                        {
                            _query += "INSERT INTO `positions`\n" +
                                      "(`Position`, `DateCreated`)\n" +
                                      "VALUES\n" +
                                      "('" + _rows[0]["Position"].ToString().ToSqlValidString() + "', NOW());\n";

                            object[]             _values = new object[_postntable.Columns.Count];
                            DataColumnCollection _cols   = _postntable.Columns;
                            _values[_cols["Position"].Ordinal]     = _rows[0]["Position"];
                            _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                            _values[_cols["LastModified"].Ordinal] = DateTime.Now;

                            _postntable.Rows.Add(_values);
                        }

                        StringBuilder _privileges = new StringBuilder();

                        for (int i = 1; i <= 700; i++)
                        {
                            _privileges.Append("1");
                        }

                        _query += "INSERT INTO `users`\n" +
                                  "(`Username`, `Password`, `FirstName`, `MiddleName`, `LastName`, `Department`, `Position`, `Active`, `Role`, `Privileges`, `AllCustomers`, `AllCompanies`, `DateCreated`)\n" +
                                  "VALUES\n" +
                                  "('" + _rows[0]["Username"].ToString().ToSqlValidString() + "', '" + _rows[0]["Password"].ToString().Encrypt(SCMS.EncryptionKey).ToSqlValidString() + "', " +
                                  "'" + _rows[0]["FirstName"].ToString().ToSqlValidString() + "', '" + _rows[0]["MiddleName"].ToString().ToSqlValidString() + "', '" + _rows[0]["LastName"].ToString().ToSqlValidString() + "', " +
                                  "'" + _rows[0]["Department"].ToString().ToSqlValidString() + "', '" + _rows[0]["Position"].ToString().ToSqlValidString() + "', 1, '" + SystemUserInfo.SuperUserRole.ToSqlValidString() + "', " +
                                  "'" + _privileges.ToString() + "', 1, 1, NOW());";

                        QueResult _result = Que.Execute(connection, _query);
                        if (String.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            if (_depttable != null)
                            {
                                _depttable.AcceptChanges();
                            }
                            if (_postntable != null)
                            {
                                _postntable.AcceptChanges();
                            }
                            if (_cachedtable != null)
                            {
                                object[]             _values = new object[_cachedtable.Columns.Count];
                                DataColumnCollection _cols   = _cachedtable.Columns;
                                _values[_cols["Username"].Ordinal]     = _rows[0]["Username"];
                                _values[_cols["Password"].Ordinal]     = _rows[0]["Password"].ToString().Encrypt(SCMS.EncryptionKey);
                                _values[_cols["FirstName"].Ordinal]    = _rows[0]["FirstName"];
                                _values[_cols["MiddleName"].Ordinal]   = _rows[0]["MiddleName"];
                                _values[_cols["LastName"].Ordinal]     = _rows[0]["LastName"];
                                _values[_cols["Position"].Ordinal]     = _rows[0]["Position"];
                                _values[_cols["Department"].Ordinal]   = _rows[0]["Department"];
                                _values[_cols["Role"].Ordinal]         = SystemUserInfo.SuperUserRole;
                                _values[_cols["Privileges"].Ordinal]   = _privileges.ToString();
                                _values[_cols["AllCustomers"].Ordinal] = 1;
                                _values[_cols["AllCompanies"].Ordinal] = 1;
                                _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                                _values[_cols["DateVoided"].Ordinal]   = DBNull.Value;

                                _cachedtable.Rows.Add(_values); _cachedtable.AcceptChanges();
                            }
                            Cache.Save();
                        }
                        else
                        {
                            if (_depttable != null)
                            {
                                _depttable.RejectChanges();
                            }
                            if (_postntable != null)
                            {
                                _postntable.RejectChanges();
                            }
                            if (_cachedtable != null)
                            {
                                _cachedtable.RejectChanges();
                            }
                        }

                        _result.Dispose(); Materia.RefreshAndManageCurrentProcess();
                    }
                }

                _table.Dispose(); _table = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Executes the current database script.
        /// </summary>
        /// <returns></returns>
        public DatabaseScriptExecutionResult Execute()
        {
            DatabaseScriptExecutionResult _result = new DatabaseScriptExecutionResult(this);

            string _message = "You are about to execute a database script with the following information<br /><br />" +
                              "<b>Reference No.</b>  " + _referenceno + "<br />" +
                              "<b>System Version</b>  " + (_systemversion != Application.ProductVersion ? "<font color=\"red\">" : "") + _systemversion + (_systemversion != Application.ProductVersion ? "<\font>" : "") + "<br />" +
                              "<b>Author</b>  " + _author + "<br />" +
                              "<b>Date Created</b>  " + VisualBasic.Format(_datecreated, "dd-MMM-yyyy") + "<br />" +
                              "<b>Title</b>" + _title + "<br />" +
                              "<b>Description</b>  " + _description + "<br />" +
                              (_requiresapprestartafterexecution ||
                               _requiresbackupbeforeexecution ||
                               _requirespcrestartafterexecution ?
                               "<b>Transitions</b><br />" : "") +
                              (_requiresbackupbeforeexecution ? "  Perform database backup before execution<br />" : "") +
                              (_requiresapprestartafterexecution ? "  Restart application after execution<br />" : "") +
                              (_requirespcrestartafterexecution ? "  Restart workstation after execution<br />" : "") +
                              "<br />" +
                              "Press <font color=\"blue\">OK</font> to continue.";

            DialogResult _dialogresult = MsgBoxEx.Shout(_message, "Execute Database Script", MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button2);

            if (_dialogresult == DialogResult.OK)
            {
                if (_requiresbackupbeforeexecution)
                {
                    string _backupdir = GlobalSettings.AutomaticBackupPath;
                    if (string.IsNullOrEmpty(_backupdir.RLTrim()))
                    {
                        _backupdir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    }
                    else
                    {
                        if (!Directory.Exists(_backupdir))
                        {
                            _backupdir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        }
                    }

                    string _filename = _backupdir + "\\" + SCMS.ServerConnection.Database.ToUpper() + "_BACKUP_" + VisualBasic.Format(DateTime.Now, "dd_MM_yyyy_HH_mm_ss") + ".scmsiv";

                    DatabaseBackupDialog _dialog = new DatabaseBackupDialog(true);
                    _dialog.BackupPath = _filename;

                    DialogResult _backupresult = _dialog.ShowDialog();
                    _dialog.Dispose(); _dialog = null;
                    Materia.RefreshAndManageCurrentProcess();

                    if (_backupresult != DialogResult.OK)
                    {
                        return(_result);
                    }
                }

                InitializerDialog _loader = new InitializerDialog();
                _loader.Message = "Executing database script into " + SCMS.ServerConnection.Server + " / " + SCMS.ServerConnection.Database + "...";
                _loader.Show();  _result.Execute();

                if (_result.Executed)
                {
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ExecuteScript, "Executed a database script" + (!string.IsNullOrEmpty(_filename.RLTrim()) ? " : " + _filename : "") + ".", _referenceno);
                    _logresult.WaitToFinish();

                    IAsyncResult _syncresult = Cache.SyncTableAsync(SCMS.Connection, "scripts");
                    _syncresult.WaitToFinish();

                    DataTable _scripts = Cache.GetCachedTable("scripts");
                    DataRow[] _rows    = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                    if (_rows.Length <= 0)
                    {
                        DataColumnCollection _cols   = _scripts.Columns;
                        object[]             _values = new object[_cols.Count];
                        _values[_cols["ReferenceNo"].Ordinal]       = _referenceno;
                        _values[_cols["Author"].Ordinal]            = _author;
                        _values[_cols["Title"].Ordinal]             = _title;
                        _values[_cols["ReferenceNo"].Ordinal]       = _referenceno;
                        _values[_cols["SystemVersion"].Ordinal]     = _systemversion;
                        _values[_cols["Description"].Ordinal]       = _description;
                        _values[_cols["Script"].Ordinal]            = _sqlstatement;
                        _values[_cols["DateCreated"].Ordinal]       = _datecreated;
                        _values[_cols["Executed"].Ordinal]          = 1;
                        _values[_cols["DateExecuted"].Ordinal]      = DateTime.Now;
                        _values[_cols["RequireBackup"].Ordinal]     = (_requiresbackupbeforeexecution ? 1 : 0);
                        _values[_cols["RequireAppRestart"].Ordinal] = (_requiresapprestartafterexecution ? 1 : 0);
                        _values[_cols["RequirePcRestart"].Ordinal]  = (_requiresapprestartafterexecution ? 1 : 0);
                        _scripts.Rows.Add(_values);
                    }
                    else
                    {
                        _rows[0]["Executed"]     = 1;
                        _rows[0]["DateExecuted"] = DateTime.Now;
                    }

                    QueryGenerator _generator = new QueryGenerator(_scripts);
                    string         _query     = _generator.ToString();
                    _generator = null; Materia.RefreshAndManageCurrentProcess();

                    if (!string.IsNullOrEmpty(_query.RLTrim()))
                    {
                        IAsyncResult _queresult = Que.BeginExecution(SCMS.Connection, _query);
                        _queresult.WaitToFinish();
                        QueResult _execresult = Que.EndExecution(_queresult);

                        if (!string.IsNullOrEmpty(_execresult.Error.RLTrim()))
                        {
                            _scripts.RejectChanges();
                        }
                        else
                        {
                            _scripts.AcceptChanges();
                        }

                        _execresult.Dispose();
                    }
                }

                _loader.Close(); _loader.Dispose(); _loader = null;
                Materia.RefreshAndManageCurrentProcess();

                if (_result.Executed)
                {
                    if (_requiresapprestartafterexecution)
                    {
                        FormCollection _forms   = Application.OpenForms;
                        int            _counter = _forms.Count;

                        for (int i = (_counter - 1); i >= 0; i--)
                        {
                            Form _form = _forms[i];
                            if (!(_form is MainWindow) &&
                                !(_form is LoginDialog))
                            {
                                if (_form.TopMost)
                                {
                                    try
                                    {
                                        _form.Close(); _form.Dispose();
                                        _counter = _forms.Count;
                                    }
                                    catch { }
                                    finally { Materia.RefreshAndManageCurrentProcess(); }
                                }
                            }
                        }

                        IAsyncResult _logoutresult = SCMS.CurrentSystemUser.LogOutAsync();
                        _logoutresult.WaitToFinish();

                        Form _mainform = null;
                        System.Collections.IEnumerator _enumerators = _forms.GetEnumerator();

                        while (_enumerators.MoveNext())
                        {
                            Form _form = (Form)_enumerators.Current;
                            if (_form is MainWindow)
                            {
                                _mainform = _form; break;
                            }
                        }

                        if (_mainform != null)
                        {
                            _mainform.Close();
                        }
                    }
                    else
                    {
                        if (_requirespcrestartafterexecution)
                        {
                            IAsyncResult _logoutresult = SCMS.CurrentSystemUser.LogOutAsync();
                            _logoutresult.WaitToFinish();

                            Process.Start("cmd", "/C shutdown -f -r -t 0");
                        }
                    }
                }
                else
                {
                    MsgBoxEx.Alert("Failed to either complete or fully execute the database script.", "Execute Database Script");
                }
            }

            return(_result);
        }