private void btnSaveCompanies_Click(object sender, EventArgs e) { if (!btnSaveCompanies.Enabled) { return; } if (grdCompanies.DataSource == null) { return; } try { grdCompanies.Row = grdCompanies.Rows.Fixed - 1; } catch { } for (int i = 0; i <= (grdCompanies.Rows.Count - 1); i++) { if (!Materia.IsNullOrNothing(grdCompanies.Rows[i]["Company"])) { if (String.IsNullOrEmpty(grdCompanies.Rows[i]["Company"].ToString().RLTrim())) { MsgBoxEx.Shout("Please specify company at entry : " + i.ToString() + ".", "Required Field Notification"); grdCompanies.StartEditing(i, grdCompanies.Cols["Company"].Index); return; } if (String.IsNullOrEmpty(grdCompanies.Rows[i]["Name"].ToString().RLTrim())) { MsgBoxEx.Shout("Please specify company name at entry : " + i.ToString() + ".", "Required Field Notification"); grdCompanies.StartEditing(i, grdCompanies.Cols["Name"].Index); return; } } } DataTable _datasource = (DataTable)grdCompanies.DataSource; if (_datasource.Rows.Count <= 0) { MsgBoxEx.Shout("Please specify at leasts a company to be registered and accessed.", "Save Company List"); return; } DataTable _changes = _datasource.GetChanges(); if (_changes != null) { try { string _path = Application.StartupPath + "\\Xml\\defaultcompanies.xml"; _datasource.WriteXml(_path, XmlWriteMode.WriteSchema); _datasource.AcceptChanges(); } catch (Exception ex) { SCMS.LogError(this.Name, ex); MsgBoxEx.Alert("Failed to save the changes made in the list. Please try again and / or report<br />this to your System Administrator.", "Save Company List"); } } }
/// <summary> /// Saves the current synchronized data into the application's cache. /// </summary> public static void Save() { if (_cacheddataset != null) { try { _cacheddataset.AcceptChanges(); _cacheddataset.WriteXml(CachePath, XmlWriteMode.WriteSchema); } catch (Exception ex) { SCMS.LogError("Cache", ex); } } }
/// <summary> /// Logs the current system user's action into the database and locally. /// </summary> /// <param name="action"></param> /// <param name="description"></param> /// <param name="refno"></param> /// <param name="amount"></param> /// <param name="currency"></param> /// <param name="amountusd"></param> public void LogAction(UserAction action, string description, string refno, decimal amount, string currency, decimal amountusd) { if (IsSignedIn) { string _path = Application.StartupPath + "\\Xml\\locallogs.xml"; DataTable _localtable = SCMS.XmlToTable(_path); if (_localtable != null) { object[] _values = new object[_localtable.Columns.Count]; DataColumnCollection _cols = _localtable.Columns; _values[_cols["Username"].Ordinal] = Username; _values[_cols["DateAndTime"].Ordinal] = DateTime.Now; _values[_cols["Action"].Ordinal] = (int)action; _values[_cols["ReferenceNo"].Ordinal] = refno; _values[_cols["Description"].Ordinal] = description; _values[_cols["Amount"].Ordinal] = amount; _values[_cols["Currency"].Ordinal] = currency; _values[_cols["AmountUSD"].Ordinal] = amountusd; _localtable.Rows.Add(_values); try { _localtable.AcceptChanges(); _localtable.WriteXml(_path, XmlWriteMode.WriteSchema); } catch (Exception ex) { SCMS.LogError("UserLogs", ex); } _localtable.Dispose(); _localtable = null; Materia.RefreshAndManageCurrentProcess(); } string _query = "INSERT INTO `userlogs`\n" + "(`Username`, `Action`, `ReferenceNo`, `Description`, `Amount`, `Currency`, `AmountUSD`, `ComputerName`, `IPAddress`)\n" + "VALUES\n" + "('" + Username.ToSqlValidString() + "', " + ((int)action).ToString() + ", '" + refno.ToSqlValidString() + "', '" + description.ToSqlValidString() + "', " + amount.ToSqlValidString() + ", '" + currency.ToSqlValidString() + "', " + amountusd.ToSqlValidString() + ", '" + Environment.MachineName.ToSqlValidString() + "', '" + Materia.GetCurrentIPAddress().ToSqlValidString() + "');"; QueResult _result = Que.Execute(SCMS.Connection, _query); if (String.IsNullOrEmpty(_result.Error.RLTrim())) { Cache.SyncTable(SCMS.Connection, "userlogs"); } else { SCMS.LogError("UserLog", new Exception(_result.Error)); } _result.Dispose(); Materia.RefreshAndManageCurrentProcess(); } }
/// <summary> /// Executes the current associated database script. /// </summary> public void Execute() { _executed = false; _error = ""; if (_databasescript != null) { MySqlResult _result = MySql.Execute(SCMS.ServerConnection.ToString(), _databasescript.SqlStatement); _executed = _result.Succeeded; _error = _result.Error; if (!string.IsNullOrEmpty(_error.RLTrim())) { SCMS.LogError(this.GetType().Name, new Exception(_error)); } _result = null; Materia.RefreshAndManageCurrentProcess(); } }
private void RunBackUp() { if (_isrunning) { return; } if (_succeeded) { _succeeded = false; } if (!Directory.Exists(Path.GetDirectoryName(lblPath.Text))) { MsgBoxEx.Shout("Please specify a valid database backup output directory.", "Database Backup"); return; } _isrunning = true; _cancelled = false; InitializeEventGrid(); btnBrowse.Enabled = false; btnBackup.Enabled = false; pctLoad.Show(); pctLoad.BringToFront(); btnCancel.BringToFront(); AddEvent(BackupEvent.Information, "Database backup operations started."); string _tempdir = Application.StartupPath + "\\dbtemp\\"; int _trycounter = 0; if (!Directory.Exists(_tempdir)) { try { Directory.CreateDirectory(_tempdir); } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Failed to create temporary output directory."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); _isrunning = false; btnCancel.SendToBack(); return; } } MySqlDumpParameterCollection _parameters = new MySqlDumpParameterCollection(); _parameters.Add(MySqlDumpParameters.CompleteInsert); _parameters.Add(MySqlDumpParameters.HexBlob); _parameters.Add(MySqlDumpParameters.Routines); _parameters.Add("--skip-extended-insert"); _parameters.Add(MySqlDumpParameters.Triggers); _parameters.Add(MySqlDumpParameters.Quick); string _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".sql"; Func <string, string, MySqlDumpParameterCollection, MySqlResult> _dumpdelegate = new Func <string, string, MySqlDumpParameterCollection, MySqlResult>(MySql.Dump); IAsyncResult _dumpresult = _dumpdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _filename, _parameters, null, _dumpdelegate); AddEvent(BackupEvent.Information, "Running database backup operations."); while (!_dumpresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_dumpresult.IsCompleted) { try { _dumpresult = null; } catch { } } AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { MySqlResult _dumpexecresult = _dumpdelegate.EndInvoke(_dumpresult); if (_dumpexecresult.Succeeded) { AddEvent(BackupEvent.Information, "Database backup has been created."); AddEvent(BackupEvent.Information, "Archiving backup file..."); Func <string, ArchivingToolEnum, FileInfo> _archiverdelegate = new Func <string, ArchivingToolEnum, FileInfo>(Archiver.CompressInsert); IAsyncResult _archiverresult = _archiverdelegate.BeginInvoke(_filename, ArchivingToolEnum.SevenZip, null, _archiverdelegate); while (!_archiverresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(20); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } else { FileInfo _archivefile = _archiverdelegate.EndInvoke(_archiverresult); if (_archivefile != null) { AddEvent(BackupEvent.Information, "Database backup file has been archived."); AddEvent(BackupEvent.Information, "Finalizing database backup operations..."); bool _copied = false; try { File.Copy(_archivefile.FullName, lblPath.Text, true); _copied = true; Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } } catch (Exception ex) { SCMS.LogError(this.GetType().Name, ex); AddEvent(BackupEvent.Error, "Failed to transfer archive file into output destinaton."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } if (_copied) { IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.BackupDatabase, "Performed database backup into : " + lblPath.Text.ToSqlValidString().Replace("\\\\", "\\") + "."); _logresult.WaitToFinish(); AddEvent(BackupEvent.Success, "Database backup operations has been completed."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; if (!_succeeded) { _succeeded = true; } } } else { AddEvent(BackupEvent.Error, "Database backup file archiving failed."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } _trycounter = 0; _filename = Application.StartupPath + "\\dbtemp\\" + Path.GetFileNameWithoutExtension(lblPath.Text) + ".7z"; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } } } else { SCMS.LogError(this.GetType().Name, new Exception(_dumpexecresult.Error)); AddEvent(BackupEvent.Error, "Database backup operations has been cancelled."); AddEvent(BackupEvent.Warning, "Cancelling database backup..."); Materia.RefreshAndManageCurrentProcess(); _trycounter = 0; while (File.Exists(_filename) && _trycounter < 30) { try { File.Delete(_filename); } catch { } _trycounter += 1; Thread.Sleep(100); Application.DoEvents(); } AddEvent(BackupEvent.Information, "Database backup operations has been cancelled."); btnBrowse.Enabled = _isfilebrowsingenabled; btnBackup.Enabled = !_isautoclose; pctLoad.Hide(); btnCancel.SendToBack(); _isrunning = false; _trycounter = 0; while (_trycounter < 10) { Thread.Sleep(100); Application.DoEvents(); _trycounter += 1; } } } }
private void 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 (!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 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 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); }
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(); } } }
/// <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 btnSaveServers_Click(object sender, EventArgs e) { if (!btnSaveServers.Enabled) { return; } if (grdServers.DataSource == null) { return; } try { grdServers.Row = grdServers.Rows.Fixed - 1; } catch { } for (int i = grdServers.Rows.Fixed; i <= (grdServers.Rows.Count - 1); i++) { if (!Materia.IsNullOrNothing(grdServers.Rows[i]["Name"])) { if (String.IsNullOrEmpty(grdServers.Rows[i]["Name"].ToString().RLTrim())) { MsgBoxEx.Shout("Please specify database server connection name at entry : " + i.ToString() + ".", "Required Field Notification"); grdServers.StartEditing(i, grdServers.Cols["Name"].Index); return; } if (String.IsNullOrEmpty(grdServers.Rows[i]["Server"].ToString().RLTrim())) { MsgBoxEx.Shout("Please specify database server IP address or hostname at entry : " + i.ToString() + ".", "Required Field Notification"); grdServers.StartEditing(i, grdServers.Cols["Server"].Index); return; } if (String.IsNullOrEmpty(grdServers.Rows[i]["Database"].ToString().RLTrim())) { MsgBoxEx.Shout("Please specify database catalog name at entry : " + i.ToString() + ".", "Required Field Notification"); grdServers.StartEditing(i, grdServers.Cols["Database"].Index); return; } } } DataTable _datasource = (DataTable)grdServers.DataSource; if (_datasource.Rows.Count <= 0) { MsgBoxEx.Shout("Please specify at least a database connection to be registered.", "Save Database Server Connections"); return; } DataTable _changes = _datasource.GetChanges(); if (_changes != null) { string _path = Application.StartupPath + "\\Xml\\databaseconnections.xml"; DataTable _current = SCMS.XmlToTable(_path); if (_current != null) { foreach (DataRow _row in _changes.Rows) { switch (_row.RowState) { case DataRowState.Added: string[] _values = new string[_current.Columns.Count]; foreach (DataColumn _col in _current.Columns) { _values[_col.Ordinal] = _row[_col.ColumnName].ToString(); } _current.Rows.Add(_values); break; case DataRowState.Modified: string _name = ""; try { _name = _row["Name", DataRowVersion.Original].ToString(); } catch { _name = _row["Name"].ToString(); } DataRow[] _existingrows = _current.Select("[Name] = '" + _name.ToSqlValidString(true) + "'"); if (_existingrows.Length > 0) { DataRow _currentrow = _existingrows[0]; foreach (DataColumn _col in _current.Columns) { _currentrow[_col.ColumnName] = _row[_col.ColumnName]; } } break; case DataRowState.Deleted: case DataRowState.Detached: string _deletedname = ""; try { _deletedname = _row["Name", DataRowVersion.Original].ToString(); } catch { _deletedname = ""; } DataRow[] _rows = _current.Select("[Name] = '" + _deletedname.ToSqlValidString(true) + "'"); if (_rows.Length > 0) { _rows[0].Delete(); } break; default: break; } } try { _current.WriteXml(_path, XmlWriteMode.WriteSchema); _datasource.AcceptChanges(); } catch (Exception ex) { SCMS.LogError(this.Name, ex); MsgBoxEx.Alert("Failed to save the changes made in the list. Please try again and / or report<br />this to your System Administrator.", "Save Database Server Connections"); } try { _current.Dispose(); } catch { } _current = null; Materia.RefreshAndManageCurrentProcess(); } } }
private void btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtLocation, !string.IsNullOrEmpty(txtLocation.Text.RLTrim()), "Please specify location name.")) { return; } DataTable _locations = Cache.GetCachedTable("locations"); if (_locations != null) { DataRow[] _rows = _locations.Select("([Location] LIKE '" + txtLocation.Text.ToSqlValidString(true) + "' AND\n" + " [Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "') AND\n" + "NOT ([LocationCode] LIKE '" + _locationcode.ToSqlValidString(true) + "')"); if (!Materia.Valid(_validator, txtLocation, _rows.Length <= 0, "Location already exists.")) { return; } string _query = ""; string _refno = _locationcode; DataColumnCollection _cols = _locations.Columns; if (_isnew) { Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber); IAsyncResult _result = _delegate.BeginInvoke("locations", true, null, _delegate); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } string _seriesnumber = _delegate.EndInvoke(_result); _refno = SCMS.CurrentCompany.Company + "-" + _seriesnumber; _query = "INSERT INTO `locations`\n" + "(`LocationCode`, `Location`, `Company`, `DateCreated`)\n" + "VALUES\n" + "('" + _refno.ToSqlValidString() + "', '" + txtLocation.Text.ToSqlValidString() + "', '" + SCMS.CurrentCompany.Company.ToSqlValidString() + "', NOW());"; object[] _values = new object[_cols.Count]; _values[_cols["LocationCode"].Ordinal] = _refno; _values[_cols["Location"].Ordinal] = txtLocation.Text; _values[_cols["Company"].Ordinal] = SCMS.CurrentCompany.Company; _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _locations.Rows.Add(_values); } else { _query = "UPDATE `locations` SET\n" + "`Location` = '" + txtLocation.Text.ToSqlValidString() + "'\n" + "WHERE\n" + "(`LocationCode` LIKE '" + _locationcode.ToSqlValidString() + "');"; DataRow[] _existing = _locations.Select("[LocationCode] LIKE '" + _locationcode.ToSqlValidString(true) + "'"); if (_existing.Length > 0) { _existing[0]["Location"] = txtLocation.Text; } } if (!string.IsNullOrEmpty(_query.RLTrim())) { btnSave.Enabled = false; btnSaveAndClose.Enabled = false; if (txtLocation.Text == _location) { if (_isnew) { _isnew = false; } if (_updated) { _updated = false; } if (_withupdates) { _withupdates = false; } Text = Text.Replace(" *", "").Replace("*", ""); if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } return; } IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } else { QueResult _queresult = Que.EndExecution(_result); if (string.IsNullOrEmpty(_queresult.Error.RLTrim())) { UserAction _action = UserAction.Add; if (!_isnew) { _action = UserAction.Edit; } string _log = "Added a new location : " + txtLocation.Text + "."; if (!_isnew) { _log = "Updated location : " + _location + (_location != txtLocation.Text ? " to " + txtLocation.Text : "").ToString() + "."; } _locations.AcceptChanges(); _locationcode = _refno; _location = txtLocation.Text; if (_isnew) { _isnew = false; } if (_updated) { _updated = false; } if (!_withupdates) { _withupdates = true; } Text = Text.Replace(" *", "").Replace("*", ""); Cursor = Cursors.WaitCursor; IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log); _logresult.WaitToFinish(); Cursor = Cursors.Default; if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } } else { if (_queresult.Error.Contains("duplicate")) { bool _invalid = Materia.Valid(_validator, txtLocation, false, "Location already exists."); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current location.", "Save Location"); } _locations.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } else { if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.None; Close(); } } }
private void btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtSystemVersion, !string.IsNullOrEmpty(txtSystemVersion.Text.RLTrim()), "Please specify the applicable system version for the current script.")) { return; } if (!Materia.Valid(_validator, txtTitle, !string.IsNullOrEmpty(txtTitle.Text.RLTrim()), "Please specify database script's title.")) { return; } if (!Materia.Valid(_validator, txtScript, !string.IsNullOrEmpty(txtScript.Text.RLTrim()), "Please specify database script's sql statement.")) { return; } if (!Materia.Valid(_validator, txtDescription, !string.IsNullOrEmpty(txtDescription.Text.RLTrim()), "Please specify database script's description.")) { return; } string _pattern = "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"; if (!Materia.Valid(_validator, txtSystemVersion, Regex.IsMatch(txtSystemVersion.Text, _pattern), "Please specify a valid system version.")) { return; } MatchCollection _matches = Regex.Matches(txtSystemVersion.Text, _pattern); if (_matches.Count > 0) { string _match = _matches[0].Value; if (!Materia.Valid(_validator, txtSystemVersion, _match == txtSystemVersion.Text, "Please specify a valid system version.")) { return; } } DataTable _scripts = Cache.GetCachedTable("scripts"); if (_scripts != null) { string _query = ""; string _refno = ""; DataColumnCollection _cols = _scripts.Columns; if (_isnew) { Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber); IAsyncResult _result = _delegate.BeginInvoke("scripts", true, null, _delegate); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch {} finally { Materia.RefreshAndManageCurrentProcess(); } } return; } string _seriesno = _delegate.EndInvoke(_result); _refno = "SQL-" + SCMS.CurrentCompany.Company + "-" + _seriesno; _query = "INSERT INTO `scripts`\n" + "(`ReferenceNo`, `Title`, `Author`, `Script`, `SystemVersion`, `RequireBackup`, `RequireAppRestart`, `RequirePcRestart`, `Description`, `DateCreated`)\n" + "VALUES\n" + "('" + _refno.ToSqlValidString() + "', '" + txtTitle.Text.ToSqlValidString() + "', '" + txtAuthor.Text.ToSqlValidString() + "', '" + txtScript.Text.ToSqlValidString() + "', '" + txtSystemVersion.Text.ToSqlValidString() + "', " + (chkBackup.Checked ? "1" : "0") + ", " + (chkRestartApp.Checked ? "1" : "0") + ", " + (chkRestartPc.Checked ? "1" : "0") + ", '" + txtDescription.Text.ToSqlValidString() + "', NOW());"; object[] _values = new object[_cols.Count]; _values[_cols["ReferenceNo"].Ordinal] = _refno; _values[_cols["Title"].Ordinal] = txtTitle.Text; _values[_cols["Author"].Ordinal] = txtAuthor.Text; _values[_cols["Script"].Ordinal] = txtScript.Text; _values[_cols["SystemVersion"].Ordinal] = txtSystemVersion.Text; _values[_cols["RequireBackup"].Ordinal] = (chkBackup.Checked? 1 : 0); _values[_cols["RequireAppRestart"].Ordinal] = (chkRestartApp.Checked ? 1 : 0); _values[_cols["RequirePcRestart"].Ordinal] = (chkRestartPc.Checked ? 1 : 0); _values[_cols["Description"].Ordinal] = txtDescription.Text; _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _scripts.Rows.Add(_values); } else { _query = "UPDATE `scripts` SET\n" + "`Title` = '" + txtTitle.Text.ToSqlValidString() + "', `Author` = '" + txtAuthor.Text.ToSqlValidString() + "', `Author` = '" + txtAuthor.Text.ToSqlValidString() + "', `Script` = '" + txtScript.Text.ToSqlValidString() + "', `SystemVersion` = '" + txtSystemVersion.Text.ToSqlValidString() + "', `RequireBackup` = " + (chkBackup.Checked ? "1" : "0") + ", `RequireAppRestart` = " + (chkRestartApp.Checked ? "1" : "0") + ", `RequirePcRestart` = " + (chkRestartPc.Checked ? "1" : "0") + ", `Description` = '" + txtDescription.Text.ToSqlValidString() + "'\n" + "WHERE\n" + "(`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString() + "');"; DataRow[] _existing = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'"); if (_existing.Length > 0) { _existing[0]["Title"] = txtTitle.Text; _existing[0]["Author"] = txtAuthor.Text; _existing[0]["Script"] = txtScript.Text; _existing[0]["SystemVersion"] = txtSystemVersion.Text; _existing[0]["RequireBackup"] = (chkBackup.Checked? 1 : 0); _existing[0]["RequireAppRestart"] = (chkRestartApp.Checked ? 1 : 0); _existing[0]["RequirePcRestart"] = (chkRestartPc.Checked? 1 : 0); _existing[0]["Description"] = txtDescription.Text; } } if (!string.IsNullOrEmpty(_query.RLTrim())) { btnSave.Enabled = false; btnSaveAndClose.Enabled = false; IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } else { QueResult _queresult = Que.EndExecution(_result); if (string.IsNullOrEmpty(_queresult.Error.RLTrim())) { UserAction _action = UserAction.Add; if (!_isnew) { _action = UserAction.Edit; } string _log = "Added a database script : " + _refno + "."; if (!_isnew) { _log = "Updated database script : " + _referenceno + "."; } _scripts.AcceptChanges(); if (_isnew) { _referenceno = _refno; _isnew = false; btnExport.Enabled = true; btnExport.Show(); btnExport.BringToFront(); btnExecute.Enabled = true; btnExecute.Show(); btnExecute.BringToFront(); } if (_updated) { _updated = false; } if (!_withupdates) { _withupdates = true; } Text = Text.Replace(" *", "").Replace("*", ""); Cursor = Cursors.WaitCursor; IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log, _referenceno); _logresult.WaitToFinish(); Cursor = Cursors.Default; if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } } else { if (_queresult.Error.Contains("duplicate")) { btnSave_Click(sender, new EventArgs()); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current database script.", "Save Database Script"); } _scripts.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } else { if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.None; Close(); } } }
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 (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 btnDelete_Click(object sender, EventArgs e) { if (!btnDelete.Enabled) { return; } if (!grdStockAdjustments.Redraw) { return; } if (grdStockAdjustments.DataSource == null) { return; } if (grdStockAdjustments.RowSel < grdStockAdjustments.Rows.Fixed) { return; } if (Materia.IsNullOrNothing(grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"])) { return; } string _referenceno = grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"].ToString(); DataTable _stockadjustments = Cache.GetCachedTable("stockadjustments"); if (_stockadjustments != null) { DataRow[] _rows = _stockadjustments.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'"); if (_rows.Length > 0) { DataRow _row = _rows[0]; if (VisualBasic.IsNumeric(_row["Closed"])) { if (VisualBasic.CBool(_row["Closed"])) { MsgBoxEx.Shout("Cannot delete stock adjustment : <font color=\"blue\">" + _referenceno + "</font> because it is already marked as final.", "Delete Stock Adjustment"); return; } } if (MsgBoxEx.Ask("Delete stock adjustment <font color=\"blue\">" + _referenceno + "</font> permanently from the list?", "Delete Stock Adjustments") != System.Windows.Forms.DialogResult.Yes) { return; } string _query = "DELETE FROM `stockadjustments` WHERE (`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString(true) + "')"; IAsyncResult _execresult = Que.BeginExecution(SCMS.Connection, _query); btnNew.Enabled = false; btnEdit.Enabled = false; btnDelete.Enabled = false; btnRefresh.Enabled = false; txtSearch.Enabled = false; while (!_execresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_execresult.IsCompleted) { try { _execresult = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } else { QueResult _result = Que.EndExecution(_execresult); if (string.IsNullOrEmpty(_result.Error.RLTrim())) { _row.Delete(); _stockadjustments.AcceptChanges(); if (grdStockAdjustments.Redraw) { grdStockAdjustments.BeginUpdate(); } DataTable _datasource = null; try { _datasource = (DataTable)grdStockAdjustments.DataSource; } catch { } if (_datasource != null) { DataRow[] _currows = _datasource.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'"); if (_currows.Length > 0) { _currows[0].Delete(); } _datasource.AcceptChanges(); } FormatGrid(); ResizeGrid(); Cursor = Cursors.WaitCursor; IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Deletes stock adjustment : " + _referenceno + ".", _referenceno); _logresult.WaitToFinish(); Cursor = Cursors.Default; while (!grdStockAdjustments.Redraw) { grdStockAdjustments.EndUpdate(); } } else { SCMS.LogError(this.GetType().Name, new Exception(_result.Error)); MsgBoxEx.Alert("Failed to delete the specified stock adjustment.", "Delete Stock Adjustment"); } _result.Dispose(); EnableButtons(); DisplayInfo(); } } } }
private void btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtAddress, !string.IsNullOrEmpty(txtAddress.Text.RLTrim()), "Please specify company address.")) { tbctrl.SelectedTab = tbCompany; return; } if (!Materia.Valid(_validator, cboCountry, cboCountry.SelectedIndex >= 0, "Please specify a valid country.")) { tbctrl.SelectedTab = tbCompany; return; } if (!Materia.Valid(_validator, cboCashAdvance, cboCashAdvance.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (!Materia.Valid(_validator, cboUnallocatedPayments, cboUnallocatedPayments.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (!Materia.Valid(_validator, cboRawMaterials, cboRawMaterials.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (!Materia.Valid(_validator, cboStockConsumption, cboStockConsumption.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (!Materia.Valid(_validator, cboStockAdjustment, cboStockAdjustment.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (!Materia.Valid(_validator, cboRollForward, cboRollForward.SelectedIndex >= 0, "Please specify a valid account.")) { tbctrl.SelectedTab = tbAccounts; return; } if (chkAutoBackup.Checked) { if (!Materia.Valid(_validator, lblPath, !string.IsNullOrEmpty(lblPath.Text.RLTrim()), "Please specify backup output destination.")) { tbctrl.SelectedTab = tbWorkstation; return; } if (!Materia.Valid(_validator, lblPath, Directory.Exists(lblPath.Text), "Please specify backup output destination.")) { tbctrl.SelectedTab = tbWorkstation; return; } if (dtpBackUpTime2.LockUpdateChecked) { DateTime _date1 = VisualBasic.CDate(DateTime.Now.ToShortDateString() + " " + VisualBasic.Format(dtpBackUpTime1.Value, "hh:mm tt")); DateTime _date2 = VisualBasic.CDate(DateTime.Now.ToShortDateString() + " " + VisualBasic.Format(dtpBackUpTime2.Value, "hh:mm tt")); if (!Materia.Valid(_validator, dtpBackUpTime2, _date2 >= _date1, "Please specify a time equal or higher than the first instance.")) { tbctrl.SelectedTab = tbWorkstation; return; } } } DataTable _settings = Cache.GetCachedTable("settings"); if (_settings != null) { DataRow[] _rows = _settings.Select("[Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "'"); if (_rows.Length > 0) { DataRow _row = _rows[0]; _row["Address"] = txtAddress.Text; _row["Country"] = cboCountry.SelectedValue.ToString(); _row["Phone"] = txtPhone.Text; _row["Mobile"] = txtMobile.Text; _row["Fax"] = txtFax.Text; _row["Email"] = txtEmail.Text; try { _row["CompanyLogo"] = pctCompanyLogo.Image.ToByteArray(); } catch { } try { _row["ReportLogo"] = pctReportLogo.Image.ToByteArray(); } catch { } _row["CashAdvanceAccountCode"] = cboCashAdvance.SelectedValue; _row["RawMaterialAccountCode"] = cboRawMaterials.SelectedValue; _row["StockConsumptionAccountCode"] = cboStockConsumption.SelectedValue; _row["StockAdjustmentAccountCode"] = cboStockAdjustment.SelectedValue; _row["UnallocatedPaymentAccountCode"] = cboUnallocatedPayments.SelectedValue; _row["RollForwardAccountCode"] = cboRollForward.SelectedValue; QueryGenerator _generator = new QueryGenerator(_settings); string _query = _generator.ToString(); _generator = null; Materia.RefreshAndManageCurrentProcess(); if (string.IsNullOrEmpty(_query.RLTrim())) { GlobalSettings.AutomaticBackupEnabled = chkAutoBackup.Checked; if (chkAutoBackup.Checked) { GlobalSettings.AutomaticBackupEnabled2 = dtpBackUpTime2.LockUpdateChecked; } else { GlobalSettings.AutomaticBackupEnabled2 = false; } GlobalSettings.AutomaticBackupPath = lblPath.Text; GlobalSettings.AutomaticBackupTime1 = dtpBackUpTime1.Value; if (chkAutoBackup.Checked && dtpBackUpTime2.LockUpdateChecked) { GlobalSettings.AutomaticBackupTime2 = dtpBackUpTime2.Value; } if (txtIdleTime.LockUpdateChecked) { GlobalSettings.AutomaticLockTime = txtIdleTime.Value; } else { GlobalSettings.AutomaticLockTime = 0; } IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Edit, "Updated the application settings."); while (!_logresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_logresult.IsCompleted) { try { _logresult = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } } DialogResult = System.Windows.Forms.DialogResult.OK; Close(); return; } btnSave.Enabled = false; IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { _settings.RejectChanges(); if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } } else { QueResult _queresult = Que.EndExecution(_result); if (string.IsNullOrEmpty(_queresult.Error.RLTrim())) { _settings.AcceptChanges(); Cache.Save(); _updated = false; GlobalSettings.AutomaticBackupEnabled = chkAutoBackup.Checked; if (chkAutoBackup.Checked) { GlobalSettings.AutomaticBackupEnabled2 = dtpBackUpTime2.LockUpdateChecked; } else { GlobalSettings.AutomaticBackupEnabled2 = false; } GlobalSettings.AutomaticBackupPath = lblPath.Text; GlobalSettings.AutomaticBackupTime1 = dtpBackUpTime1.Value; if (chkAutoBackup.Checked && dtpBackUpTime2.LockUpdateChecked) { GlobalSettings.AutomaticBackupTime2 = dtpBackUpTime2.Value; } if (txtIdleTime.LockUpdateChecked) { GlobalSettings.AutomaticLockTime = txtIdleTime.Value; } else { GlobalSettings.AutomaticLockTime = 0; } IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Edit, "Updated the application settings."); while (!_logresult.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_logresult.IsCompleted) { try { _logresult = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } } else { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } } else { _settings.RejectChanges(); SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save application settings.", "Save Settings"); btnSave.Enabled = true; } } } } }
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 btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtBrand, !string.IsNullOrEmpty(txtBrand.Text.RLTrim()), "Please specify vehicle make name.")) { return; } DataTable _brands = Cache.GetCachedTable("brands"); if (_brands != null) { DataRow[] _rows = _brands.Select("([Brand] LIKE '" + txtBrand.Text.ToSqlValidString(true) + "') AND\n" + "NOT ([Brand] LIKE '" + _brand.ToSqlValidString(true) + "')"); if (!Materia.Valid(_validator, txtBrand, _rows.Length <= 0, "Brand already exists.")) { return; } string _query = ""; DataColumnCollection _cols = _brands.Columns; if (_isnew) { _query = "INSERT INTO `brands`\n" + "(`Brand`, `DateCreated`)\n" + "VALUES\n" + "('" + txtBrand.Text.ToSqlValidString() + "', NOW());"; object[] _values = new object[_cols.Count]; _values[_cols["Brand"].Ordinal] = txtBrand.Text; _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _brands.Rows.Add(_values); } else { _query = "UPDATE `brands` SET\n" + "`Brand` = '" + txtBrand.Text.ToSqlValidString() + "'\n" + "WHERE\n" + "(`Brand` LIKE '" + _brand.ToSqlValidString() + "');"; DataRow[] _existing = _brands.Select("[Brand] LIKE '" + _brand.ToSqlValidString(true) + "'"); if (_existing.Length > 0) { _existing[0]["Brand"] = txtBrand.Text; } } if (!string.IsNullOrEmpty(_query.RLTrim())) { btnSave.Enabled = false; btnSaveAndClose.Enabled = false; if (txtBrand.Text == _brand) { if (_isnew) { _isnew = false; } if (_updated) { _updated = false; } if (_withupdates) { _withupdates = false; } Text = Text.Replace(" *", "").Replace("*", ""); if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } return; } IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } else { QueResult _queresult = Que.EndExecution(_result); if (string.IsNullOrEmpty(_queresult.Error.RLTrim())) { UserAction _action = UserAction.Add; if (!_isnew) { _action = UserAction.Edit; } string _log = "Added a new brand : " + txtBrand.Text + "."; if (!_isnew) { _log = "Updated brand : " + _brand + (_brand != txtBrand.Text ? " to " + txtBrand.Text : "").ToString() + "."; } _brands.AcceptChanges(); _brand = txtBrand.Text; if (_isnew) { _isnew = false; } if (_updated) { _updated = false; } if (!_withupdates) { _withupdates = true; } Text = Text.Replace(" *", "").Replace("*", ""); Cursor = Cursors.WaitCursor; IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log); _logresult.WaitToFinish(); Cursor = Cursors.Default; if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } } else { if (_queresult.Error.Contains("duplicate")) { bool _invalid = Materia.Valid(_validator, txtBrand, false, "Brand already exists."); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current brand.", "Save Brand"); } _brands.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } else { if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.None; Close(); } } }
private void 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(); } }
private void btnSave_Click(object sender, EventArgs e) { if (!btnSave.Enabled) { return; } Validator _validator = SCMS.Validators[this]; if (!Materia.Valid(_validator, txtValue, txtValue.Value > 0, "Please specify currency denomination value.")) { return; } if (!Materia.Valid(_validator, cboCurrency, cboCurrency.SelectedIndex >= 0, "Please specify a valid currency.")) { return; } DataTable _denominations = Cache.GetCachedTable("currencydenominations"); DataRow _newrow = null; if (_denominations != null) { DataRow[] _rows = _denominations.Select("([Denomination] = " + txtValue.Value.ToSqlValidString() + " AND\n" + " [Currency] LIKE '" + cboCurrency.SelectedValue.ToString().ToSqlValidString(true) + "') AND\n" + "([DetailId] <> " + _id.ToString() + ")"); if (!Materia.Valid(_validator, txtValue, _rows.Length <= 0, "Currency denomination already exists.")) { return; } string _query = ""; DataColumnCollection _cols = _denominations.Columns; if (_isnew) { _query = "INSERT INTO `currencydenominations`\n" + "(`Currency`, `Denomination`, `Active`, `DateCreated`)\n" + "VALUES\n" + "('" + cboCurrency.SelectedValue.ToString().ToSqlValidString(true) + "', " + txtValue.Value.ToSqlValidString() + ", " + (chkActive.Checked? "1" : "0").ToString() + ", NOW());\n" + "SELECT LAST_INSERT_ID() AS `Id`;"; object[] _values = new object[_cols.Count]; _values[_cols["Currency"].Ordinal] = cboCurrency.SelectedValue; _values[_cols["Denomination"].Ordinal] = txtValue.Value; _values[_cols["Active"].Ordinal] = (chkActive.Checked ? 1 : 0); _values[_cols["DateCreated"].Ordinal] = DateTime.Now; _values[_cols["LastModified"].Ordinal] = DateTime.Now; _newrow = _denominations.Rows.Add(_values); } else { _query = "UPDATE `currencydenominations` SET\n" + "`Currency` = '" + cboCurrency.SelectedValue.ToString().ToSqlValidString() + "', `Denomination` = " + txtValue.Value.ToSqlValidString() + ", `Active` = " + (chkActive.Checked? "1" : "0").ToString() + "\n" + "WHERE\n" + "(`DetailId` = " + _id.ToString() + ");"; DataRow[] _existing = _denominations.Select("[DetailId] = " + _id.ToString()); if (_existing.Length > 0) { _existing[0]["Currency"] = cboCurrency.SelectedValue; _existing[0]["Denomination"] = txtValue.Value; _existing[0]["Active"] = (chkActive.Checked? 1 : 0); } } if (!string.IsNullOrEmpty(_query.RLTrim())) { btnSave.Enabled = false; btnSaveAndClose.Enabled = false; IAsyncResult _result = Que.BeginExecution(SCMS.Connection, _query); while (!_result.IsCompleted && !_cancelled) { Thread.Sleep(1); Application.DoEvents(); } if (_cancelled) { if (!_result.IsCompleted) { try { _result = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } return; } else { QueResult _queresult = Que.EndExecution(_result); if (string.IsNullOrEmpty(_queresult.Error.RLTrim())) { UserAction _action = UserAction.Add; if (!_isnew) { _action = UserAction.Edit; } string _log = "Added a new currency denomination : " + txtValue.Value.ToSqlValidString() + " " + cboCurrency.SelectedValue.ToString() + "."; if (!_isnew) { _log = "Updated currency denomination : " + txtValue.Value.ToSqlValidString() + " " + cboCurrency.SelectedValue.ToString() + "."; } if (_isnew) { if (_queresult.ResultSet.Tables.Count > 0) { DataTable _table = _queresult.ResultSet.Tables[0]; if (_table.Rows.Count > 0) { DataRow _row = _table.Rows[0]; if (VisualBasic.IsNumeric(_row["Id"])) { _id = VisualBasic.CLng(_row["Id"]); if (_newrow != null) { _newrow["DetailId"] = _id; } } } } } _denominations.AcceptChanges(); if (_isnew) { _isnew = false; } if (_updated) { _updated = false; } if (!_withupdates) { _withupdates = true; } Text = Text.Replace(" *", "").Replace("*", ""); Cursor = Cursors.WaitCursor; IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(_action, _log); _logresult.WaitToFinish(); Cursor = Cursors.Default; if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.OK; Close(); } } else { if (_queresult.Error.Contains("duplicate")) { bool _invalid = Materia.Valid(_validator, txtValue, false, "Currency denomination already exists."); } else { SCMS.LogError(this.GetType().Name, new Exception(_queresult.Error)); MsgBoxEx.Alert("Failed to save the current currency denomination.", "Save Currency Denomination"); } _denominations.RejectChanges(); } _queresult.Dispose(); } btnSave.Enabled = true; btnSaveAndClose.Enabled = true; } } else { if (sender == btnSaveAndClose) { DialogResult = System.Windows.Forms.DialogResult.None; Close(); } } }
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(); } }