private void btnExecute_Click(object sender, EventArgs e)
        {
            if (!btnExport.Enabled)
            {
                return;
            }

            if (_updated)
            {
                if (MsgBoxEx.Shout("Changes in the current database script will be saved<br />first? Continue with the exportation?", "Export Database Script", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button1) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
                btnSave_Click(btnSave, new EventArgs());
                if (_updated)
                {
                    return;
                }
            }

            DatabaseScriptInfo _script = new DatabaseScriptInfo(_referenceno);

            _script.Execute();

            try { InitializeInfo(); }
            catch { }
        }
Esempio n. 2
0
        private void btnSaveCompanies_Click(object sender, EventArgs e)
        {
            if (!btnSaveCompanies.Enabled)
            {
                return;
            }
            if (grdCompanies.DataSource == null)
            {
                return;
            }

            try { grdCompanies.Row = grdCompanies.Rows.Fixed - 1; }
            catch { }

            for (int i = 0; i <= (grdCompanies.Rows.Count - 1); i++)
            {
                if (!Materia.IsNullOrNothing(grdCompanies.Rows[i]["Company"]))
                {
                    if (String.IsNullOrEmpty(grdCompanies.Rows[i]["Company"].ToString().RLTrim()))
                    {
                        MsgBoxEx.Shout("Please specify company at entry : " + i.ToString() + ".", "Required Field Notification");
                        grdCompanies.StartEditing(i, grdCompanies.Cols["Company"].Index); return;
                    }

                    if (String.IsNullOrEmpty(grdCompanies.Rows[i]["Name"].ToString().RLTrim()))
                    {
                        MsgBoxEx.Shout("Please specify company name at entry : " + i.ToString() + ".", "Required Field Notification");
                        grdCompanies.StartEditing(i, grdCompanies.Cols["Name"].Index); return;
                    }
                }
            }

            DataTable _datasource = (DataTable)grdCompanies.DataSource;

            if (_datasource.Rows.Count <= 0)
            {
                MsgBoxEx.Shout("Please specify at leasts a company to be registered and accessed.", "Save Company List"); return;
            }

            DataTable _changes = _datasource.GetChanges();

            if (_changes != null)
            {
                try
                {
                    string _path = Application.StartupPath + "\\Xml\\defaultcompanies.xml";
                    _datasource.WriteXml(_path, XmlWriteMode.WriteSchema);
                    _datasource.AcceptChanges();
                }
                catch (Exception ex)
                {
                    SCMS.LogError(this.Name, ex);
                    MsgBoxEx.Alert("Failed to save the changes made in the list. Please try again and / or report<br />this to your System Administrator.", "Save Company List");
                }
            }
        }
Esempio n. 3
0
        private void BankInformationDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (SCMS.CurrentSystemUser == null)
            {
                return;
            }
            if (!SCMS.CurrentSystemUser.IsSignedIn)
            {
                return;
            }
            if (!TopMost)
            {
                return;
            }
            if (MdiParent != null)
            {
                if (MdiParent is MainWindow)
                {
                    if (((MainWindow)MdiParent).IsClosing)
                    {
                        return;
                    }
                }
            }

            if (_updated)
            {
                System.Windows.Forms.DialogResult _result = MsgBoxEx.Shout("You have made some updates in the current bank account. Do you<br/>want to save the changes applied before closing?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button3);

                switch (_result)
                {
                case System.Windows.Forms.DialogResult.Yes:
                    btnSave_Click(btnSaveAndClose, new EventArgs());
                    e.Cancel = _updated; break;

                case System.Windows.Forms.DialogResult.Cancel:
                    e.Cancel = true; break;

                default: break;
                }
            }

            _cancelled = (!e.Cancel);
        }
        private void GlobalSettingDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_updated)
            {
                System.Windows.Forms.DialogResult _result = MsgBoxEx.Shout("You have made some updates in the application settings. Do you<br/>want to save the changes applied before closing?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button3);

                switch (_result)
                {
                case System.Windows.Forms.DialogResult.Yes:
                    btnSave_Click(btnSave, new EventArgs());
                    e.Cancel = _updated; break;

                case System.Windows.Forms.DialogResult.Cancel:
                    e.Cancel = true; break;

                default: break;
                }
            }
        }
