Example #1
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");
                }
            }
        }
        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();
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!btnDelete.Enabled)
            {
                return;
            }
            if (!grdScripts.Redraw)
            {
                return;
            }
            if (grdScripts.DataSource == null)
            {
                return;
            }
            if (grdScripts.RowSel < (grdScripts.Rows.Fixed))
            {
                return;
            }

            string _referenceno = grdScripts[grdScripts.RowSel, "ReferenceNo"].ToString();

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

            string _query = "DELETE FROM `scripts` WHERE (`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString() + "');";

            Cursor = Cursors.WaitCursor;

            IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

                return;
            }
            else
            {
                QueResult _queresult = Que.EndExecution(_result);
                if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                {
                    Cursor = Cursors.WaitCursor;
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Deleted script : " + _referenceno + " from the database script list.", _referenceno);
                    _logresult.WaitToFinish(); Cursor = Cursors.Default;

                    DataTable _datasource = null;

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

                    if (_datasource != null)
                    {
                        if (grdScripts.Redraw)
                        {
                            grdScripts.BeginUpdate();
                        }

                        DataRow[] _rows = _datasource.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                        if (_rows.Length > 0)
                        {
                            System.Collections.IEnumerator _enumerators = _rows.GetEnumerator();
                            while (_enumerators.MoveNext())
                            {
                                ((DataRow)_enumerators.Current).Delete();
                            }
                            _datasource.AcceptChanges();
                        }

                        DataTable _scripts = Cache.GetCachedTable("scripts");
                        if (_scripts != null)
                        {
                            DataRow[] _syncrows = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                            System.Collections.IEnumerator _enumerators = _syncrows.GetEnumerator();
                            while (_enumerators.MoveNext())
                            {
                                ((DataRow)_enumerators.Current).Delete();
                            }
                            Cache.Save();
                        }

                        FormatGrid(); ResizeGrid();

                        while (!grdScripts.Redraw)
                        {
                            grdScripts.EndUpdate();
                        }
                        EnableButtons(); DisplayInfo();
                    }
                }
                else
                {
                    SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                    MsgBoxEx.Alert("Failed to permanently delete the specified database script.", "Deletion Failed");
                }

                _queresult.Dispose(); Materia.RefreshAndManageCurrentProcess();
            }
        }
Example #4
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtAccountNo, !string.IsNullOrEmpty(txtAccountNo.Text.RLTrim()), "Please specify bank account number."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtAccountName, !string.IsNullOrEmpty(txtAccountName.Text.RLTrim()), "Please specify bank account name."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboBankingCompany, cboBankingCompany.SelectedIndex >= 0, "Please specify a valid banking company."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboCurrency, cboCurrency.SelectedIndex >= 0, "Please specify bank currency."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboAccountCode, cboAccountCode.SelectedIndex >= 0, "Please specify bank's associated G/L account."))
            {
                return;
            }

            DataTable _bankaccounts = Cache.GetCachedTable("bankaccounts");

            if (_bankaccounts != null)
            {
                DataRow[] _rows = _bankaccounts.Select("([AccountNo] LIKE '" + txtAccountNo.Text.ToSqlValidString(true) + "' AND\n" +
                                                       " [Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "') AND\n" +
                                                       "NOT ([BankAccountCode] LIKE '" + _bankaccountcode.ToSqlValidString(true) + "')");

                if (!Materia.Valid(_validator, txtAccountNo, _rows.Length <= 0, "Account already exists."))
                {
                    return;
                }

                string _query = ""; string _refno = ""; string _seriesno = "";
                DataColumnCollection _cols = _bankaccounts.Columns;

                if (_isnew)
                {
                    Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber);
                    IAsyncResult _result = _delegate.BeginInvoke("bankaccounts", 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;
                    }

                    _seriesno = _delegate.EndInvoke(_result);
                    _refno    = "BANK-" + SCMS.CurrentCompany.Company + "-" + _seriesno;

                    object[] _values = new object[_cols.Count];
                    _values[_cols["BankAccountCode"].Ordinal] = _refno;
                    _values[_cols["AccountNo"].Ordinal]       = txtAccountNo.Text;
                    _values[_cols["AccountName"].Ordinal]     = txtAccountName.Text;
                    _values[_cols["Currency"].Ordinal]        = cboCurrency.SelectedValue.ToString();
                    _values[_cols["AccountCode"].Ordinal]     = cboAccountCode.SelectedValue;
                    _values[_cols["Swift"].Ordinal]           = txtSwift.Text;
                    _values[_cols["IBAN"].Ordinal]            = txtIban.Text;
                    _values[_cols["Bank"].Ordinal]            = cboBankingCompany.SelectedValue;
                    _values[_cols["Branch"].Ordinal]          = txtBranch.Text;
                    _values[_cols["Notes"].Ordinal]           = txtNotes.Text;
                    _values[_cols["Company"].Ordinal]         = SCMS.CurrentCompany.Company;
                    _values[_cols["DateCreated"].Ordinal]     = DateTime.Now;
                    _values[_cols["LastModified"].Ordinal]    = DateTime.Now;
                    _bankaccounts.Rows.Add(_values);
                }
                else
                {
                    DataRow[] _existing = _bankaccounts.Select("[BankAccountCode] LIKE '" + _bankaccountcode.ToSqlValidString(true) + "'");
                    if (_existing.Length > 0)
                    {
                        _existing[0]["AccountNo"]   = txtAccountNo.Text;
                        _existing[0]["AccountName"] = txtAccountName.Text;
                        _existing[0]["Currency"]    = cboCurrency.SelectedValue;
                        _existing[0]["AccountCode"] = cboAccountCode.SelectedValue;
                        _existing[0]["Swift"]       = txtSwift.Text;
                        _existing[0]["IBAN"]        = txtIban.Text;
                        _existing[0]["Bank"]        = cboBankingCompany.SelectedValue;
                        _existing[0]["Branch"]      = txtBranch.Text;
                        _existing[0]["Notes"]       = txtNotes.Text;
                    }
                }

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

                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a new bank account : " + txtAccountNo.Text + " - " + txtAccountName.Text + ".";
                            if (!_isnew)
                            {
                                _log = "Updated bank account : " + txtAccountNo.Text + " - " + txtAccountName.Text + ".";
                            }

                            _bankaccounts.AcceptChanges();
                            if (_isnew)
                            {
                                _bankaccountcode = _refno;
                            }
                            if (_isnew)
                            {
                                _isnew = false;
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            if (!txtSearch.AutoCompleteCustomSource.Contains(txtAccountNo.Text))
                            {
                                txtSearch.AutoCompleteCustomSource.Add(txtAccountNo.Text);
                            }
                            if (!txtSearch.AutoCompleteCustomSource.Contains(txtAccountName.Text))
                            {
                                txtSearch.AutoCompleteCustomSource.Add(txtAccountName.Text);
                            }
                            if (!txtSearch.AutoCompleteCustomSource.Contains(cboBankingCompany.SelectedValue.ToString()))
                            {
                                txtSearch.AutoCompleteCustomSource.Add(cboBankingCompany.SelectedValue.ToString());
                            }
                            if (!txtSearch.AutoCompleteCustomSource.Contains(cboAccountCode.SelectedValue.ToString()))
                            {
                                txtSearch.AutoCompleteCustomSource.Add(cboAccountCode.SelectedValue.ToString());
                            }

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                            else
                            {
                                if (!tbOutstanding.Visible)
                                {
                                    tbOutstanding.Visible = true;
                                }
                                if (!tbBankLedger.Visible)
                                {
                                    tbBankLedger.Visible = true;
                                }
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                btnSave_Click(sender, new EventArgs());
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current bank account.", "Save Bank Account");
                            }

                            _bankaccounts.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            if (!btnTestConnection.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtUserId, !String.IsNullOrEmpty(txtUserId.Text.RLTrim()), "Please specify database server's log on account id."))
            {
                return;
            }

            if (!Materia.Valid(_validator, txtPassword1, !String.IsNullOrEmpty(txtPassword1.Text.RLTrim()), "Please specify database server's log on account password."))
            {
                return;
            }

            if (!Materia.Valid(_validator, txtPassword2, string.Compare(txtPassword1.Text, txtPassword2.Text) == 0 &&
                               txtPassword1.Text == txtPassword2.Text, "Passwords doesn't match each other."))
            {
                return;
            }

            btnTestConnection.Enabled = false; btnOk.Enabled = false;
            txtUserId.ReadOnly        = true; txtPassword1.ReadOnly = true; txtPassword2.ReadOnly = true;

            string        _connectionstring = "SERVER=" + txtServer.Text + ";DATABASE=" + txtDatabase.Text + ";UID=" + txtUserId.Text + ";PWD=" + txtPassword1.Text + ";";
            IDbConnection _connection       = Development.Materia.Database.Database.CreateConnection(_connectionstring);

            Func <IDbConnection, bool> _delegate = new Func <IDbConnection, bool>(Materia.CanConnect);
            IAsyncResult _result = _delegate.BeginInvoke(_connection, null, _delegate);

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

            Materia.RefreshAndManageCurrentProcess();

            if (_cancelled)
            {
                if (!_result.IsCompleted)
                {
                    try { _result = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }
            }
            else
            {
                bool _connected = _delegate.EndInvoke(_result);

                if (_connected)
                {
                    MsgBoxEx.Inform("Connection has been successfully established.", "Test Database Connection");
                }
                else
                {
                    MsgBoxEx.Alert("Failed to establish a connection using the specified configurations.", "Connection Failed");
                }
            }

            if (_connection != null)
            {
                if (_connection.State == ConnectionState.Open)
                {
                    try { _connection.Close(); }
                    catch { }
                }

                try { _connection.Dispose(); }
                catch { }
                finally
                { _connection = null; Materia.RefreshAndManageCurrentProcess(); }
            }

            btnTestConnection.Enabled = true; btnOk.Enabled = true;
            txtUserId.ReadOnly        = false; txtPassword1.ReadOnly = false; txtPassword2.ReadOnly = false;
        }
