Exemple #1
0
        private void CreateInitialCurrencies(IDbConnection connection)
        {
            string    _path = Application.StartupPath + "\\Xml\\defaultcurrencies.xml";
            DataTable _defaultcurrencies = SCMS.XmlToTable(_path);

            if (_defaultcurrencies != null)
            {
                Cache.SyncTable(connection, "currencies");
                DataTable _currencies = Cache.GetCachedTable("currencies");

                if (_currencies != null)
                {
                    string    _query = "";
                    long      _cashathandac = 54005; long _exrateac = 34625;
                    DataTable _accounts = Cache.GetCachedTable("accounts");

                    if (_accounts != null)
                    {
                        DataRow[] _rows = _accounts.Select("[AccountName] LIKE 'Cash at hand'");
                        if (_rows.Length > 0)
                        {
                            _cashathandac = (long)_rows[0]["AccountCode"];
                        }

                        _rows = _accounts.Select("[AccountName] LIKE 'Exchange rate differences'");
                        if (_rows.Length > 0)
                        {
                            _exrateac = (long)_rows[0]["AccountCode"];
                        }
                    }

                    for (int i = 0; i <= (_defaultcurrencies.Rows.Count - 1); i++)
                    {
                        DataRow   _row  = _defaultcurrencies.Rows[i];
                        DataRow[] _rows = _currencies.Select("[Currency] LIKE '" + _row["Currency"].ToString().ToSqlValidString(true) + "'");
                        if (_rows.Length <= 0)
                        {
                            _query += "INSERT INTO `currencies`\n" +
                                      "(`Currency`, `Description`, `AccountCode`, `ExchangeRateAccountCode`, `DateCreated`)\n" +
                                      "VALUES\n" +
                                      "('" + _row["Currency"].ToString().ToSqlValidString() + "', '" + _row["Description"].ToString().ToSqlValidString() + "', " + _cashathandac.ToString() + ", " + _exrateac.ToString() + ", NOW());";

                            DataColumnCollection _cols   = _currencies.Columns;
                            object[]             _values = new object[_cols.Count];
                            _values[_cols["Currency"].Ordinal]                = _row["Currency"];
                            _values[_cols["Description"].Ordinal]             = _row["Description"];
                            _values[_cols["AccountCode"].Ordinal]             = _cashathandac;
                            _values[_cols["ExchangeRateAccountCode"].Ordinal] = _exrateac;
                            _values[_cols["DateCreated"].Ordinal]             = DateTime.Now;
                            _values[_cols["LastModified"].Ordinal]            = DateTime.Now;
                            _currencies.Rows.Add(_values);
                        }
                    }

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

                _defaultcurrencies.Dispose(); _defaultcurrencies = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
        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();
            }
        }
        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;
        }
        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();
                }
            }
        }
        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;
                        }
                    }
                }
            }
        }
        private void CreateInitialUser(IDbConnection connection)
        {
            string    _path  = Application.StartupPath + "\\Xml\\defaultusers.xml";
            DataTable _table = SCMS.XmlToTable(_path);

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

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

                        string _query = "";  _exists = false;

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

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

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

                            _depttable.Rows.Add(_values);
                        }

                        _exists = false;

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

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

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

                            _postntable.Rows.Add(_values);
                        }

                        StringBuilder _privileges = new StringBuilder();

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

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

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

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

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

                _table.Dispose(); _table = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }