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(); } }
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, 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 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 btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtModel, !string.IsNullOrEmpty(txtModel.Text.RLTrim()), "Please specify vehicle model name.")) { return; } if (!Materia.Valid(_validator, cboBrand, cboBrand.SelectedIndex >= 0, "Please specify a valid vehicle make.")) { return; } DataTable _models = Cache.GetCachedTable("models"); if (_models != null) { DataRow[] _rows = _models.Select("([Model] LIKE '" + txtModel.Text.ToSqlValidString(true) + "' AND\n" + " [Brand] LIKE '" + cboBrand.SelectedValue.ToString().ToSqlValidString(true) + "') AND\n" + "NOT ([ModelCode] LIKE '" + _modelcode.ToSqlValidString(true) + "')"); if (!Materia.Valid(_validator, txtModel, _rows.Length <= 0, "Model already exists.")) { return; } string _query = ""; DataColumnCollection _cols = _models.Columns; string _refno = ""; if (_isnew) { Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber); IAsyncResult _result = _delegate.BeginInvoke("models", 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; } _refno = _delegate.EndInvoke(_result); _query = "INSERT INTO `models`\n" + "(`ModelCode`, `Model`, `Brand`, `DateCreated`)\n" + "VALUES\n" + "('MODEL-" + _refno + "', '" + txtModel.Text.ToSqlValidString() + "', '" + cboBrand.SelectedValue.ToString().ToSqlValidString() + "', NOW());"; object[] _values = new object[_cols.Count]; _values[_cols["ModelCode"].Ordinal] = "MODEL-" + _refno; _values[_cols["Model"].Ordinal] = txtModel.Text; _values[_cols["Brand"].Ordinal] = cboBrand.SelectedValue; _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _models.Rows.Add(_values); } else { _query = "UPDATE `models` SET\n" + "`Model` = '" + txtModel.Text.ToSqlValidString() + "', `Brand` = '" + cboBrand.SelectedValue.ToString().ToSqlValidString() + "'\n" + "WHERE\n" + "(`ModelCode` LIKE '" + _modelcode.ToSqlValidString() + "');"; DataRow[] _existing = _models.Select("[ModelCode] LIKE '" + _modelcode.ToSqlValidString(true) + "'"); if (_existing.Length > 0) { _existing[0]["Model"] = txtModel.Text; _existing[0]["Brand"] = cboBrand.SelectedValue; } } 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 model : " + txtModel.Text + "."; if (!_isnew) { _log = "Updated model : " + cboBrand.SelectedValue.ToString() + " - " + txtModel.Text + "."; } _models.AcceptChanges(); if (_isnew) { _modelcode = "MODEL-" + _refno; } 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, txtModel, false, "Model already exists."); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current model.", "Save Model"); } _models.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } 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, txtDescription, !string.IsNullOrEmpty(txtDescription.Text.RLTrim()), "Please specify bank miscellaneous.")) { return; } if (!Materia.Valid(_validator, cboAccount, cboAccount.SelectedIndex >= 0, "Please specify a valid account.")) { return; } if (!Materia.Valid(_validator, cboType, cboType.SelectedIndex >= 0, "Please specify a valid type.")) { return; } DataTable _bankmisc = Cache.GetCachedTable("bankmiscellaneous"); if (_bankmisc != null) { DataRow[] _rows = _bankmisc.Select("([BankMiscellaneous] LIKE '" + txtDescription.Text.ToSqlValidString(true) + "') AND\n" + "NOT ([BankMiscellaneous] LIKE '" + _bankmiscellaneous.ToSqlValidString(true) + "')"); if (!Materia.Valid(_validator, txtDescription, _rows.Length <= 0, "Bank miscellaneous already exists.")) { return; } string _query = ""; DataColumnCollection _cols = _bankmisc.Columns; if (_isnew) { _query = "INSERT INTO `bankmiscellaneous`\n" + "(`BankMiscellaneous`, `AccountCode`, `Type`, `DateCreated`)\n" + "VALUES\n" + "('" + txtDescription.Text.ToSqlValidString() + "', " + cboAccount.SelectedValue.ToString() + ", " + cboType.SelectedIndex.ToString() + ", NOW());"; object[] _values = new object[_cols.Count]; _values[_cols["BankMiscellaneous"].Ordinal] = txtDescription.Text; _values[_cols["AccountCode"].Ordinal] = cboAccount.SelectedValue; _values[_cols["Type"].Ordinal] = cboType.SelectedIndex; _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _bankmisc.Rows.Add(_values); } else { _query = "UPDATE `bankmiscellaneous` SET\n" + "`BankMiscellaneous` = '" + txtDescription.Text.ToSqlValidString() + "', `AccountCode` = " + cboAccount.SelectedValue.ToString() + ", `Type` = " + cboType.SelectedIndex.ToString() + "\n" + "WHERE\n" + "(`BankMiscellaneous` LIKE '" + _bankmiscellaneous.ToSqlValidString() + "');"; DataRow[] _existing = _bankmisc.Select("[BankMiscellaneous] LIKE '" + _bankmiscellaneous.ToSqlValidString(true) + "'"); if (_existing.Length > 0) { _existing[0]["BankMiscellaneous"] = txtDescription.Text; _existing[0]["AccountCode"] = cboAccount.SelectedValue; _existing[0]["Type"] = cboType.SelectedIndex; } } 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 miscellaneous : " + txtDescription.Text + "."; if (!_isnew) { _log = "Updated bank miscellaneous : " + _bankmiscellaneous + (_bankmiscellaneous != txtDescription.Text ? " to " + txtDescription.Text : "").ToString() + "."; } _bankmisc.AcceptChanges(); _bankmiscellaneous = txtDescription.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, txtDescription, false, "Bank miscellaneous already exists."); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current bank miscellaneous.", "Save Bank Miscellaneous"); } _bankmisc.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } else { if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.None; Close(); } } }
private void RunRestoration() { if (!File.Exists(_backupfilename)) { MsgBoxEx.Shout("Could not locate the specified database backup file / restore point.", "Database Restoration"); return; } btnBrowseDrive.Enabled = false; btnBrowseRestorePoint.Enabled = false; btnRestore.Enabled = false; btnCancel.BringToFront(); InitializeEventGrid(); chkCreateRestorePoint.Enabled = false; pctLoad.Show(); pctLoad.BringToFront(); _isrunning = true; _cancelled = false; AddEvent(BackupEvent.Information, "Starting database restoration routines..."); RestorePointInfo _restorepoint = null; if (chkCreateRestorePoint.Checked) { _restorepoint = MakeRestorePoint(); if (_restorepoint == null) { btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return; } } string _filename = _backupfilename; int _trycounter = 0; if (Path.GetExtension(_filename).ToLower().Replace(".", "").RLTrim() == "scmsiv") { AddEvent(BackupEvent.Information, "Extracting database backup..."); _filename = ""; string _dbtempdir = Application.StartupPath + "\\dbtemp"; if (!Directory.Exists(_dbtempdir)) { try { Directory.CreateDirectory(_dbtempdir); } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Could not create temporary backup file extraction directory."); btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return; } } string _archivedir = _dbtempdir + "\\" + Path.GetFileNameWithoutExtension(_backupfilename); Func <string, string, bool> _extractordelegate = new Func <string, string, bool>(Archiver.Decompress); IAsyncResult _extractorresult = _extractordelegate.BeginInvoke(_backupfilename, _archivedir, null, _extractordelegate); while (!_extractorresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { AddEvent(BackupEvent.Warning, "Cancelling database restoration..."); _trycounter = 0; while (Directory.Exists(_archivedir) && _trycounter <= 30) { try { Directory.Delete(_archivedir, true); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); AddEvent(BackupEvent.Information, "Cancelled database restoration."); _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { bool _extracted = _extractordelegate.EndInvoke(_extractorresult); if (_extracted) { if (Directory.Exists(_archivedir)) { string[] _files = Directory.GetFiles(_archivedir); foreach (string _file in _files) { if (Path.GetExtension(_file).ToLower().Replace(".", "").RLTrim() == "sql") { _filename = _file; break; } } if (String.IsNullOrEmpty(_filename.RLTrim())) { AddEvent(BackupEvent.Error, "Could not find any supported database backup file."); _trycounter = 0; while (Directory.Exists(_archivedir) && _trycounter <= 30) { try { Directory.Delete(_archivedir, true); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return; } } else { AddEvent(BackupEvent.Error, "Could not extract data from database backup."); _trycounter = 0; while (Directory.Exists(_archivedir) && _trycounter <= 30) { try { Directory.Delete(_archivedir, true); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return; } } else { AddEvent(BackupEvent.Error, "Could not extract data from database backup."); _trycounter = 0; while (Directory.Exists(_archivedir) && _trycounter <= 30) { try { Directory.Delete(_archivedir, true); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); return; } } } if (!String.IsNullOrEmpty(_filename.RLTrim())) { FileInfo _backupfile = new FileInfo(_filename); Func <string, FileInfo, MySqlResult> _restoredelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute); IAsyncResult _restoreresult = _restoredelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _backupfile, null, _restoredelegate); while (!_restoreresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { AddEvent(BackupEvent.Warning, "Cancelling database restoration..."); if (_restorepoint != null) { if (File.Exists(_restorepoint.Filename)) { AddEvent(BackupEvent.Information, "Performing roll back from recorded restore point."); FileInfo _restorepointfile = new FileInfo(_restorepoint.Filename); _trycounter = 0; while (_trycounter < 30) { _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } Func <string, FileInfo, MySqlResult> _restorepointdelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute); IAsyncResult _restorepointresult = _restorepointdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _restorepointfile, null, _restorepointdelegate); _restorepointresult.WaitToFinish(); MySqlResult _rpresult = _restorepointdelegate.EndInvoke(_restorepointresult); if (_rpresult.Succeeded) { AddEvent(BackupEvent.Success, "Roll back from recorded restore point has been completed."); } else { SCMS.LogError(this.GetType().Name, new Exception(_rpresult.Error)); AddEvent(BackupEvent.Error, "Failed to roll back from restore point."); } } } SCMS.CleanUp(); btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); AddEvent(BackupEvent.Information, "Cancelled database restoration."); _trycounter = 0; while (_trycounter < 30) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { MySqlResult _execresult = _restoredelegate.EndInvoke(_restoreresult); if (_execresult.Succeeded) { AddEvent(BackupEvent.Information, "Finalizing database restoration..."); IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.RestoreDatabase, "Restored database from file : " + lblPath.Text.ToSqlValidString().Replace("\\\\", "\\") + "."); IAsyncResult _queexresult = Que.BeginExecution(SCMS.ServerConnection.ToString(), "UPDATE `settings` SET `LastRestored` = NOW();"); while (!_logresult.IsCompleted && !_queexresult.IsCompleted) { Thread.Sleep(1); Application.DoEvents(); } QueResult _queresult = Que.EndExecution(_queexresult); _queresult.Dispose(QueResultDisposition.WithAssociatedQue); SCMS.CleanUp(); _isrunning = false; AddEvent(BackupEvent.Success, "Database backup restoration has been completed."); _trycounter = 0; while (_trycounter <= 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } MsgBoxEx.Inform("Application will restart for the restored values to fully take effect.", "Database Backup Restoration"); DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } else { SCMS.LogError(this.GetType().Name, new Exception(_execresult.Error)); AddEvent(BackupEvent.Error, "Failed to complete database restoration from the specified database backup / restore point."); if (_restorepoint != null) { if (File.Exists(_restorepoint.Filename)) { AddEvent(BackupEvent.Information, "Performing roll back from recorded restore point."); FileInfo _restorepointfile = new FileInfo(_restorepoint.Filename); _trycounter = 0; while (_trycounter < 15) { _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } Func <string, FileInfo, MySqlResult> _restorepointdelegate = new Func <string, FileInfo, MySqlResult>(MySql.Execute); IAsyncResult _restorepointresult = _restorepointdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _restorepointfile, null, _restorepointdelegate); _restorepointresult.WaitToFinish(); MySqlResult _rpresult = _restorepointdelegate.EndInvoke(_restorepointresult); if (_rpresult.Succeeded) { AddEvent(BackupEvent.Success, "Roll back from recorded restore point has been completed."); } else { SCMS.LogError(this.GetType().Name, new Exception(_rpresult.Error)); AddEvent(BackupEvent.Error, "Failed to roll back from restore point."); } } } SCMS.CleanUp(); btnBrowseDrive.Enabled = true; btnBrowseRestorePoint.Enabled = true; btnRestore.Enabled = true; btnCancel.SendToBack(); chkCreateRestorePoint.Enabled = true; pctLoad.Hide(); _isrunning = false; Materia.RefreshAndManageCurrentProcess(); } } } }
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(); } }
/// <summary> /// Updates the current workstation's cache time stamp. /// </summary> /// <param name="timestamp"></param> public static void UpdateCacheTimeStamp(DateTime timestamp) { string _path = Application.StartupPath + "\\Xml\\cachesettings.xml"; DataTable _cachesettings = SCMS.XmlToTable(_path); if (_cachesettings != null) { CompanyInfo _company = SCMS.CurrentCompany; ServerConnectionInfo _server = SCMS.ServerConnection; if (_company == null) { _company = new CompanyInfo(SCMS.LastSelectedCompany); } if (_server == null) { _server = new ServerConnectionInfo(SCMS.LastSelectedConnection); } if (_cachesettings.Rows.Count > 0) { DataRow[] _rows = _cachesettings.Select("[Company] LIKE '" + _company.Company.ToSqlValidString(true) + "' AND\n" + "[Server] LIKE '" + _server.Server.ToSqlValidString(true) + "' AND\n" + "[Database] LIKE '" + _server.Database.ToSqlValidString(true) + "'"); if (_rows.Length > 0) { _rows[0]["LastRestored"] = timestamp; } else { object[] _values = new object[_cachesettings.Columns.Count]; DataColumnCollection _cols = _cachesettings.Columns; _values[_cols["Company"].Ordinal] = _company.Company; _values[_cols["Server"].Ordinal] = _server.Server; _values[_cols["Database"].Ordinal] = _server.Database; _values[_cols["LastRestored"].Ordinal] = timestamp; _cachesettings.Rows.Add(_values); } } else { object[] _values = new object[_cachesettings.Columns.Count]; DataColumnCollection _cols = _cachesettings.Columns; _values[_cols["Company"].Ordinal] = _company.Company; _values[_cols["Server"].Ordinal] = _server.Server; _values[_cols["Database"].Ordinal] = _server.Database; _values[_cols["LastRestored"].Ordinal] = timestamp; _cachesettings.Rows.Add(_values); } _cachesettings.AcceptChanges(); try { _cachesettings.WriteXml(_path, XmlWriteMode.WriteSchema); } catch { } _cachesettings.Dispose(); _cachesettings = null; Materia.RefreshAndManageCurrentProcess(); } }
private RestorePointInfo MakeRestorePoint() { RestorePointInfo _restorepoint = null; AddEvent(BackupEvent.Information, "Creating database restore point..."); string _rpdir = Application.StartupPath + "\\Restore Points"; if (!Directory.Exists(_rpdir)) { try { Directory.CreateDirectory(_rpdir); } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Can't create database restore point directory."); } } if (Directory.Exists(_rpdir)) { Func <IDbConnection, DateTime> _serverdatedelegate = new Func <IDbConnection, DateTime>(MySql.GetServerDateAndTime); IAsyncResult _serverdateresult = _serverdatedelegate.BeginInvoke(SCMS.Connection, null, _serverdatedelegate); _serverdateresult.WaitToFinish(); DateTime _serverdatetime = _serverdatedelegate.EndInvoke(_serverdateresult); string _rpfilename = _rpdir + "\\" + SCMS.ServerConnection.Database.ToUpper() + "_" + SCMS.CurrentCompany.Company + "_RESTORE_POINT_" + VisualBasic.Format(_serverdatetime, "dd_MM_yyyy_HH_mm_ss") + ".sql"; int _trycounter = 0; MySqlDumpParameterCollection _parameters = new MySqlDumpParameterCollection(); _parameters.Add(MySqlDumpParameters.CompleteInsert); _parameters.Add(MySqlDumpParameters.HexBlob); _parameters.Add(MySqlDumpParameters.Routines); _parameters.Add("--skip-extended-insert"); _parameters.Add(MySqlDumpParameters.Triggers); _parameters.Add(MySqlDumpParameters.Quick); Func <string, string, MySqlDumpParameterCollection, MySqlResult> _dumpdelegate = new Func <string, string, MySqlDumpParameterCollection, MySqlResult>(MySql.Dump); IAsyncResult _dumpresult = _dumpdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _rpfilename, _parameters, null, _dumpdelegate); AddEvent(BackupEvent.Information, "Restore point creation started."); while (!_dumpresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { AddEvent(BackupEvent.Warning, "Cancelling restore point creation..."); _trycounter = 0; while (File.Exists(_rpfilename) && _trycounter <= 30) { try { File.Delete(_rpfilename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } Materia.RefreshAndManageCurrentProcess(); AddEvent(BackupEvent.Information, "Restore point creation cancelled."); } else { MySqlResult _result = _dumpdelegate.EndInvoke(_dumpresult); if (_result.Succeeded) { string _path = Application.StartupPath + "\\Xml\\restorepoints.xml"; DataTable _table = SCMS.XmlToTable(_path); if (_table != null) { bool _created = false; DataRow _newrow = null; object[] _values = new object[_table.Columns.Count]; DataColumnCollection _cols = _table.Columns; _values[_cols["DateAndTime"].Ordinal] = _serverdatetime; _values[_cols["Filename"].Ordinal] = _rpfilename; _values[_cols["Company"].Ordinal] = SCMS.CurrentCompany.Company; _values[_cols["Server"].Ordinal] = SCMS.ServerConnection.Server; _values[_cols["Database"].Ordinal] = SCMS.ServerConnection.Database; try { _newrow = _table.Rows.Add(_values); _table.AcceptChanges(); _table.WriteXml(_path, XmlWriteMode.WriteSchema); _created = true; } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point."); _trycounter = 0; while (File.Exists(_rpfilename) && _trycounter <= 30) { try { File.Delete(_rpfilename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } } if (_created) { _restorepoint = new RestorePointInfo(VisualBasic.CLng(_newrow["DetailId"])); } _table.Dispose(); _table = null; Materia.RefreshAndManageCurrentProcess(); } else { AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point."); _trycounter = 0; while (File.Exists(_rpfilename) && _trycounter <= 30) { try { File.Delete(_rpfilename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } Materia.RefreshAndManageCurrentProcess(); } } else { SCMS.LogError(this.GetType().Name, new Exception(_result.Error)); AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point."); _trycounter = 0; while (File.Exists(_rpfilename) && _trycounter <= 30) { try { File.Delete(_rpfilename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } Materia.RefreshAndManageCurrentProcess(); } } } return(_restorepoint); }
/// <summary> /// Synchronizes the specified database table using the supplied database connection. /// </summary> /// <param name="connection"></param> /// <param name="tablename"></param> /// <param name="primarykey"></param> public static void SyncTable(IDbConnection connection, string tablename, string primarykey) { if (_cacheddataset == null) { _cacheddataset = SCMS.XmlToDataSet(CachePath); } if (_cacheddataset == null) { if (connection != null) { _cacheddataset = new DataSet(); _cacheddataset.DataSetName = connection.ConnectionString.ConnectionStringValue(ConnectionStringSection.Database); } } if (_cacheddataset != null) { DataTable _table = null; if (_cacheddataset.Tables.Contains(tablename)) { _table = _cacheddataset.Tables[tablename]; DataTable _updated = null; if (_table.Columns.Contains("LastModified") || _table.Columns.Contains("DateAndTime")) { DateTime _lastupdate = VisualBasic.CDate("1/1/1900"); string _datetimefield = "DateAndTime"; if (_table.Columns.Contains("LastModified")) { _datetimefield = "LastModified"; } object _maxdate = _table.Compute("MAX([" + _datetimefield + "])", ""); if (VisualBasic.IsDate(_maxdate)) { _lastupdate = VisualBasic.CDate(_maxdate); } _updated = _updated.LoadData(SCMS.Connection, "SELECT `OldValue`, `NewValue` FROM `updateditems` AS `u` WHERE (`TableName` LIKE '" + tablename.ToSqlValidString() + "') AND (`LastModified` >= '" + _lastupdate.ToSqlValidString(true) + "')"); } else { _updated = _updated.LoadData(SCMS.Connection, "SELECT `OldValue`, `NewValue` FROM `updateditems` AS `u` WHERE (`TableName` LIKE '" + tablename.ToSqlValidString() + "')"); } if (_updated != null) { string _pk = primarykey; if (string.IsNullOrEmpty(_pk.RLTrim())) { for (int i = 0; i <= (_table.Columns.Count - 1); i++) { if (_table.Columns[i].Unique) { _pk = _table.Columns[i].ColumnName; break; } } } if (!string.IsNullOrEmpty(_pk.RLTrim())) { for (int i = 0; i <= (_updated.Rows.Count - 1); i++) { DataRow _row = _updated.Rows[i]; DataRow[] _rows = _table.Select("CONVERT([" + _pk + "], System.String) = '" + _row["OldValue"].ToString().ToSqlValidString(true) + "'"); if (_rows.Length > 0) { DataRow[] _exists = _table.Select("CONVERT([" + _pk + "], System.String) = '" + _row["NewValue"].ToString().ToSqlValidString(true) + "'"); if (_exists.Length <= 0) { _rows[0][_pk] = _row["NewValue"]; } } } _table.AcceptChanges(); } _updated.Dispose(); _updated = null; Materia.RefreshAndManageCurrentProcess(); } if (_table.Columns.Contains("LastModified") || _table.Columns.Contains("DateAndTime")) { DateTime _lastupdate = VisualBasic.CDate("1/1/1900"); string _datetimefield = "DateAndTime"; if (_table.Columns.Contains("LastModified")) { _datetimefield = "LastModified"; } object _maxdate = _table.Compute("MAX([" + _datetimefield + "])", ""); if (VisualBasic.IsDate(_maxdate)) { _lastupdate = VisualBasic.CDate(_maxdate); } DataTable _updates = null; _updates = _updates.LoadData(connection, "SELECT * FROM `" + tablename + "` WHERE (`" + _datetimefield + "` >= '" + _lastupdate.ToSqlValidString(true) + "')"); if (_updates != null) { if (_updates.Rows.Count > 0) { try { _table.Merge(_updates, false, MissingSchemaAction.Add); } catch (Exception ex) { SCMS.LogError("Cache", ex); } if (_table.Columns.Contains("Voided")) { DataRow[] _rows = _table.Select("[Voided] = 1"); if (_rows.Length > 0) { System.Collections.IEnumerator _enumerators = _rows.GetEnumerator(); while (_enumerators.MoveNext()) { ((DataRow)_enumerators.Current).Delete(); } } } _table.AcceptChanges(); } try { _updates.Dispose(); } catch { } finally { _updates = null; Materia.RefreshAndManageCurrentProcess(); } } DataTable _deleted = null; if (_table.Columns.Contains("LastModified") || _table.Columns.Contains("DateAndTime")) { _deleted = _deleted.LoadData(connection, "SELECT * FROM `deleteditems` WHERE (`TableName` LIKE '" + tablename.ToSqlValidString() + "') AND (`LastModified` >= '" + _lastupdate.ToSqlValidString(true) + "');"); } else { _deleted = _deleted.LoadData(connection, "SELECT * FROM `deleteditems` WHERE (`TableName` LIKE '" + tablename.ToSqlValidString() + "');"); } if (_deleted != null) { if (_deleted.Rows.Count > 0) { for (int i = 0; i <= (_deleted.Rows.Count - 1); i++) { DataRow _delrow = _deleted.Rows[i]; string _pk = primarykey; if (string.IsNullOrEmpty(_pk.RLTrim())) { foreach (DataColumn _col in _table.Columns) { if (_col.Unique) { _pk = _col.ColumnName; break; } } } if (!String.IsNullOrEmpty(_pk.RLTrim())) { DataRow[] _delrows = _table.Select("CONVERT([" + _pk + "], System.String) LIKE '" + _delrow["Value"].ToString().ToSqlValidString(true) + "'"); if (_delrows.Length > 0) { System.Collections.IEnumerator _selrows = _delrows.GetEnumerator(); while (_selrows.MoveNext()) { ((DataRow)_selrows.Current).Delete(); } _table.AcceptChanges(); Materia.RefreshAndManageCurrentProcess(); } } } } _deleted.Dispose(); _deleted = null; Materia.RefreshAndManageCurrentProcess(); } } } else { if (connection != null) { _table = _table.LoadData(connection, "SELECT * FROM `" + tablename + "`"); if (_table != null) { if (!string.IsNullOrEmpty(primarykey.RLTrim())) { if (_table.Constraints.Count > 0 && _table.Columns.Contains(primarykey)) { _table.Constraints.Clear(); } if (_table.Constraints.Count <= 0 && _table.Columns.Contains(primarykey)) { _table.Constraints.Add("PK", _table.Columns[primarykey], true); } } if (_table.Columns.Contains("Voided")) { DataRow[] _rows = _table.Select("[Voided] = 1"); if (_rows.Length > 0) { System.Collections.IEnumerator _enumerators = _rows.GetEnumerator(); while (_enumerators.MoveNext()) { ((DataRow)_enumerators.Current).Delete(); } } } DataTable _deleted = null; _deleted = _deleted.LoadData(connection, "SELECT * FROM `deleteditems` WHERE (`TableName` LIKE '" + tablename.ToSqlValidString() + "');"); if (_deleted != null) { if (_deleted.Rows.Count > 0) { for (int i = 0; i <= (_deleted.Rows.Count - 1); i++) { DataRow _delrow = _deleted.Rows[i]; string _pk = primarykey; if (string.IsNullOrEmpty(_pk.RLTrim())) { foreach (DataColumn _col in _table.Columns) { if (_col.Unique) { _pk = _col.ColumnName; break; } } } if (!String.IsNullOrEmpty(_pk.RLTrim())) { DataRow[] _delrows = _table.Select("CONVERT([" + _pk + "], System.String) LIKE '" + _delrow["Value"].ToString().ToSqlValidString(true) + "'"); if (_delrows.Length > 0) { System.Collections.IEnumerator _selrows = _delrows.GetEnumerator(); while (_selrows.MoveNext()) { ((DataRow)_selrows.Current).Delete(); } _table.AcceptChanges(); Materia.RefreshAndManageCurrentProcess(); } } } } _deleted.Dispose(); _deleted = null; Materia.RefreshAndManageCurrentProcess(); } _table.AcceptChanges(); _cacheddataset.Tables.Add(_table); } } } Save(); } }
private void InitializeModuleNodes() { if (!_nodesloading) { _nodesloading = true; } trvwModules.BeginUpdate(); trvwModules.Nodes.Clear(); trvwModules.ImageList = _images16; trvwModules.DragDropEnabled = false; DevComponents.AdvTree.Node _scmsnode = new DevComponents.AdvTree.Node(); _scmsnode.Name = "SCMS"; _scmsnode.Text = "Supply Chain Management System"; _scmsnode.Selectable = true; _scmsnode.Enabled = true; _scmsnode.ImageKey = "SCMS"; _scmsnode.Editable = false; trvwModules.Nodes.Add(_scmsnode); string _path = Application.StartupPath + "\\Xml\\nodes.xml"; DataTable _nodes = SCMS.XmlToTable(_path); if (_nodes != null) { var _query = from _n in _nodes.AsEnumerable() where _n.Field <int>("Module") == VisualBasic.CInt(_selectedmodule) select _n; DataTable _modulenodes = null; try { _modulenodes = _query.CopyToDataTable(); } catch { } if (_modulenodes != null) { _modulenodes.TableName = "nodes"; _modulenodes.DefaultView.Sort = "[Ordering]"; DataTable _viewtable = _modulenodes.DefaultView.ToTable(); if (_viewtable.Rows.Count > 0) { for (int i = 0; i <= (_viewtable.Rows.Count - 1); i++) { DataRow _row = _viewtable.Rows[i]; DevComponents.AdvTree.Node[] _parentnodes = trvwModules.Nodes.Find(_row["ParentKey"].ToString(), true); if (_parentnodes.Length > 0) { DevComponents.AdvTree.Node _parentnode = _parentnodes[0]; DevComponents.AdvTree.Node _childnode = new DevComponents.AdvTree.Node(); _childnode.Name = _row["NodeKey"].ToString(); _childnode.Text = _row["Text"].ToString(); _childnode.ImageKey = _row["NodeKey"].ToString(); _childnode.Editable = false; _childnode.Enabled = true; _childnode.Selectable = true; _childnode.Tag = _row["SubModuleEnum"]; _parentnode.Nodes.Add(_childnode); } } } _viewtable.Dispose(); _viewtable = null; _modulenodes.Dispose(); _modulenodes = null; _nodes.Dispose(); _nodes = null; Materia.RefreshAndManageCurrentProcess(); } } trvwModules.ExpandAll(); trvwModules.EndUpdate(); if (_nodesloading) { _nodesloading = false; } if (_scmsnode.Nodes.Count > 0) { DevComponents.AdvTree.Node _selectednode = _scmsnode.Nodes[0]; trvwModules.SelectedNode = _selectednode; } }
private DataTable GetPartInventory() { DataTable _datasource = null; Cache.SyncTable(SCMS.Connection, "parts"); Cache.SyncTable(SCMS.Connection, "partnames"); Cache.SyncTable(SCMS.Connection, "partcategories"); Cache.SyncTable(SCMS.Connection, "brands"); Cache.SyncTable(SCMS.Connection, "models"); Cache.SyncTable(SCMS.Connection, "measurements"); Cache.SyncTable(SCMS.Connection, "stockledger"); Cache.SyncTable(SCMS.Connection, "customers"); Cache.SyncTable(SCMS.Connection, "suppliers"); Cache.SyncTable(SCMS.Connection, "locations"); Cache.SyncTable(SCMS.Connection, "users"); DataTable _parts = Cache.GetCachedTable("parts"); DataTable _partnames = Cache.GetCachedTable("partnames"); DataTable _partcategories = Cache.GetCachedTable("partcategories"); DataTable _brands = Cache.GetCachedTable("brands"); DataTable _models = Cache.GetCachedTable("models"); DataTable _measurements = Cache.GetCachedTable("measurements"); DataTable _ledger = Cache.GetCachedTable("stockledger"); if (_parts != null && _partnames != null && _partcategories != null && _brands != null && _models != null && _measurements != null && _ledger != null) { string _path = Application.StartupPath + "\\Xml\\stocktypes.xml"; DataTable _stocktypes = SCMS.XmlToTable(_path); if (_stocktypes != null) { var _query = from _part in _parts.AsEnumerable() join _uom in _measurements.AsEnumerable() on _part.Field <string>("Unit") equals _uom.Field <string>("Unit") join _name in _partnames.AsEnumerable() on _part.Field <string>("PartName") equals _name.Field <string>("PartName") join _brand in _brands.AsEnumerable() on _part.Field <string>("Brand") equals _brand.Field <string>("Brand") join _type in _stocktypes.AsEnumerable() on _part.Field <int>("StockType") equals _type.Field <int>("Id") join _model in _models.AsEnumerable() on _part.Field <string>("ModelCode") equals _model.Field <string>("ModelCode") into _pm join _stockledger in _ledger.AsEnumerable() on _part.Field <string>("PartCode") equals _stockledger.Field <string>("PartCode") into _sl where _part.Field <string>("Company") == SCMS.CurrentCompany.Company from _model in _pm.DefaultIfEmpty(_models.NewRow()) from _stockledger in _sl.DefaultIfEmpty(_ledger.NewRow()) group _stockledger by new { PartCode = _part.Field <string>("PartCode"), PartNo = _part.Field <string>("PartNo"), PartName = _part.Field <string>("PartName"), Description = _part.Field <string>("Description"), Brand = _part.Field <string>("Brand"), Model = _model.Field <string>("Model"), Category = _name.Field <string>("PartCategory"), Unit = _part.Field <string>("Unit"), ReorderPoint = _part.Field <int>("ReorderPoint"), ReorderQty = _part.Field <int>("ReorderQty"), Type = _type.Field <string>("StockType"), Status = (_part.Field <Int16>("Active") == 1 ? "Active" : "Inactive") } into _group select new { PartCode = _group.Key.PartCode, PartNo = _group.Key.PartNo, PartName = _group.Key.PartName, Description = _group.Key.Description, Brand = _group.Key.Brand, Model = _group.Key.Model, Category = _group.Key.Category, Unit = _group.Key.Unit, Quantity = _group.Sum(_stockledger => (_stockledger.Field <int>("In") - _stockledger.Field <int>("Out"))), Incoming = _group.Sum(_stockledger => _stockledger.Field <int>("Incoming")), Outgoing = _group.Sum(_stockledger => _stockledger.Field <int>("Outgoing")), Balance = _group.Sum(_stockledger => (_stockledger.Field <int>("In") - _stockledger.Field <int>("Out") + _stockledger.Field <int>("Incoming") - _stockledger.Field <int>("Outgoing"))), ReorderPoint = _group.Key.ReorderPoint, ReorderQty = _group.Key.ReorderQty, Type = _group.Key.Type, Status = _group.Key.Status, LastPurchased = _group.Max(_stockledger => _stockledger.Field <DateTime>("PurchaseDate")), UnitCost = _group.Sum(_stockledger => ((_stockledger.Field <int>("In") > 0 || _stockledger.Field <int>("Incoming") > 0 ? 1 : -1) * _stockledger.Field <decimal>("TotalCostUSD"))) }; _datasource = new DataTable(); _datasource.TableName = "parts"; DataColumn _dpk = _datasource.Columns.Add("PartCode", typeof(string)); _datasource.Columns.Add("PartNo", typeof(string)); _datasource.Columns.Add("PartName", typeof(string)); _datasource.Columns.Add("Description", typeof(string)); _datasource.Columns.Add("Brand", typeof(string)); _datasource.Columns.Add("Model", typeof(string)); _datasource.Columns.Add("Category", typeof(string)); _datasource.Columns.Add("Unit", typeof(string)); _datasource.Columns.Add("Quantity", typeof(int)); _datasource.Columns.Add("Incoming", typeof(int)); _datasource.Columns.Add("Outgoing", typeof(int)); _datasource.Columns.Add("Balance", typeof(int)); _datasource.Columns.Add("UnitCost", typeof(decimal)); _datasource.Columns.Add("ReorderPoint", typeof(int)); _datasource.Columns.Add("ReorderQty", typeof(int)); _datasource.Columns.Add("Type", typeof(string)); _datasource.Columns.Add("Status", typeof(string)); DataColumn _lastpurchasecol = _datasource.Columns.Add("LastPurchased", typeof(DateTime)); _lastpurchasecol.AllowDBNull = true; _datasource.Constraints.Add("PK", _dpk, true); try { foreach (var _row in _query) { decimal _unitcost = 0; if (_row.Balance > 0 && _row.UnitCost > 0) { _unitcost = _row.UnitCost / _row.Balance; } object _lastpurchased = _row.LastPurchased; if (VisualBasic.IsDate(_lastpurchased)) { if (VisualBasic.CDate(_lastpurchased) == VisualBasic.CDate("1/1/1900")) { _lastpurchased = DBNull.Value; } } _datasource.Rows.Add(new object[] { _row.PartCode, _row.PartNo, _row.PartName, _row.Description, _row.Brand, _row.Model, _row.Category, _row.Unit, _row.Quantity, _row.Incoming, _row.Outgoing, _row.Balance, _unitcost, _row.ReorderPoint, _row.ReorderQty, _row.Type, _row.Status, _lastpurchased }); } } catch { } _datasource.AcceptChanges(); } } _datasource.DefaultView.Sort = "[PartNo]"; return(_datasource); }
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 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 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 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 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 InitializeModules(ModuleGroup modules) { string _path = Application.StartupPath + "\\Xml\\modules.xml"; DataTable _table = SCMS.XmlToTable(_path); if (_table != null) { DataRow[] _rows = _table.Select("[Group] = " + VisualBasic.CInt(modules).ToString(), "[Order]"); if (_rows != null) { if (_rows.Length > 0) { brModules.Items.Clear(); for (int i = 0; i <= (_rows.Length - 1); i++) { DataRow _row = _rows[i]; Image _image = (Image)Properties.Resources.Brick.Clone(); bool _begingroup = VisualBasic.CBool(brModules.Items.Count > 0); ButtonItem _button = new ButtonItem("btnModule" + _row["Id"].ToString(), _row["Text"].ToString()); _button.ButtonStyle = eButtonStyle.ImageAndText; if (_moduleimages.Images.ContainsKey(_row["ImageKey"].ToString())) { _image = _moduleimages.Images[_row["ImageKey"].ToString()]; } _button.Image = _image; _button.ImageFixedSize = new Size(32, 32); _button.ImagePosition = eImagePosition.Top; _button.Tag = _row["Id"]; _button.FixedSize = new Size(120, 75); _button.BeginGroup = _begingroup; _button.Cursor = Cursors.Hand; _button.Click += new EventHandler(_button_Click); brModules.Items.Add(_button); } _selectedmodulegroup = modules; } } _table.Dispose(); _table = null; Materia.RefreshAndManageCurrentProcess(); } ButtonItem _modulebutton = null; Image _modulebuttonimage = (Image)Properties.Resources.Brick.Clone(); switch (modules) { case ModuleGroup.Operations: _modulebutton = new ButtonItem("btnFinance", "Finance"); if (_moduleimages.Images.ContainsKey("Finance")) { _modulebuttonimage = _moduleimages.Images["Finance"]; } _modulebutton.Image = _modulebuttonimage; _modulebutton.Tag = ModuleGroup.Finance; break; case ModuleGroup.Finance: _modulebutton = new ButtonItem("btnOperations", "Operations"); if (_moduleimages.Images.ContainsKey("Operations")) { _modulebuttonimage = _moduleimages.Images["Operations"]; } _modulebutton.Image = _modulebuttonimage; _modulebutton.Tag = ModuleGroup.Operations; break; default: break; } if (_modulebutton != null) { _modulebutton.ButtonStyle = eButtonStyle.ImageAndText; _modulebutton.ImageFixedSize = new Size(32, 32); _modulebutton.FixedSize = new Size(120, 75); _modulebutton.ImagePosition = eImagePosition.Top; bool _begingroup = VisualBasic.CBool(brModules.Items.Count > 0); _modulebutton.BeginGroup = _begingroup; _modulebutton.Click += new EventHandler(_button_Click); _modulebutton.Cursor = Cursors.Hand; brModules.Items.Add(_modulebutton); } brModules.RecalcSize(); brModules.Refresh(); brModules.Update(); Materia.RefreshAndManageCurrentProcess(); }
public string SaveBudget(SCMS.Models.BudgetMaster BudgetModel) { DALBudgetEntry objDalBudgetEntry = new DALBudgetEntry(); DALCalendar objDalCalendar = new DALCalendar(); GL_BgdtMaster GLBgdtMaster = new GL_BgdtMaster(); string ls_YearPrefix = ""; Int32 li_ReturnValue = 0; String ls_BudgetMasterId = "", ls_BudgetMasterCode = "", ls_Status = "", ls_BudgetType = "", ls_Year = "", ls_LocationId = "", ls_Remarks = "", ls_BudgetDetailId = ""; DateTime ldt_BudgetDate; try { ls_BudgetMasterId = BudgetModel.MasterId; ls_BudgetMasterCode = BudgetModel.Code.Replace("[Auto]", null); ldt_BudgetDate = !String.IsNullOrEmpty(BudgetModel.Date) ? Convert.ToDateTime(BudgetModel.Date) : DateTime.Now; ls_Status = BudgetModel.Status; ls_BudgetType = BudgetModel.BudgetType; ls_Year = BudgetModel.CalendarYear; ls_LocationId = BudgetModel.Location; ls_Remarks = BudgetModel.Remarks; //ls_YearPrefix = objDalCalendar.GetCalendarPrefix_ByCurrentDate(ldt_BudgetDate); ls_YearPrefix = objDalCalendar.GetCalendarPrefix_ByCldrId(ls_Year); if (String.IsNullOrEmpty(ls_BudgetMasterId)) { if (DALCommon.AutoCodeGeneration("GL_BgdtMaster") == 1) { if (ls_YearPrefix == null && ls_YearPrefix == "") { return ""; } ls_BudgetMasterId = DALCommon.GetMaxBudgetMasId(ls_YearPrefix); ls_BudgetMasterCode = ls_BudgetMasterId; } } else { objDalBudgetEntry.DeleteBudgetDetail_ByBgdtMasId(ls_BudgetMasterId); } if (!String.IsNullOrEmpty(ls_BudgetMasterCode)) { GLBgdtMaster.BgdtMas_Id = ls_BudgetMasterId; GLBgdtMaster.BgdtMas_Code = ls_BudgetMasterCode; GLBgdtMaster.BgdtMas_Date = ldt_BudgetDate; GLBgdtMaster.BgdtMas_Status = ls_Status; GLBgdtMaster.BgdtType_Id = ls_BudgetType; GLBgdtMaster.Cldr_Id = ls_Year; GLBgdtMaster.Loc_Id = ls_LocationId; GLBgdtMaster.BgdtMas_Remarks = ls_Remarks; GLBgdtMaster.BgdtMas_EnteredDate = DateTime.Now; GLBgdtMaster.BgdtMas_EnteredBy = ((SECURITY_User)Session["user"]).User_Title; li_ReturnValue = objDalBudgetEntry.SaveBudgetMaster(GLBgdtMaster); if (li_ReturnValue > 0) { foreach (SCMS.Models.BudgetDetail detail in BudgetModel.ListBudgetDetail) { ls_BudgetDetailId = DALCommon.GetMaxBudgetDetId(ls_YearPrefix); GL_BgdtDetail dbDetail = new GL_BgdtDetail(); dbDetail.BgdtDet_Id = ls_BudgetDetailId; dbDetail.BgdtMas_Id = ls_BudgetMasterId; dbDetail.ChrtAcc_Id = detail.Account; dbDetail.BgdtDet_Month1 = detail.Month1; dbDetail.BgdtDet_Month2 = detail.Month2; dbDetail.BgdtDet_Month3 = detail.Month3; dbDetail.BgdtDet_Month4 = detail.Month4; dbDetail.BgdtDet_Month5 = detail.Month5; dbDetail.BgdtDet_Month6 = detail.Month6; dbDetail.BgdtDet_Month7 = detail.Month7; dbDetail.BgdtDet_Month8 = detail.Month8; dbDetail.BgdtDet_Month9 = detail.Month9; dbDetail.BgdtDet_Month10 = detail.Month10; dbDetail.BgdtDet_Month11 = detail.Month11; dbDetail.BgdtDet_Month12 = detail.Month12; dbDetail.BgdtDet_TotalAmount = detail.TotalAmount; dbDetail.BgdtDet_Remarks = detail.Remarks; objDalBudgetEntry.SaveBudgetDetail(dbDetail); } } } return ls_BudgetMasterId + ":" + ls_BudgetMasterCode; } catch { return "0"; } }
private void mnuLogout_Click(object sender, EventArgs e) { SCMS.CleanUp(); SCMS.CurrentSystemUser.LogOut(); Close(); SCMS.CurrentSystemUser = null; Materia.RefreshAndManageCurrentProcess(); }
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 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"); } } } }
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 InitializeRestorePoints() { if (grdRestorePoints.Redraw) { grdRestorePoints.BeginUpdate(); } if (grdRestorePoints.DataSource != null) { try { grdRestorePoints.DataSource = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } string _path = Application.StartupPath + "\\Xml\\restorepoints.xml"; DataTable _table = SCMS.XmlToTable(_path); if (_table != null) { DataTable _datasource = new DataTable(); DataColumn _pkcol = _datasource.Columns.Add("Id", typeof(int)); _pkcol.AutoIncrement = true; _pkcol.AutoIncrementSeed = 1; _pkcol.AutoIncrementStep = 1; _datasource.Columns.Add("Select", typeof(bool)); _datasource.Columns.Add("As Of", typeof(DateTime)); _datasource.Columns.Add("Info", typeof(RestorePointInfo)); DataRow[] _rows = _table.Select("[Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "' AND\n" + "[Server] LIKE '" + SCMS.ServerConnection.Server.ToSqlValidString(true) + "' AND\n" + "[Database] LIKE '" + SCMS.ServerConnection.Database.ToSqlValidString(true) + "'"); for (int i = 0; i <= (_rows.Length - 1); i++) { DataRow _row = _rows[i]; RestorePointInfo _restorepoint = new RestorePointInfo(VisualBasic.CLng(_row["DetailId"])); if (!String.IsNullOrEmpty(_restorepoint.Filename.RLTrim())) { if (File.Exists(_restorepoint.Filename)) { DataColumnCollection _cols = _datasource.Columns; object[] _values = new object[_cols.Count]; _values[_cols["Select"].Ordinal] = VisualBasic.CBool(i == 0); _values[_cols["As Of"].Ordinal] = _row["DateAndTime"]; _values[_cols["Info"].Ordinal] = _restorepoint; _datasource.Rows.Add(_values); } } } grdRestorePoints.DataSource = _datasource; grdRestorePoints.Rows[grdRestorePoints.Rows.Fixed - 1].Visible = false; grdRestorePoints.Cols["Id"].Visible = false; grdRestorePoints.Cols["Select"].Caption = ""; grdRestorePoints.Cols["As Of"].Format = "dd-MMM-yyyy hh:mm:ss tt"; grdRestorePoints.Cols["Info"].Visible = false; grdRestorePoints.AutoNumber(); grdRestorePoints.AutoSizeCols(); grdRestorePoints.ExtendLastCol = true; } else { grdRestorePoints.InitializeAppearance(); } while (!grdRestorePoints.Redraw) { grdRestorePoints.EndUpdate(); } }
private void RunBackUp() { if (_isrunning) { return; } if (_succeeded) { _succeeded = false; } if (!Directory.Exists(Path.GetDirectoryName(lblPath.Text))) { MsgBoxEx.Shout("Please specify a valid database backup output directory.", "Database Backup"); return; } _isrunning = true; _cancelled = false; InitializeEventGrid(); btnBrowse.Enabled = false; btnBackup.Enabled = false; pctLoad.Show(); pctLoad.BringToFront(); btnCancel.BringToFront(); AddEvent(BackupEvent.Information, "Database backup operations started."); string _tempdir = Application.StartupPath + "\\dbtemp\\"; int _trycounter = 0; if (!Directory.Exists(_tempdir)) { try { Directory.CreateDirectory(_tempdir); } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Failed to create temporary output directory."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); _isrunning = false; btnCancel.SendToBack(); return; } } MySqlDumpParameterCollection _parameters = new MySqlDumpParameterCollection(); _parameters.Add(MySqlDumpParameters.CompleteInsert); _parameters.Add(MySqlDumpParameters.HexBlob); _parameters.Add(MySqlDumpParameters.Routines); _parameters.Add("--skip-extended-insert"); _parameters.Add(MySqlDumpParameters.Triggers); _parameters.Add(MySqlDumpParameters.Quick); string _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".sql"; Func <string, string, MySqlDumpParameterCollection, MySqlResult> _dumpdelegate = new Func <string, string, MySqlDumpParameterCollection, MySqlResult>(MySql.Dump); IAsyncResult _dumpresult = _dumpdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _filename, _parameters, null, _dumpdelegate); AddEvent(BackupEvent.Information, "Running database backup operations."); while (!_dumpresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_dumpresult.IsCompleted) { try { _dumpresult = null; } catch { } } AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { MySqlResult _dumpexecresult = _dumpdelegate.EndInvoke(_dumpresult); if (_dumpexecresult.Succeeded) { AddEvent(BackupEvent.Information, "Database backup has been created."); AddEvent(BackupEvent.Information, "Archiving backup file..."); Func <string, ArchivingToolEnum, FileInfo> _archiverdelegate = new Func <string, ArchivingToolEnum, FileInfo>(Archiver.CompressInsert); IAsyncResult _archiverresult = _archiverdelegate.BeginInvoke(_filename, ArchivingToolEnum.SevenZip, null, _archiverdelegate); while (!_archiverresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(20); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { FileInfo _archivefile = _archiverdelegate.EndInvoke(_archiverresult); if (_archivefile != null) { AddEvent(BackupEvent.Information, "Database backup file has been archived."); AddEvent(BackupEvent.Information, "Finalizing database backup operations..."); bool _copied = false; try { File.Copy(_archivefile.FullName, lblPath.Text, true); _copied = true; Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Failed to transfer archive file into output destinaton."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } if (_copied) { IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.BackupDatabase, "Performed database backup into : " + lblPath.Text.ToSqlValidString().Replace("\\\\", "\\") + "."); _logresult.WaitToFinish(); AddEvent(BackupEvent.Success, "Database backup operations has been completed."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; if (!_succeeded) { _succeeded = true; } } } else { AddEvent(BackupEvent.Error, "Database backup file archiving failed."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } } } else { SCMS.LogError(this.GetType().Name, new Exception(_dumpexecresult.Error)); AddEvent(BackupEvent.Error, "Database backup operations has been cancelled."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } } }
private void 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(); } } } }