Example #6
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtBrand, !string.IsNullOrEmpty(txtBrand.Text.RLTrim()), "Please specify vehicle make name."))
            {
                return;
            }
            DataTable _brands = Cache.GetCachedTable("brands");

            if (_brands != null)
            {
                DataRow[] _rows = _brands.Select("([Brand] LIKE '" + txtBrand.Text.ToSqlValidString(true) + "') AND\n" +
                                                 "NOT ([Brand] LIKE '" + _brand.ToSqlValidString(true) + "')");

                if (!Materia.Valid(_validator, txtBrand, _rows.Length <= 0, "Brand already exists."))
                {
                    return;
                }

                string _query = "";
                DataColumnCollection _cols = _brands.Columns;

                if (_isnew)
                {
                    _query = "INSERT INTO `brands`\n" +
                             "(`Brand`, `DateCreated`)\n" +
                             "VALUES\n" +
                             "('" + txtBrand.Text.ToSqlValidString() + "', NOW());";

                    object[] _values = new object[_cols.Count];
                    _values[_cols["Brand"].Ordinal]        = txtBrand.Text;
                    _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                    _values[_cols["LastModified"].Ordinal] = DateTime.Now;
                    _brands.Rows.Add(_values);
                }
                else
                {
                    _query = "UPDATE `brands` SET\n" +
                             "`Brand` = '" + txtBrand.Text.ToSqlValidString() + "'\n" +
                             "WHERE\n" +
                             "(`Brand` LIKE '" + _brand.ToSqlValidString() + "');";
                    DataRow[] _existing = _brands.Select("[Brand] LIKE '" + _brand.ToSqlValidString(true) + "'");
                    if (_existing.Length > 0)
                    {
                        _existing[0]["Brand"] = txtBrand.Text;
                    }
                }

                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    if (txtBrand.Text == _brand)
                    {
                        if (_isnew)
                        {
                            _isnew = false;
                        }
                        if (_updated)
                        {
                            _updated = false;
                        }
                        if (_withupdates)
                        {
                            _withupdates = false;
                        }

                        Text = Text.Replace(" *", "").Replace("*", "");

                        if (sender == btnSaveAndClose)
                        {
                            DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                        }

                        return;
                    }

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a new brand : " + txtBrand.Text + ".";
                            if (!_isnew)
                            {
                                _log = "Updated brand : " + _brand + (_brand != txtBrand.Text ? " to " + txtBrand.Text : "").ToString() + ".";
                            }

                            _brands.AcceptChanges(); _brand = txtBrand.Text;
                            if (_isnew)
                            {
                                _isnew = false;
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                bool _invalid = Materia.Valid(_validator, txtBrand, false, "Brand already exists.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current brand.", "Save Brand");
                            }

                            _brands.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        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 btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, cboUsername, cboUsername.SelectedIndex >= 0, "Please specify signatory from the existing accounts."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboRole, cboRole.SelectedIndex >= 0, "Please specify signatory role."))
            {
                return;
            }

            DataTable _signatories = Cache.GetCachedTable("signatories");

            if (_signatories != null)
            {
                DataRow[] _rows = _signatories.Select("([Username] LIKE '" + cboUsername.SelectedValue.ToString().ToSqlValidString(true) + "' AND\n" +
                                                      " [RoleId] = " + cboRole.SelectedValue.ToString() + " AND\n" +
                                                      " [Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "') AND\n" +
                                                      "([DetailId] <> " + _id.ToString() + ")");

                if (!Materia.Valid(_validator, cboUsername, _rows.Length <= 0, "Signatory under the specified role already exists."))
                {
                    return;
                }

                string _query = "";
                DataColumnCollection _cols = _signatories.Columns;
                DataRow _newrow            = null;

                if (_isnew)
                {
                    _query = "INSERT INTO `signatories`\n" +
                             "(`Username`, `RoleId`, `CashLimit`, `BankLimit`, `Company`)\n" +
                             "VALUES\n" +
                             "('" + cboUsername.SelectedValue.ToString().ToSqlValidString() + "', " + cboRole.SelectedValue.ToString() + ", " + (txtCashLimit.LockUpdateChecked? txtCashLimit.Value.ToSqlValidString() : "0") + ", " + (txtBankLimit.LockUpdateChecked? txtBankLimit.Value.ToSqlValidString() : "0") + ", '" + SCMS.CurrentCompany.Company.ToSqlValidString() + "');\n" +
                             "SELECT LAST_INSERT_ID() AS `Id`;";

                    object[] _values = new object[_cols.Count];
                    _values[_cols["Username"].Ordinal]     = cboUsername.SelectedValue;
                    _values[_cols["RoleId"].Ordinal]       = cboRole.SelectedValue;
                    _values[_cols["CashLimit"].Ordinal]    = (txtCashLimit.LockUpdateChecked ? txtCashLimit.Value : 0);
                    _values[_cols["BankLimit"].Ordinal]    = (txtCashLimit.LockUpdateChecked ? txtCashLimit.Value : 0);
                    _values[_cols["LastModified"].Ordinal] = DateTime.Now;
                    _newrow = _signatories.Rows.Add(_values);
                }
                else
                {
                    _query = "UPDATE `signatories` SET\n" +
                             "`Username` = '" + cboUsername.SelectedValue.ToString() + "', `RoleId` = " + cboRole.SelectedValue.ToString() + ", `CashLimit` = " + (txtCashLimit.LockUpdateChecked? txtCashLimit.Value.ToSqlValidString() : "0") + ", `BankLimit` = " + (txtBankLimit.LockUpdateChecked ? txtBankLimit.Value.ToSqlValidString() : "0") + "\n" +
                             "WHERE\n" +
                             "(`DetailId` = " + _id.ToString() + ");";

                    DataRow[] _existing = _signatories.Select("[DetailId] = " + _id.ToString());
                    if (_existing.Length > 0)
                    {
                        _existing[0]["Username"]  = cboUsername.SelectedValue;
                        _existing[0]["RoleId"]    = cboRole.SelectedValue;
                        _existing[0]["CashLimit"] = (txtCashLimit.LockUpdateChecked ? txtCashLimit.Value : 0);
                        _existing[0]["BankLimit"] = (txtBankLimit.LockUpdateChecked ? txtBankLimit.Value : 0);
                    }
                }

                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a new signatory : " + txtFullName.Text + " as " + cboRole.Text.ToLower() + ".";
                            if (!_isnew)
                            {
                                _log = "Updated signatory : " + txtFullName.Text + " as " + cboRole.Text.ToLower() + ".";
                            }

                            if (_queresult.ResultSet != null)
                            {
                                if (_queresult.ResultSet.Tables.Count > 0)
                                {
                                    DataTable _table = _queresult.ResultSet.Tables[0];
                                    if (_table.Rows.Count > 0)
                                    {
                                        DataRow _row = _table.Rows[0];
                                        if (VisualBasic.IsNumeric(_row["Id"]))
                                        {
                                            if (_newrow != null)
                                            {
                                                _id = VisualBasic.CLng(_row["Id"]);
                                                _newrow["DetailId"] = _row["Id"];
                                            }
                                        }
                                    }
                                }
                            }

                            _signatories.AcceptChanges();
                            if (_isnew)
                            {
                                _isnew = false;
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                bool _invalid = Materia.Valid(_validator, cboUsername, false, "Signatory with the specified role already exists.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current signatory.", "Save Signatory");
                            }

                            _signatories.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        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;
        }
Example #10
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");
                    }
                }
            }
        }
Example #11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtUsername, !String.IsNullOrEmpty(txtUsername.Text.RLTrim()), "Please specify the user account's logon name."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtPassword, !String.IsNullOrEmpty(txtPassword.Text.RLTrim()), "Please specify the user account's password."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtFirstName, !String.IsNullOrEmpty(txtFirstName.Text.RLTrim()), "Please specify the account holder's given name."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtLastName, !String.IsNullOrEmpty(txtLastName.Text.RLTrim()), "Please specify the account holder's surname."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboDepartment, cboDepartment.SelectedIndex >= 0, "Please specify a valid department."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboPosition, cboPosition.SelectedIndex >= 0, "Please specify a valid position."))
            {
                return;
            }

            DataTable _users = Cache.GetCachedTable("users");

            if (_users != null)
            {
                DataRow[] _exists = _users.Select("([Username] LIKE '" + txtUsername.Text.ToSqlValidString(true) + "') AND\n" +
                                                  "NOT ([Username] LIKE '" + _username.ToSqlValidString(true) + "')");

                if (!Materia.Valid(_validator, txtUsername, _exists.Length <= 0, "Username already exists."))
                {
                    return;
                }
                string _role       = (chkSuperUser.Checked ? SystemUserInfo.SuperUserRole : SystemUserInfo.RegularUserRole).ToString();
                string _privileges = "";

                if (chkSuperUser.Checked)
                {
                    for (int i = 0; i <= 800; i++)
                    {
                        _privileges += "1";
                    }
                }

                if (_isnew)
                {
                    _users.Rows.Add(new object[] {
                        txtUsername.Text, txtPassword.Text.Encrypt(SCMS.EncryptionKey),
                        txtFirstName.Text, txtMiddleName.Text, txtLastName.Text,
                        cboPosition.SelectedValue.ToString(), cboDepartment.SelectedValue.ToString(),
                        (chkActive.Checked? 1 : 0), _role, _privileges,
                        (chkAllowAllCustomers.Checked? 1 : 0), (chkAllowAllCompanies.Checked? 1:0),
                        DateTime.Now, DateTime.Now, 0, DBNull.Value
                    });
                }
                else
                {
                    DataRow[] _rows = _users.Select("[Username] LIKE '" + _username.ToSqlValidString(true) + "'");
                    if (_rows.Length > 0)
                    {
                        DataRow _row = _rows[0];
                        _row["Username"]     = txtUsername.Text;
                        _row["Password"]     = txtPassword.Text.Encrypt(SCMS.EncryptionKey);
                        _row["FirstName"]    = txtFirstName.Text;
                        _row["MiddleName"]   = txtMiddleName.Text;
                        _row["LastName"]     = txtLastName.Text;
                        _row["Position"]     = cboPosition.SelectedValue.ToString();
                        _row["Department"]   = cboDepartment.SelectedValue.ToString();
                        _row["Active"]       = (chkActive.Checked ? 1 : 0);
                        _row["Role"]         = _role; _row["Privileges"] = _privileges;
                        _row["AllCustomers"] = (chkAllowAllCustomers.Checked ? 1 : 0);
                        _row["AllCompanies"] = (chkAllowAllCompanies.Checked ? 1 : 0);
                    }
                }

                QueryGenerator _generator = new QueryGenerator(_users);
                _generator.ExcludedFields.Add("LastModified");
                string _query = _generator.ToString(); _generator = null;
                Materia.RefreshAndManageCurrentProcess();

                if (!String.IsNullOrEmpty(_query.RLTrim()))
                {
                    if (Regex.IsMatch(_query, "WHERE[A-Za-z0-9\\s\\n\\r\\t\\W]+"))
                    {
                        string _tempquery = _query;
                        _query = Regex.Replace(_tempquery, "WHERE[A-Za-z0-9\\s\\n\\r\\t\\W]+", "WHERE (`Username` LIKE '" + _username.ToSqlValidString() + "')");
                    }

                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;
                    IAsyncResult _queresult = Que.BeginExecution(SCMS.Connection, _query);
                    while (!_queresult.IsCompleted &&
                           !_cancelled)
                    {
                        Thread.Sleep(1); Application.DoEvents();
                    }

                    if (_cancelled)
                    {
                        if (!_queresult.IsCompleted)
                        {
                            try { _queresult = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }
                    }
                    else
                    {
                        QueResult _result = Que.EndExecution(_queresult);

                        if (string.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            _users.AcceptChanges(); Cache.Save();
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }

                            Cursor = Cursors.WaitCursor;

                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _logdescription = "Added a new system user account : " + txtUsername.Text + ".";
                            if (!_isnew)
                            {
                                _logdescription = "Updated user account : " + _username + ".";
                            }

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _logdescription);
                            _logresult.WaitToFinish(); Cursor = Cursors.Default;

                            _isnew = false; _username = txtUsername.Text;
                            if (_updated)
                            {
                                _updated = false;
                            }
                            Text = Text.Replace(" *", "").Replace("*", "");

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_result.Error.ToLower().Contains("duplicate"))
                            {
                                Materia.Valid(_validator, txtUsername, false, "Username already exists.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_result.Error));
                                MsgBoxEx.Alert("Failed to save the user account.", "Save User Account");
                            }
                        }

                        _result.Dispose(); _result = null; Materia.RefreshAndManageCurrentProcess();
                        btnSave.Enabled            = true; btnSaveAndClose.Enabled = true;
                    }
                }
                else
                {
                    if (_updated)
                    {
                        _updated = false;
                    }
                    Text = Text.Replace(" *", "").Replace("*", "");
                    if (sender == btnSaveAndClose)
                    {
                        DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                    }
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
Example #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();
                    }
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtAddress, !string.IsNullOrEmpty(txtAddress.Text.RLTrim()), "Please specify company address."))
            {
                tbctrl.SelectedTab = tbCompany; return;
            }

            if (!Materia.Valid(_validator, cboCountry, cboCountry.SelectedIndex >= 0, "Please specify a valid country."))
            {
                tbctrl.SelectedTab = tbCompany; return;
            }

            if (!Materia.Valid(_validator, cboCashAdvance, cboCashAdvance.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (!Materia.Valid(_validator, cboUnallocatedPayments, cboUnallocatedPayments.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (!Materia.Valid(_validator, cboRawMaterials, cboRawMaterials.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (!Materia.Valid(_validator, cboStockConsumption, cboStockConsumption.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (!Materia.Valid(_validator, cboStockAdjustment, cboStockAdjustment.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (!Materia.Valid(_validator, cboRollForward, cboRollForward.SelectedIndex >= 0, "Please specify a valid account."))
            {
                tbctrl.SelectedTab = tbAccounts; return;
            }

            if (chkAutoBackup.Checked)
            {
                if (!Materia.Valid(_validator, lblPath, !string.IsNullOrEmpty(lblPath.Text.RLTrim()), "Please specify backup output destination."))
                {
                    tbctrl.SelectedTab = tbWorkstation; return;
                }

                if (!Materia.Valid(_validator, lblPath, Directory.Exists(lblPath.Text), "Please specify backup output destination."))
                {
                    tbctrl.SelectedTab = tbWorkstation; return;
                }

                if (dtpBackUpTime2.LockUpdateChecked)
                {
                    DateTime _date1 = VisualBasic.CDate(DateTime.Now.ToShortDateString() + " " + VisualBasic.Format(dtpBackUpTime1.Value, "hh:mm tt"));
                    DateTime _date2 = VisualBasic.CDate(DateTime.Now.ToShortDateString() + " " + VisualBasic.Format(dtpBackUpTime2.Value, "hh:mm tt"));

                    if (!Materia.Valid(_validator, dtpBackUpTime2, _date2 >= _date1, "Please specify a time equal or higher than the first instance."))
                    {
                        tbctrl.SelectedTab = tbWorkstation; return;
                    }
                }
            }

            DataTable _settings = Cache.GetCachedTable("settings");

            if (_settings != null)
            {
                DataRow[] _rows = _settings.Select("[Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    DataRow _row = _rows[0];
                    _row["Address"] = txtAddress.Text; _row["Country"] = cboCountry.SelectedValue.ToString();
                    _row["Phone"]   = txtPhone.Text; _row["Mobile"] = txtMobile.Text;
                    _row["Fax"]     = txtFax.Text; _row["Email"] = txtEmail.Text;

                    try { _row["CompanyLogo"] = pctCompanyLogo.Image.ToByteArray(); }
                    catch { }

                    try { _row["ReportLogo"] = pctReportLogo.Image.ToByteArray(); }
                    catch { }

                    _row["CashAdvanceAccountCode"]        = cboCashAdvance.SelectedValue;
                    _row["RawMaterialAccountCode"]        = cboRawMaterials.SelectedValue;
                    _row["StockConsumptionAccountCode"]   = cboStockConsumption.SelectedValue;
                    _row["StockAdjustmentAccountCode"]    = cboStockAdjustment.SelectedValue;
                    _row["UnallocatedPaymentAccountCode"] = cboUnallocatedPayments.SelectedValue;
                    _row["RollForwardAccountCode"]        = cboRollForward.SelectedValue;

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

                    if (string.IsNullOrEmpty(_query.RLTrim()))
                    {
                        GlobalSettings.AutomaticBackupEnabled = chkAutoBackup.Checked;

                        if (chkAutoBackup.Checked)
                        {
                            GlobalSettings.AutomaticBackupEnabled2 = dtpBackUpTime2.LockUpdateChecked;
                        }
                        else
                        {
                            GlobalSettings.AutomaticBackupEnabled2 = false;
                        }

                        GlobalSettings.AutomaticBackupPath  = lblPath.Text;
                        GlobalSettings.AutomaticBackupTime1 = dtpBackUpTime1.Value;
                        if (chkAutoBackup.Checked &&
                            dtpBackUpTime2.LockUpdateChecked)
                        {
                            GlobalSettings.AutomaticBackupTime2 = dtpBackUpTime2.Value;
                        }

                        if (txtIdleTime.LockUpdateChecked)
                        {
                            GlobalSettings.AutomaticLockTime = txtIdleTime.Value;
                        }
                        else
                        {
                            GlobalSettings.AutomaticLockTime = 0;
                        }

                        IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Edit, "Updated the application settings.");

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

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

                        DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                        return;
                    }

                    btnSave.Enabled = false;
                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

                    if (_cancelled)
                    {
                        _settings.RejectChanges();
                        if (!_result.IsCompleted)
                        {
                            try { _result = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }
                    }
                    else
                    {
                        QueResult _queresult = Que.EndExecution(_result);
                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            _settings.AcceptChanges(); Cache.Save(); _updated = false;
                            GlobalSettings.AutomaticBackupEnabled             = chkAutoBackup.Checked;

                            if (chkAutoBackup.Checked)
                            {
                                GlobalSettings.AutomaticBackupEnabled2 = dtpBackUpTime2.LockUpdateChecked;
                            }
                            else
                            {
                                GlobalSettings.AutomaticBackupEnabled2 = false;
                            }

                            GlobalSettings.AutomaticBackupPath  = lblPath.Text;
                            GlobalSettings.AutomaticBackupTime1 = dtpBackUpTime1.Value;
                            if (chkAutoBackup.Checked &&
                                dtpBackUpTime2.LockUpdateChecked)
                            {
                                GlobalSettings.AutomaticBackupTime2 = dtpBackUpTime2.Value;
                            }

                            if (txtIdleTime.LockUpdateChecked)
                            {
                                GlobalSettings.AutomaticLockTime = txtIdleTime.Value;
                            }
                            else
                            {
                                GlobalSettings.AutomaticLockTime = 0;
                            }

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Edit, "Updated the application settings.");

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

                            if (_cancelled)
                            {
                                if (!_logresult.IsCompleted)
                                {
                                    try { _logresult = null; }
                                    catch { }
                                    finally { Materia.RefreshAndManageCurrentProcess(); }
                                }
                            }
                            else
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            _settings.RejectChanges(); SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                            MsgBoxEx.Alert("Failed to save application settings.", "Save Settings"); btnSave.Enabled = true;
                        }
                    }
                }
            }
        }
Example #14
0
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if (!btnSignIn.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this]; pnlNotification.Hide();

            if (!Materia.Valid(_validator, cboServers, cboServers.SelectedIndex >= 0, "Select a database server."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboCompanies, cboCompanies.SelectedIndex >= 0, "Select access company."))
            {
                return;
            }

            SCMS.ServerConnection = null; SCMS.Connection = null;
            Materia.RefreshAndManageCurrentProcess();

            if (String.IsNullOrEmpty(txtUsername.Text.RLTrim()) ||
                String.IsNullOrEmpty(txtPassword.Text.RLTrim()))
            {
                pnlNotification.Text = "Invalid account credentials.";
                pnlNotification.Show(); pnlNotification.BringToFront();
                return;
            }

            ServerConnectionInfo _info = new ServerConnectionInfo(cboServers.SelectedValue.ToString());

            pctLoad.Show(); pctLoad.BringToFront();
            btnSignIn.Enabled = false; cboServers.Enabled = false; cboCompanies.Enabled = false;

            IDbConnection _connection = Database.CreateConnection(_info.ToString());

            Func <IDbConnection, bool> _connectdelegate = new Func <IDbConnection, bool>(Materia.CanConnect);
            IAsyncResult _connectresult = _connectdelegate.BeginInvoke(_connection, null, _connectdelegate);

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

            bool _connected = false;

            if (_cancelled)
            {
                if (!_connectresult.IsCompleted)
                {
                    try { _connectresult = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }
            }
            else
            {
                _connected = _connectdelegate.EndInvoke(_connectresult);
                if (!_connected)
                {
                    MsgBoxEx.Alert("Failed to connect to the specified database server.", "Database Connection");
                }
            }

            if (!_connected)
            {
                if (_connection != null)
                {
                    if (_connection.State == ConnectionState.Open)
                    {
                        try { _connection.Close(); }
                        catch { }
                    }

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

                    _connection = null; Materia.RefreshAndManageCurrentProcess();
                }

                cboServers.Enabled = true; cboCompanies.Enabled = true;
                btnSignIn.Enabled  = true; pctLoad.Hide(); return;
            }

            SCMS.Connection     = _connection; SCMS.ServerConnection = new ServerConnectionInfo(cboServers.SelectedValue.ToString());
            SCMS.CurrentCompany = new CompanyInfo(cboCompanies.SelectedValue.ToString());

            Func <IDbConnection, string, DateTime> _getvaluedelegate = new Func <IDbConnection, string, DateTime>(Que.GetValue <DateTime>);
            IAsyncResult _getvalueresult = _getvaluedelegate.BeginInvoke(_connection, "SELECT MAX(`LastRestored`) AS `Date` FROM `settings`", null, _getvaluedelegate);

            _getvalueresult.WaitToFinish();
            DateTime _dbtimestamp = _getvaluedelegate.EndInvoke(_getvalueresult);
            DateTime _timestamp   = Cache.LastRestoration;

            if (_dbtimestamp > _timestamp)
            {
                Cache.Clear(); Cache.UpdateCacheTimeStamp(_dbtimestamp);
            }

            Action <IDbConnection> _inituserdelegate = new Action <IDbConnection>(CreateInitialUser);
            IAsyncResult           _inituserresult   = _inituserdelegate.BeginInvoke(SCMS.Connection, null, _inituserdelegate);

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

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

                return;
            }
            else
            {
                Action <IDbConnection> _initcompaniesdelegate = new Action <IDbConnection>(CreateInitialCompanies);
                IAsyncResult           _initcompaniesresult   = _initcompaniesdelegate.BeginInvoke(SCMS.Connection, null, _initcompaniesdelegate);

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

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

                    return;
                }
                else
                {
                    SCMS.CurrentSystemUser = null; Materia.RefreshAndManageCurrentProcess();
                    SystemUserInfo _userinfo = new SystemUserInfo(txtUsername.Text, txtPassword.Text);

                    IAsyncResult _loginasync = _userinfo.LogInAsync();

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

                    if (_cancelled)
                    {
                        if (!_loginasync.IsCompleted)
                        {
                            try { _loginasync = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }
                    }
                    else
                    {
                        if (_userinfo.IsSignedIn)
                        {
                            SCMS.CurrentSystemUser = _userinfo;
                            InitializerDialog _loader = new InitializerDialog();
                            _loader.Message  = "Gathering application settings for " + SCMS.CurrentCompany.Company + ".";
                            txtPassword.Text = ""; Hide(); _loader.Show();

                            IAsyncResult _gsresult = GlobalSettings.RefreshAsync(SCMS.CurrentCompany.Company);
                            _gsresult.WaitToFinish(); SCMS.CleanUp();

                            _loader.Close(); _loader.Dispose(); _loader = null;
                            Materia.RefreshAndManageCurrentProcess();
                            MainWindow _main = new MainWindow(); _main.Show();
                        }
                        else
                        {
                            if (_userinfo.IsValidUser &&
                                !_userinfo.IsActive)
                            {
                                pnlNotification.Text = "Account needs activation.";
                                pnlNotification.Show(); pnlNotification.BringToFront();
                            }
                            else
                            {
                                if (_userinfo.IsValidUser &&
                                    !_userinfo.AccessibleCompanies.Contains(SCMS.CurrentCompany.Company))
                                {
                                    pnlNotification.Text = "Account not allowed in selected company.";
                                    pnlNotification.Show(); pnlNotification.BringToFront();
                                }
                                else
                                {
                                    pnlNotification.Text = "Invalid account credentials.";
                                    pnlNotification.Show(); pnlNotification.BringToFront();
                                }
                            }

                            _userinfo = null; Materia.RefreshAndManageCurrentProcess();
                        }

                        cboCompanies.Enabled = true; cboServers.Enabled = true;
                        btnSignIn.Enabled    = true; pctLoad.Hide();
                    }
                }
            }
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (!btnExport.Enabled)
            {
                return;
            }
            if (!grdScripts.Redraw)
            {
                return;
            }
            if (grdScripts.DataSource == null)
            {
                return;
            }
            if (grdScripts.RowSel < (grdScripts.Rows.Fixed))
            {
                return;
            }

            string _referenceno = grdScripts[grdScripts.RowSel, "ReferenceNo"].ToString();

            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 btnExportExcel_Click(object sender, EventArgs e)
        {
            if (!_shown)
            {
                return;
            }
            if (!btnExportExcel.Enabled)
            {
                return;
            }
            if (!grdLogs.Redraw)
            {
                return;
            }
            if (grdLogs.DataSource == null)
            {
                return;
            }

            DataTable _datasource = null;

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

            if (_datasource != null)
            {
                SaveFileDialog _dialog = new SaveFileDialog();
                _dialog.DefaultExt = "xls";
                _dialog.FileName   = "userlogs.xls";
                _dialog.Filter     = "Micrososft Excel Worksheet (*.xls)|*.xls";
                _dialog.Title      = "Export User Logs";
                if (_dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    _dialog.Dispose(); _dialog = null;
                    Materia.RefreshAndManageCurrentProcess(); return;
                }

                DataTable _viewtable = _datasource.DefaultView.ToTable();
                Cursor = Cursors.WaitCursor;

                try
                {
                    _viewtable.SaveExcel(_dialog.FileName);
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ExportExcel, "Exported user logs into : " + _dialog.FileName + ".");
                    _logresult.WaitToFinish(); Cursor = Cursors.Default;

                    if (File.Exists(_dialog.FileName))
                    {
                        Process.Start(_dialog.FileName);
                    }
                }
                catch (Exception ex)
                {
                    SCMS.LogError(this.GetType().Name, ex);
                    MsgBoxEx.Alert("Failed to export the current list into the output file.", "Export User Logs");
                }

                Cursor = Cursors.Default;
                _dialog.Dispose(); _dialog       = null;
                _viewtable.Dispose(); _viewtable = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
Example #17
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtLocation, !string.IsNullOrEmpty(txtLocation.Text.RLTrim()), "Please specify location name."))
            {
                return;
            }
            DataTable _locations = Cache.GetCachedTable("locations");

            if (_locations != null)
            {
                DataRow[] _rows = _locations.Select("([Location] LIKE '" + txtLocation.Text.ToSqlValidString(true) + "' AND\n" +
                                                    " [Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "') AND\n" +
                                                    "NOT ([LocationCode] LIKE '" + _locationcode.ToSqlValidString(true) + "')");

                if (!Materia.Valid(_validator, txtLocation, _rows.Length <= 0, "Location already exists."))
                {
                    return;
                }

                string _query = ""; string _refno = _locationcode;
                DataColumnCollection _cols = _locations.Columns;

                if (_isnew)
                {
                    Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber);
                    IAsyncResult _result = _delegate.BeginInvoke("locations", 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;
                    }

                    string _seriesnumber = _delegate.EndInvoke(_result);
                    _refno = SCMS.CurrentCompany.Company + "-" + _seriesnumber;

                    _query = "INSERT INTO `locations`\n" +
                             "(`LocationCode`, `Location`, `Company`, `DateCreated`)\n" +
                             "VALUES\n" +
                             "('" + _refno.ToSqlValidString() + "', '" + txtLocation.Text.ToSqlValidString() + "', '" + SCMS.CurrentCompany.Company.ToSqlValidString() + "', NOW());";

                    object[] _values = new object[_cols.Count];
                    _values[_cols["LocationCode"].Ordinal] = _refno;
                    _values[_cols["Location"].Ordinal]     = txtLocation.Text;
                    _values[_cols["Company"].Ordinal]      = SCMS.CurrentCompany.Company;
                    _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                    _values[_cols["LastModified"].Ordinal] = DateTime.Now;
                    _locations.Rows.Add(_values);
                }
                else
                {
                    _query = "UPDATE `locations` SET\n" +
                             "`Location` = '" + txtLocation.Text.ToSqlValidString() + "'\n" +
                             "WHERE\n" +
                             "(`LocationCode` LIKE '" + _locationcode.ToSqlValidString() + "');";

                    DataRow[] _existing = _locations.Select("[LocationCode] LIKE '" + _locationcode.ToSqlValidString(true) + "'");
                    if (_existing.Length > 0)
                    {
                        _existing[0]["Location"] = txtLocation.Text;
                    }
                }

                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    if (txtLocation.Text == _location)
                    {
                        if (_isnew)
                        {
                            _isnew = false;
                        }
                        if (_updated)
                        {
                            _updated = false;
                        }
                        if (_withupdates)
                        {
                            _withupdates = false;
                        }

                        Text = Text.Replace(" *", "").Replace("*", "");

                        if (sender == btnSaveAndClose)
                        {
                            DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                        }

                        return;
                    }

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a new location : " + txtLocation.Text + ".";
                            if (!_isnew)
                            {
                                _log = "Updated location : " + _location + (_location != txtLocation.Text ? " to " + txtLocation.Text : "").ToString() + ".";
                            }

                            _locations.AcceptChanges(); _locationcode = _refno;
                            _location = txtLocation.Text;
                            if (_isnew)
                            {
                                _isnew = false;
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                bool _invalid = Materia.Valid(_validator, txtLocation, false, "Location already exists.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current location.", "Save Location");
                            }

                            _locations.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        private void btnExportXml_Click(object sender, EventArgs e)
        {
            if (!_shown)
            {
                return;
            }
            if (!btnExportXml.Enabled)
            {
                return;
            }
            if (!grdLogs.Redraw)
            {
                return;
            }
            if (grdLogs.DataSource == null)
            {
                return;
            }

            DataTable _datasource = null;

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

            if (_datasource != null)
            {
                SaveFileDialog _dialog = new SaveFileDialog();
                _dialog.DefaultExt = "xml";
                _dialog.FileName   = "userlogs.xml";
                _dialog.Filter     = "Extensive Markup Language Files (*.xml)|*.xml";
                _dialog.Title      = "Export User Logs";
                if (_dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    _dialog.Dispose(); _dialog = null;
                    Materia.RefreshAndManageCurrentProcess(); return;
                }

                DataTable _viewtable = _datasource.DefaultView.ToTable();
                Cursor                 = Cursors.WaitCursor;
                btnClear.Enabled       = false; btnSearch.Enabled = false;
                btnExportExcel.Enabled = false; btnExportXml.Enabled = false;

                Func <DataTable, DataTable> _delegate = new Func <DataTable, DataTable>(Materia.ToExportableTable);
                IAsyncResult _result = _delegate.BeginInvoke(_viewtable, null, _delegate);
                _result.WaitToFinish();
                DataTable _exportabletable = _delegate.EndInvoke(_result);

                try
                {
                    _exportabletable.WriteXml(_dialog.FileName, XmlWriteMode.WriteSchema);
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ExportXml, "Exported user logs into : " + _dialog.FileName + ".");
                    _logresult.WaitToFinish(); Cursor = Cursors.Default;

                    if (File.Exists(_dialog.FileName))
                    {
                        Process.Start("explorer.exe", "/select, \"" + _dialog.FileName + "\"");
                    }
                }
                catch (Exception ex)
                {
                    SCMS.LogError(this.GetType().Name, ex);
                    MsgBoxEx.Alert("Failed to export the current list into the output file.", "Export User Logs");
                }

                EnableButtons(); Cursor    = Cursors.Default;
                _dialog.Dispose(); _dialog = null;
                _exportabletable.Dispose(); _exportabletable = null;
                _viewtable.Dispose(); _viewtable             = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtSystemVersion, !string.IsNullOrEmpty(txtSystemVersion.Text.RLTrim()), "Please specify the applicable system version for the current script."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtTitle, !string.IsNullOrEmpty(txtTitle.Text.RLTrim()), "Please specify database script's title."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtScript, !string.IsNullOrEmpty(txtScript.Text.RLTrim()), "Please specify database script's sql statement."))
            {
                return;
            }
            if (!Materia.Valid(_validator, txtDescription, !string.IsNullOrEmpty(txtDescription.Text.RLTrim()), "Please specify database script's description."))
            {
                return;
            }

            string _pattern = "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+";

            if (!Materia.Valid(_validator, txtSystemVersion, Regex.IsMatch(txtSystemVersion.Text, _pattern), "Please specify a valid system version."))
            {
                return;
            }

            MatchCollection _matches = Regex.Matches(txtSystemVersion.Text, _pattern);

            if (_matches.Count > 0)
            {
                string _match = _matches[0].Value;
                if (!Materia.Valid(_validator, txtSystemVersion, _match == txtSystemVersion.Text, "Please specify a valid system version."))
                {
                    return;
                }
            }
            DataTable _scripts = Cache.GetCachedTable("scripts");

            if (_scripts != null)
            {
                string _query = ""; string _refno = "";
                DataColumnCollection _cols = _scripts.Columns;

                if (_isnew)
                {
                    Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber);
                    IAsyncResult _result = _delegate.BeginInvoke("scripts", 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;
                    }

                    string _seriesno = _delegate.EndInvoke(_result);
                    _refno = "SQL-" + SCMS.CurrentCompany.Company + "-" + _seriesno;

                    _query = "INSERT INTO `scripts`\n" +
                             "(`ReferenceNo`, `Title`, `Author`, `Script`, `SystemVersion`, `RequireBackup`, `RequireAppRestart`, `RequirePcRestart`, `Description`, `DateCreated`)\n" +
                             "VALUES\n" +
                             "('" + _refno.ToSqlValidString() + "', '" + txtTitle.Text.ToSqlValidString() + "', '" + txtAuthor.Text.ToSqlValidString() + "', '" + txtScript.Text.ToSqlValidString() + "', '" + txtSystemVersion.Text.ToSqlValidString() + "', " + (chkBackup.Checked ? "1" : "0") + ", " + (chkRestartApp.Checked ? "1" : "0") + ", " + (chkRestartPc.Checked ? "1" : "0") + ", '" + txtDescription.Text.ToSqlValidString() + "', NOW());";

                    object[] _values = new object[_cols.Count];
                    _values[_cols["ReferenceNo"].Ordinal]       = _refno;
                    _values[_cols["Title"].Ordinal]             = txtTitle.Text;
                    _values[_cols["Author"].Ordinal]            = txtAuthor.Text;
                    _values[_cols["Script"].Ordinal]            = txtScript.Text;
                    _values[_cols["SystemVersion"].Ordinal]     = txtSystemVersion.Text;
                    _values[_cols["RequireBackup"].Ordinal]     = (chkBackup.Checked? 1 : 0);
                    _values[_cols["RequireAppRestart"].Ordinal] = (chkRestartApp.Checked ? 1 : 0);
                    _values[_cols["RequirePcRestart"].Ordinal]  = (chkRestartPc.Checked ? 1 : 0);
                    _values[_cols["Description"].Ordinal]       = txtDescription.Text;
                    _values[_cols["DateCreated"].Ordinal]       = DateTime.Now;
                    _values[_cols["LastModified"].Ordinal]      = DateTime.Now;
                    _scripts.Rows.Add(_values);
                }
                else
                {
                    _query = "UPDATE `scripts` SET\n" +
                             "`Title` = '" + txtTitle.Text.ToSqlValidString() + "', `Author` = '" + txtAuthor.Text.ToSqlValidString() + "', `Author` = '" + txtAuthor.Text.ToSqlValidString() + "', `Script` = '" + txtScript.Text.ToSqlValidString() + "', `SystemVersion` = '" + txtSystemVersion.Text.ToSqlValidString() + "', `RequireBackup` = " + (chkBackup.Checked ? "1" : "0") + ", `RequireAppRestart` = " + (chkRestartApp.Checked ? "1" : "0") + ", `RequirePcRestart` = " + (chkRestartPc.Checked ? "1" : "0") + ", `Description` = '" + txtDescription.Text.ToSqlValidString() + "'\n" +
                             "WHERE\n" +
                             "(`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString() + "');";

                    DataRow[] _existing = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");

                    if (_existing.Length > 0)
                    {
                        _existing[0]["Title"]             = txtTitle.Text;
                        _existing[0]["Author"]            = txtAuthor.Text;
                        _existing[0]["Script"]            = txtScript.Text;
                        _existing[0]["SystemVersion"]     = txtSystemVersion.Text;
                        _existing[0]["RequireBackup"]     = (chkBackup.Checked? 1 : 0);
                        _existing[0]["RequireAppRestart"] = (chkRestartApp.Checked ? 1 : 0);
                        _existing[0]["RequirePcRestart"]  = (chkRestartPc.Checked? 1 : 0);
                        _existing[0]["Description"]       = txtDescription.Text;
                    }
                }


                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a database script : " + _refno + ".";
                            if (!_isnew)
                            {
                                _log = "Updated database script : " + _referenceno + ".";
                            }

                            _scripts.AcceptChanges();
                            if (_isnew)
                            {
                                _referenceno = _refno;
                                _isnew       = false;

                                btnExport.Enabled = true;
                                btnExport.Show(); btnExport.BringToFront();

                                btnExecute.Enabled = true;
                                btnExecute.Show(); btnExecute.BringToFront();
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log, _referenceno);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                btnSave_Click(sender, new EventArgs());
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current database script.", "Save Database Script");
                            }

                            _scripts.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
Example #20
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 btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

            if (!Materia.Valid(_validator, txtValue, txtValue.Value > 0, "Please specify currency denomination value."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboCurrency, cboCurrency.SelectedIndex >= 0, "Please specify a valid currency."))
            {
                return;
            }

            DataTable _denominations = Cache.GetCachedTable("currencydenominations");
            DataRow   _newrow        = null;

            if (_denominations != null)
            {
                DataRow[] _rows = _denominations.Select("([Denomination] = " + txtValue.Value.ToSqlValidString() + " AND\n" +
                                                        " [Currency] LIKE '" + cboCurrency.SelectedValue.ToString().ToSqlValidString(true) + "') AND\n" +
                                                        "([DetailId] <> " + _id.ToString() + ")");

                if (!Materia.Valid(_validator, txtValue, _rows.Length <= 0, "Currency denomination already exists."))
                {
                    return;
                }

                string _query = "";
                DataColumnCollection _cols = _denominations.Columns;

                if (_isnew)
                {
                    _query = "INSERT INTO `currencydenominations`\n" +
                             "(`Currency`, `Denomination`, `Active`, `DateCreated`)\n" +
                             "VALUES\n" +
                             "('" + cboCurrency.SelectedValue.ToString().ToSqlValidString(true) + "', " + txtValue.Value.ToSqlValidString() + ", " + (chkActive.Checked? "1" : "0").ToString() + ", NOW());\n" +
                             "SELECT LAST_INSERT_ID() AS `Id`;";

                    object[] _values = new object[_cols.Count];
                    _values[_cols["Currency"].Ordinal]     = cboCurrency.SelectedValue;
                    _values[_cols["Denomination"].Ordinal] = txtValue.Value;
                    _values[_cols["Active"].Ordinal]       = (chkActive.Checked ? 1 : 0);
                    _values[_cols["DateCreated"].Ordinal]  = DateTime.Now;
                    _values[_cols["LastModified"].Ordinal] = DateTime.Now;
                    _newrow = _denominations.Rows.Add(_values);
                }
                else
                {
                    _query = "UPDATE `currencydenominations` SET\n" +
                             "`Currency` = '" + cboCurrency.SelectedValue.ToString().ToSqlValidString() + "', `Denomination` = " + txtValue.Value.ToSqlValidString() + ", `Active` = " + (chkActive.Checked? "1" : "0").ToString() + "\n" +
                             "WHERE\n" +
                             "(`DetailId` = " + _id.ToString() + ");";

                    DataRow[] _existing = _denominations.Select("[DetailId] = " + _id.ToString());
                    if (_existing.Length > 0)
                    {
                        _existing[0]["Currency"]     = cboCurrency.SelectedValue;
                        _existing[0]["Denomination"] = txtValue.Value;
                        _existing[0]["Active"]       = (chkActive.Checked? 1 : 0);
                    }
                }

                if (!string.IsNullOrEmpty(_query.RLTrim()))
                {
                    btnSave.Enabled = false; btnSaveAndClose.Enabled = false;

                    IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query);

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

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

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

                        if (string.IsNullOrEmpty(_queresult.Error.RLTrim()))
                        {
                            UserAction _action = UserAction.Add;
                            if (!_isnew)
                            {
                                _action = UserAction.Edit;
                            }

                            string _log = "Added a new currency denomination : " + txtValue.Value.ToSqlValidString() + " " + cboCurrency.SelectedValue.ToString() + ".";
                            if (!_isnew)
                            {
                                _log = "Updated currency denomination : " + txtValue.Value.ToSqlValidString() + " " + cboCurrency.SelectedValue.ToString() + ".";
                            }

                            if (_isnew)
                            {
                                if (_queresult.ResultSet.Tables.Count > 0)
                                {
                                    DataTable _table = _queresult.ResultSet.Tables[0];
                                    if (_table.Rows.Count > 0)
                                    {
                                        DataRow _row = _table.Rows[0];
                                        if (VisualBasic.IsNumeric(_row["Id"]))
                                        {
                                            _id = VisualBasic.CLng(_row["Id"]);
                                            if (_newrow != null)
                                            {
                                                _newrow["DetailId"] = _id;
                                            }
                                        }
                                    }
                                }
                            }

                            _denominations.AcceptChanges();

                            if (_isnew)
                            {
                                _isnew = false;
                            }
                            if (_updated)
                            {
                                _updated = false;
                            }
                            if (!_withupdates)
                            {
                                _withupdates = true;
                            }
                            Text   = Text.Replace(" *", "").Replace("*", "");
                            Cursor = Cursors.WaitCursor;

                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log);
                            _logresult.WaitToFinish();

                            Cursor = Cursors.Default;

                            if (sender == btnSaveAndClose)
                            {
                                DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                            }
                        }
                        else
                        {
                            if (_queresult.Error.Contains("duplicate"))
                            {
                                bool _invalid = Materia.Valid(_validator, txtValue, false, "Currency denomination already exists.");
                            }
                            else
                            {
                                SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error));
                                MsgBoxEx.Alert("Failed to save the current currency denomination.", "Save Currency Denomination");
                            }

                            _denominations.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        /// <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);
        }