Esempio n. 5
0
        private void VehicleMakeInfoDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_updated)
            {
                System.Windows.Forms.DialogResult _result = MsgBoxEx.Shout("You have made some updates in the current brand. Do you<br/>want to save the changes applied before closing?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button3);

                switch (_result)
                {
                case System.Windows.Forms.DialogResult.Yes:
                    btnSave_Click(btnSaveAndClose, new EventArgs());
                    e.Cancel = _updated; break;

                case System.Windows.Forms.DialogResult.Cancel:
                    e.Cancel = true; break;

                default: break;
                }
            }

            _cancelled = (!e.Cancel);
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (!btnExport.Enabled)
            {
                return;
            }

            if (_updated)
            {
                if (MsgBoxEx.Shout("Changes in the current database script will be saved<br />first? Continue with the exportation?", "Export Database Script", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button1) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
                btnSave_Click(btnSave, new EventArgs());
                if (_updated)
                {
                    return;
                }
            }

            SaveFileDialog _dialog = new SaveFileDialog();

            _dialog.DefaultExt = SCMS.ScriptFileExtension;
            _dialog.Filter     = "SCMS database script file (*." + SCMS.ScriptFileExtension + ")|*." + SCMS.ScriptFileExtension;
            _dialog.Title      = "Export Database Script";
            _dialog.FileName   = _referenceno + "." + SCMS.ScriptFileExtension;
            if (_dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                _dialog.Dispose(); _dialog = null;
                Materia.RefreshAndManageCurrentProcess(); return;
            }

            DataTable _scripts = Cache.GetCachedTable("scripts");

            if (_scripts != null)
            {
                var _query = from _scr in _scripts.AsEnumerable()
                             where _scr.Field <string>("ReferenceNo") == _referenceno
                             select _scr;

                DataTable _script = _query.CopyToDataTable();
                _script.TableName = "scripts";
                FileInfo _exportedfile = _script.ExportData(_dialog.FileName, true);
                if (_exportedfile != null)
                {
                    Cursor = Cursors.WaitCursor;
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ExportEdi, "Exported database script into : " + _dialog.FileName + ".", _referenceno);
                    _logresult.WaitToFinish(); Cursor = Cursors.Default;
                    Process.Start("explorer.exe", "/select, \"" + _exportedfile.FullName + "\"");
                }
                else
                {
                    MsgBoxEx.Alert("Failed to export the current database script into the specified path.", "Export Database Script");
                }
                _script.Dispose(); _script = null; _exportedfile = null;
                Materia.RefreshAndManageCurrentProcess();
            }
            else
            {
                MsgBoxEx.Alert("Failed to export the current database script into the specified path.", "Export Database Script");
            }

            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
        }
        private void RunBackUp()
        {
            if (_isrunning)
            {
                return;
            }
            if (_succeeded)
            {
                _succeeded = false;
            }

            if (!Directory.Exists(Path.GetDirectoryName(lblPath.Text)))
            {
                MsgBoxEx.Shout("Please specify a valid database backup output directory.", "Database Backup"); return;
            }

            _isrunning        = true; _cancelled = false; InitializeEventGrid();
            btnBrowse.Enabled = false; btnBackup.Enabled = false;
            pctLoad.Show(); pctLoad.BringToFront(); btnCancel.BringToFront();

            AddEvent(BackupEvent.Information, "Database backup operations started.");

            string _tempdir = Application.StartupPath + "\\dbtemp\\"; int _trycounter = 0;

            if (!Directory.Exists(_tempdir))
            {
                try { Directory.CreateDirectory(_tempdir); }
                catch (Exception ex)
                {
                    SCMS.LogError(this.GetType().Name, ex);
                    AddEvent(BackupEvent.Error, "Failed to create temporary output directory.");
                    btnBrowse.Enabled          = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                    pctLoad.Hide(); _isrunning = false; btnCancel.SendToBack(); return;
                }
            }

            MySqlDumpParameterCollection _parameters = new MySqlDumpParameterCollection();

            _parameters.Add(MySqlDumpParameters.CompleteInsert);
            _parameters.Add(MySqlDumpParameters.HexBlob);
            _parameters.Add(MySqlDumpParameters.Routines);
            _parameters.Add("--skip-extended-insert");
            _parameters.Add(MySqlDumpParameters.Triggers);
            _parameters.Add(MySqlDumpParameters.Quick);

            string _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".sql";

            Func <string, string, MySqlDumpParameterCollection, MySqlResult> _dumpdelegate = new Func <string, string, MySqlDumpParameterCollection, MySqlResult>(MySql.Dump);
            IAsyncResult _dumpresult = _dumpdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _filename, _parameters, null, _dumpdelegate);

            AddEvent(BackupEvent.Information, "Running database backup operations.");

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

            if (_cancelled)
            {
                if (!_dumpresult.IsCompleted)
                {
                    try { _dumpresult = null; }
                    catch { }
                }

                AddEvent(BackupEvent.Warning, "Cancelling database backup...");

                Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                while (File.Exists(_filename) &&
                       _trycounter < 30)
                {
                    try { File.Delete(_filename); }
                    catch { }

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

                AddEvent(BackupEvent.Information, "Database backup operations has been cancelled.");
                btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                _trycounter = 0;

                while (_trycounter < 10)
                {
                    Thread.Sleep(100); Application.DoEvents();
                    _trycounter += 1;
                }
            }
            else
            {
                MySqlResult _dumpexecresult = _dumpdelegate.EndInvoke(_dumpresult);
                if (_dumpexecresult.Succeeded)
                {
                    AddEvent(BackupEvent.Information, "Database backup has been created.");
                    AddEvent(BackupEvent.Information, "Archiving backup file...");

                    Func <string, ArchivingToolEnum, FileInfo> _archiverdelegate = new Func <string, ArchivingToolEnum, FileInfo>(Archiver.CompressInsert);
                    IAsyncResult _archiverresult = _archiverdelegate.BeginInvoke(_filename, ArchivingToolEnum.SevenZip, null, _archiverdelegate);

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

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

                        Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                        while (File.Exists(_filename) &&
                               _trycounter < 30)
                        {
                            try { File.Delete(_filename); }
                            catch { }

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

                        _trycounter = 0;
                        _filename   = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z";

                        while (File.Exists(_filename) &&
                               _trycounter < 30)
                        {
                            try { File.Delete(_filename); }
                            catch { }

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

                        AddEvent(BackupEvent.Information, "Database backup operations has been cancelled.");
                        btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                        pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                        _trycounter = 0;

                        while (_trycounter < 10)
                        {
                            Thread.Sleep(100); Application.DoEvents();
                            _trycounter += 1;
                        }
                    }
                    else
                    {
                        FileInfo _archivefile = _archiverdelegate.EndInvoke(_archiverresult);

                        if (_archivefile != null)
                        {
                            AddEvent(BackupEvent.Information, "Database backup file has been archived.");
                            AddEvent(BackupEvent.Information, "Finalizing database backup operations...");

                            bool _copied = false;

                            try
                            {
                                File.Copy(_archivefile.FullName, lblPath.Text, true);
                                _copied = true;

                                Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                                while (File.Exists(_filename) &&
                                       _trycounter < 30)
                                {
                                    try { File.Delete(_filename); }
                                    catch { }

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

                                _trycounter = 0;
                                _filename   = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z";

                                while (File.Exists(_filename) &&
                                       _trycounter < 30)
                                {
                                    try { File.Delete(_filename); }
                                    catch { }

                                    _trycounter += 1; Thread.Sleep(100); Application.DoEvents();
                                }
                            }
                            catch (Exception ex)
                            {
                                SCMS.LogError(this.GetType().Name, ex);
                                AddEvent(BackupEvent.Error, "Failed to transfer archive file into output destinaton.");
                                AddEvent(BackupEvent.Warning, "Cancelling database backup...");

                                Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                                while (File.Exists(_filename) &&
                                       _trycounter < 30)
                                {
                                    try { File.Delete(_filename); }
                                    catch { }

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

                                _trycounter = 0;
                                _filename   = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z";

                                while (File.Exists(_filename) &&
                                       _trycounter < 30)
                                {
                                    try { File.Delete(_filename); }
                                    catch { }

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

                                AddEvent(BackupEvent.Information, "Database backup operations has been cancelled.");
                                btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                                pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                                _trycounter = 0;

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

                            if (_copied)
                            {
                                IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.BackupDatabase, "Performed database backup into : " + lblPath.Text.ToSqlValidString().Replace("\\\\", "\\") + ".");
                                _logresult.WaitToFinish();
                                AddEvent(BackupEvent.Success, "Database backup operations has been completed.");
                                btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                                pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                                if (!_succeeded)
                                {
                                    _succeeded = true;
                                }
                            }
                        }
                        else
                        {
                            AddEvent(BackupEvent.Error, "Database backup file archiving failed.");
                            AddEvent(BackupEvent.Warning, "Cancelling database backup...");

                            Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                            while (File.Exists(_filename) &&
                                   _trycounter < 30)
                            {
                                try { File.Delete(_filename); }
                                catch { }

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

                            _trycounter = 0;
                            _filename   = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z";

                            while (File.Exists(_filename) &&
                                   _trycounter < 30)
                            {
                                try { File.Delete(_filename); }
                                catch { }

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

                            AddEvent(BackupEvent.Information, "Database backup operations has been cancelled.");
                            btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                            pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                            _trycounter = 0;

                            while (_trycounter < 10)
                            {
                                Thread.Sleep(100); Application.DoEvents();
                                _trycounter += 1;
                            }
                        }
                    }
                }
                else
                {
                    SCMS.LogError(this.GetType().Name, new Exception(_dumpexecresult.Error));
                    AddEvent(BackupEvent.Error, "Database backup operations has been cancelled.");
                    AddEvent(BackupEvent.Warning, "Cancelling database backup...");

                    Materia.RefreshAndManageCurrentProcess(); _trycounter = 0;
                    while (File.Exists(_filename) &&
                           _trycounter < 30)
                    {
                        try { File.Delete(_filename); }
                        catch { }

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

                    AddEvent(BackupEvent.Information, "Database backup operations has been cancelled.");
                    btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose;
                    pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false;

                    _trycounter = 0;

                    while (_trycounter < 10)
                    {
                        Thread.Sleep(100); Application.DoEvents();
                        _trycounter += 1;
                    }
                }
            }
        }
        private void btnImport_Click(object sender, EventArgs e)
        {
            if (!btnImport.Enabled)
            {
                return;
            }

            OpenFileDialog _dialog = new OpenFileDialog();

            _dialog.CheckFileExists = true;
            _dialog.CheckPathExists = true;
            _dialog.DefaultExt      = SCMS.ScriptFileExtension;
            _dialog.Filter          = "SCMS Database Script Files (*." + SCMS.ScriptFileExtension + ")|*." + SCMS.ScriptFileExtension;
            _dialog.Title           = "Import Database Script File";

            if (_dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                _dialog.Dispose(); _dialog = null;
                Materia.RefreshAndManageCurrentProcess(); return;
            }

            string _filename = _dialog.FileName;

            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
            btnAdd.Enabled           = false; btnEdit.Enabled = false; btnDelete.Enabled = false;
            btnExecuteScript.Enabled = false; btnExport.Enabled = false; btnImport.Enabled = false;

            Func <string, bool, DataTable> _delegate = new Func <string, bool, DataTable>(SCMS.ImportData);
            IAsyncResult _result = _delegate.BeginInvoke(_filename, true, null, _delegate);

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

            if (_cancelled)
            {
                if (!_result.IsCompleted)
                {
                    try { _result = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }

                return;
            }
            else
            {
                DataTable _table = _delegate.EndInvoke(_result);
                if (_table != null)
                {
                    if (_table.TableName != "scripts")
                    {
                        MsgBoxEx.Shout("The specified file does not contain any relevant database script information.", "Import Database Script");
                    }
                    else
                    {
                        if (_table.Rows.Count > 0)
                        {
                            DataRow   _row     = _table.Rows[0];
                            DataTable _scripts = Cache.GetCachedTable("scripts");
                            if (_scripts != null)
                            {
                                DataRow[] _rows = _scripts.Select("[ReferenceNo] LIKE '" + _row["ReferenceNo"].ToString().ToSqlValidString(true) + "'");
                                if (_rows.Length <= 0)
                                {
                                    DataColumnCollection _cols   = _scripts.Columns;
                                    object[]             _values = new object[_cols.Count];

                                    for (int i = 0; i <= (_cols.Count - 1); i++)
                                    {
                                        if (_table.Columns.Contains(_cols[i].ColumnName))
                                        {
                                            _values[i] = _row[_cols[i].ColumnName];
                                        }
                                    }

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

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

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

                                        if (_cancelled)
                                        {
                                            if (!_execresult.IsCompleted)
                                            {
                                                try { _execresult = null; }
                                                catch { }
                                                finally { Materia.RefreshAndManageCurrentProcess(); }

                                                return;
                                            }
                                        }
                                        else
                                        {
                                            QueResult _queresult = Que.EndExecution(_execresult);

                                            if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                                            {
                                                Cursor = Cursors.WaitCursor;
                                                IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ImportEdi, "Imported database script from : " + _filename + ".", _row["ReferenceNo"].ToString());
                                                _logresult.WaitToFinish(); Cursor = Cursors.Default;

                                                _scripts.AcceptChanges(); InitializeScripts();
                                            }
                                            else
                                            {
                                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                                MsgBoxEx.Alert("Failed to import the specified database script file.", "Import Database Script");
                                            }

                                            _queresult.Dispose();
                                        }
                                    }
                                }
                                else
                                {
                                    MsgBoxEx.Shout("Database script : <font color=\"blue\">" + _row["ReferenceNo"].ToString() + "</font> already exists.", "Import Database Script");
                                }
                            }
                            else
                            {
                                MsgBoxEx.Shout("Cannot import database script information.", "Import Database Script");
                            }
                        }
                        else
                        {
                            MsgBoxEx.Shout("The specified file does not contain any relevant database script information.", "Import Database Script");
                        }
                    }
                    _table.Dispose(); _table = null;
                    Materia.RefreshAndManageCurrentProcess();
                }
                else
                {
                    MsgBoxEx.Alert("Failed to import the specified database script file.", "Import Database Script");
                }
            }

            EnableButtons(); DisplayInfo();
        }
Esempio n. 9
0
        private void btnSaveServers_Click(object sender, EventArgs e)
        {
            if (!btnSaveServers.Enabled)
            {
                return;
            }
            if (grdServers.DataSource == null)
            {
                return;
            }
            try { grdServers.Row = grdServers.Rows.Fixed - 1; }
            catch { }

            for (int i = grdServers.Rows.Fixed; i <= (grdServers.Rows.Count - 1); i++)
            {
                if (!Materia.IsNullOrNothing(grdServers.Rows[i]["Name"]))
                {
                    if (String.IsNullOrEmpty(grdServers.Rows[i]["Name"].ToString().RLTrim()))
                    {
                        MsgBoxEx.Shout("Please specify database server connection name at entry : " + i.ToString() + ".", "Required Field Notification");
                        grdServers.StartEditing(i, grdServers.Cols["Name"].Index); return;
                    }

                    if (String.IsNullOrEmpty(grdServers.Rows[i]["Server"].ToString().RLTrim()))
                    {
                        MsgBoxEx.Shout("Please specify database server IP address or hostname at entry : " + i.ToString() + ".", "Required Field Notification");
                        grdServers.StartEditing(i, grdServers.Cols["Server"].Index); return;
                    }

                    if (String.IsNullOrEmpty(grdServers.Rows[i]["Database"].ToString().RLTrim()))
                    {
                        MsgBoxEx.Shout("Please specify database catalog name at entry : " + i.ToString() + ".", "Required Field Notification");
                        grdServers.StartEditing(i, grdServers.Cols["Database"].Index); return;
                    }
                }
            }

            DataTable _datasource = (DataTable)grdServers.DataSource;

            if (_datasource.Rows.Count <= 0)
            {
                MsgBoxEx.Shout("Please specify at least a database connection to be registered.", "Save Database Server Connections"); return;
            }

            DataTable _changes = _datasource.GetChanges();

            if (_changes != null)
            {
                string    _path    = Application.StartupPath + "\\Xml\\databaseconnections.xml";
                DataTable _current = SCMS.XmlToTable(_path);

                if (_current != null)
                {
                    foreach (DataRow _row in _changes.Rows)
                    {
                        switch (_row.RowState)
                        {
                        case DataRowState.Added:
                            string[] _values = new string[_current.Columns.Count];
                            foreach (DataColumn _col in _current.Columns)
                            {
                                _values[_col.Ordinal] = _row[_col.ColumnName].ToString();
                            }
                            _current.Rows.Add(_values); break;

                        case DataRowState.Modified:
                            string _name = "";

                            try { _name = _row["Name", DataRowVersion.Original].ToString(); }
                            catch { _name = _row["Name"].ToString(); }

                            DataRow[] _existingrows = _current.Select("[Name] = '" + _name.ToSqlValidString(true) + "'");
                            if (_existingrows.Length > 0)
                            {
                                DataRow _currentrow = _existingrows[0];
                                foreach (DataColumn _col in _current.Columns)
                                {
                                    _currentrow[_col.ColumnName] = _row[_col.ColumnName];
                                }
                            }

                            break;

                        case DataRowState.Deleted:
                        case DataRowState.Detached:
                            string _deletedname = "";

                            try { _deletedname = _row["Name", DataRowVersion.Original].ToString(); }
                            catch { _deletedname = ""; }

                            DataRow[] _rows = _current.Select("[Name] = '" + _deletedname.ToSqlValidString(true) + "'");
                            if (_rows.Length > 0)
                            {
                                _rows[0].Delete();
                            }

                            break;

                        default: break;
                        }
                    }

                    try
                    {
                        _current.WriteXml(_path, XmlWriteMode.WriteSchema);
                        _datasource.AcceptChanges();
                    }
                    catch (Exception ex)
                    {
                        SCMS.LogError(this.Name, ex);
                        MsgBoxEx.Alert("Failed to save the changes made in the list. Please try again and / or report<br />this to your System Administrator.", "Save Database Server Connections");
                    }

                    try { _current.Dispose(); }
                    catch { }

                    _current = null; Materia.RefreshAndManageCurrentProcess();
                }
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!btnDelete.Enabled)
            {
                return;
            }
            if (!grdUsers.Redraw)
            {
                return;
            }
            if (grdUsers.DataSource == null)
            {
                return;
            }
            if (grdUsers.RowSel < grdUsers.Rows.Fixed)
            {
                return;
            }

            string _username      = grdUsers[grdUsers.RowSel, "Username"].ToString();
            string _accountholder = grdUsers[grdUsers.RowSel, "FullName"].ToString();

            if (_username == SCMS.CurrentSystemUser.Username)
            {
                MsgBoxEx.Shout("System does not allow to remove your own user account.", "Delete User Account"); return;
            }

            if (MsgBoxEx.Ask("Do you really want to remove <font color=\"blue\">" + _accountholder + " (" + _username + ")</font> from the user<br />account list?<br /><br /><b>Note :</b> If account has historical data along with it, user account will<br />not be removed permanently to retain historical logs of the account.", "Delete User Account") != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }

            string _query = "DELETE FROM `users` WHERE (`Username` LIKE '" + _username.ToSqlValidString() + "');";

            btnAdd.Enabled     = false; btnEdit.Enabled = false; btnDelete.Enabled = false;
            btnRefresh.Enabled = false; txtSearch.Enabled = false;

            Cursor = Cursors.WaitCursor;
            IAsyncResult _delresult = Que.BeginExecution(SCMS.Connection, _query);

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

            if (_cancelled)
            {
                if (!_delresult.IsCompleted)
                {
                    try { _delresult = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }

                return;
            }
            else
            {
                QueResult _result = Que.EndExecution(_delresult);
                if (string.IsNullOrEmpty(_result.Error.RLTrim()))
                {
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Removed " + _accountholder + " (" + _username + ") from the user accounts list.");
                    _logresult.WaitToFinish();

                    DataTable _datasource = null;

                    try { _datasource = (DataTable)grdUsers.DataSource; }
                    catch { }

                    if (_datasource != null)
                    {
                        DataRow[] _rows = _datasource.Select("[Username] LIKE '" + _username.ToSqlValidString(true) + "'");
                        if (_rows.Length > 0)
                        {
                            if (grdUsers.Redraw)
                            {
                                grdUsers.BeginUpdate();
                            }

                            _rows[0].Delete();
                            _datasource.AcceptChanges();
                            FormatGrid(); ResizeGrid();

                            DataTable _users = Cache.GetCachedTable("users");
                            if (_users != null)
                            {
                                DataRow[] _delusers = _users.Select("[Username] LIKE '" + _username.ToSqlValidString(true) + "'");
                                System.Collections.IEnumerator _delenums = _delusers.GetEnumerator();
                                while (_delenums.MoveNext())
                                {
                                    ((DataRow)_delenums.Current).Delete();
                                }
                                _users.AcceptChanges(); Cache.Save();
                            }

                            while (!grdUsers.Redraw)
                            {
                                grdUsers.EndUpdate();
                            }
                            DisplayInfo();
                        }
                    }
                }
                else
                {
                    _query = "UPDATE `users` SET\n" +
                             "`Voided` = 1, `DateVoided` = NOW()\n" +
                             "WHERE\n" +
                             "(`Username` LIKE '" + _username.ToSqlValidString(true) + "');";

                    Cursor     = Cursors.WaitCursor;
                    _delresult = null; Materia.RefreshAndManageCurrentProcess();
                    _delresult = Que.BeginExecution(SCMS.Connection, _query);
                    while (!_delresult.IsCompleted &&
                           !_cancelled)
                    {
                        Thread.Sleep(1); Application.DoEvents();
                    }

                    if (_cancelled)
                    {
                        if (!_delresult.IsCompleted)
                        {
                            try { _delresult = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }

                        return;
                    }
                    else
                    {
                        _result.Dispose(); Materia.RefreshAndManageCurrentProcess();
                        _result = Que.EndExecution(_delresult);
                        if (string.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Removed " + _accountholder + " (" + _username + ") from the user accounts list.");
                            _logresult.WaitToFinish();

                            DataTable _datasource = null;

                            try { _datasource = (DataTable)grdUsers.DataSource; }
                            catch { }

                            if (_datasource != null)
                            {
                                DataRow[] _rows = _datasource.Select("[Username] LIKE '" + _username.ToSqlValidString(true) + "'");
                                if (_rows.Length > 0)
                                {
                                    if (grdUsers.Redraw)
                                    {
                                        grdUsers.BeginUpdate();
                                    }

                                    _rows[0].Delete();
                                    _datasource.AcceptChanges();
                                    FormatGrid(); ResizeGrid();

                                    DataTable _users = Cache.GetCachedTable("users");
                                    if (_users != null)
                                    {
                                        DataRow[] _delusers = _users.Select("[Username] LIKE '" + _username.ToSqlValidString(true) + "'");
                                        System.Collections.IEnumerator _delenums = _delusers.GetEnumerator();
                                        while (_delenums.MoveNext())
                                        {
                                            ((DataRow)_delenums.Current).Delete();
                                        }
                                        _users.AcceptChanges(); Cache.Save();
                                    }

                                    while (!grdUsers.Redraw)
                                    {
                                        grdUsers.EndUpdate();
                                    }
                                    DisplayInfo();
                                }
                            }
                        }
                        else
                        {
                            SCMS.LogError(this.GetType().Name, new Exception(_result.Error));
                            MsgBoxEx.Alert("Failed to remove the specified user account from the list.", "Delete User Account");
                        }
                    }
                }

                _result.Dispose(); EnabledButtons();
            }

            Cursor = Cursors.Default;
        }
Esempio n. 11
0
        private void mnuExecuteScripts_Click(object sender, EventArgs e)
        {
            if (!mnuExecuteScripts.Enabled)
            {
                return;
            }

            OpenFileDialog _dialog = new OpenFileDialog();

            _dialog.CheckFileExists = true;
            _dialog.CheckPathExists = true;
            _dialog.DefaultExt      = SCMS.ScriptFileExtension;
            _dialog.Filter          = "SCMS Database Script Files (*." + SCMS.ScriptFileExtension + ")|*." + SCMS.ScriptFileExtension;
            _dialog.Title           = "Browse Database Script File";

            string _filename = "";

            if (_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _filename = (_dialog.FileName);
            }
            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();

            if (!string.IsNullOrEmpty(_filename.RLTrim()))
            {
                if (File.Exists(_filename))
                {
                    string _tempdir = Application.StartupPath + "\\Temp";

                    if (!Directory.Exists(_tempdir))
                    {
                        try { Directory.CreateDirectory(_tempdir); }
                        catch { }
                    }

                    if (Directory.Exists(_tempdir))
                    {
                        FileInfo _file      = new FileInfo(_filename);
                        string   _decrypted = _file.Decrypt(SCMS.EncryptionKey);
                        string   _tempfile  = _tempdir + "\\" + Path.GetFileNameWithoutExtension(_filename) + ".xml";

                        FileInfo _xmlfile = Materia.WriteToFile(_tempfile, _decrypted, false);
                        if (_xmlfile != null)
                        {
                            DataTable _table = SCMS.XmlToTable(_xmlfile.FullName);
                            if (_table != null)
                            {
                                if (_table.TableName == "scripts")
                                {
                                    if (_table.Rows.Count > 0)
                                    {
                                        DatabaseScriptInfo            _script = new DatabaseScriptInfo(_table);
                                        DatabaseScriptExecutionResult _result = _script.Execute();
                                    }
                                    else
                                    {
                                        MsgBoxEx.Shout("The specified file does not contain anyt releveant database script information.", "Execute Database Script");
                                    }
                                }
                                else
                                {
                                    MsgBoxEx.Shout("The specified file does not contain anyt releveant database script information.", "Execute Database Script");
                                }
                            }
                            else
                            {
                                MsgBoxEx.Alert("Failed to extract script information from the specified file.", "Execute Database Script");
                            }
                        }
                        else
                        {
                            MsgBoxEx.Alert("Failed to extract script information from the specified file.", "Execute Database Script");
                        }
                    }
                    else
                    {
                        MsgBoxEx.Alert("Failed to extract script information from the specified file.", "Execute Database Script");
                    }
                }
            }
        }
Esempio n. 12
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!btnDelete.Enabled)
            {
                return;
            }
            if (!grdStockAdjustments.Redraw)
            {
                return;
            }
            if (grdStockAdjustments.DataSource == null)
            {
                return;
            }
            if (grdStockAdjustments.RowSel < grdStockAdjustments.Rows.Fixed)
            {
                return;
            }
            if (Materia.IsNullOrNothing(grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"]))
            {
                return;
            }

            string    _referenceno      = grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"].ToString();
            DataTable _stockadjustments = Cache.GetCachedTable("stockadjustments");

            if (_stockadjustments != null)
            {
                DataRow[] _rows = _stockadjustments.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    DataRow _row = _rows[0];
                    if (VisualBasic.IsNumeric(_row["Closed"]))
                    {
                        if (VisualBasic.CBool(_row["Closed"]))
                        {
                            MsgBoxEx.Shout("Cannot delete stock adjustment : <font color=\"blue\">" + _referenceno + "</font> because it is already marked as final.", "Delete Stock Adjustment");
                            return;
                        }
                    }

                    if (MsgBoxEx.Ask("Delete stock adjustment <font color=\"blue\">" + _referenceno + "</font> permanently from the list?", "Delete Stock Adjustments") != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }

                    string       _query      = "DELETE FROM `stockadjustments` WHERE (`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString(true) + "')";
                    IAsyncResult _execresult = Que.BeginExecution(SCMS.Connection, _query);

                    btnNew.Enabled     = false; btnEdit.Enabled = false; btnDelete.Enabled = false;
                    btnRefresh.Enabled = false; txtSearch.Enabled = false;

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

                    if (_cancelled)
                    {
                        if (!_execresult.IsCompleted)
                        {
                            try { _execresult = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }

                        return;
                    }
                    else
                    {
                        QueResult _result = Que.EndExecution(_execresult);
                        if (string.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            _row.Delete(); _stockadjustments.AcceptChanges();

                            if (grdStockAdjustments.Redraw)
                            {
                                grdStockAdjustments.BeginUpdate();
                            }

                            DataTable _datasource = null;

                            try { _datasource = (DataTable)grdStockAdjustments.DataSource; }
                            catch { }

                            if (_datasource != null)
                            {
                                DataRow[] _currows = _datasource.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                                if (_currows.Length > 0)
                                {
                                    _currows[0].Delete();
                                }
                                _datasource.AcceptChanges();
                            }

                            FormatGrid(); ResizeGrid();

                            Cursor = Cursors.WaitCursor;
                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Deletes stock adjustment : " + _referenceno + ".", _referenceno);
                            _logresult.WaitToFinish(); Cursor = Cursors.Default;

                            while (!grdStockAdjustments.Redraw)
                            {
                                grdStockAdjustments.EndUpdate();
                            }
                        }
                        else
                        {
                            SCMS.LogError(this.GetType().Name, new Exception(_result.Error));
                            MsgBoxEx.Alert("Failed to delete the specified stock adjustment.", "Delete Stock Adjustment");
                        }

                        _result.Dispose(); EnableButtons(); DisplayInfo();
                    }
                }
            }
        }
Esempio n. 13
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();
                    }
                }
            }
        }
        /// <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);
        }