private void CurrencyInfoDialog_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; this.ManageOnDispose(); SCMS.Validators.Add(this); AttachEditorHandler(); cboAccount.LoadAccounts(); cboExchangeRateDiff.LoadAccounts(); txtCurrency.ReadOnly = (_currency.ToUpper() == "USD"); string _path = Application.StartupPath + "\\Xml\\defaultaccounts.xml"; DataTable _defaultaccounts = SCMS.XmlToTable(_path); if (_defaultaccounts != null) { if (cboAccount.DataSource != null) { long _cashathand = 54005; DataRow[] _rows = _defaultaccounts.Select("[AccountName] LIKE 'Cash at hand'"); if (_rows.Length > 0) { _cashathand = VisualBasic.CLng(_rows[0]["AccountCode"]); } try { cboAccount.SelectedValue = _cashathand; } catch { } } if (cboExchangeRateDiff.DataSource != null) { long _exratediff = 34625; DataRow[] _rows = _defaultaccounts.Select("[AccountName] LIKE 'Exchange rate differences'"); if (_rows.Length > 0) { _exratediff = VisualBasic.CLng(_rows[0]["AccountCode"]); } try { cboExchangeRateDiff.SelectedValue = _exratediff; } catch { } } _defaultaccounts.Dispose(); _defaultaccounts = null; Materia.RefreshAndManageCurrentProcess(); } txtCurrency.SetAsRequired(); cboAccount.SetAsRequired(); cboExchangeRateDiff.SetAsRequired(); if (!_isnew) { InitializeInfo(); } }
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 UploadFile(int index) { _currentuploadsize = 0; FireEventFromWorker(UploadTransitions.FileUploadAttempting); UploadFileInfo _file = Uploads[index]; double _size = 0; byte[] _readbytes = new byte[PacketSize]; int _currentpackagesize = 0; FileInfo _fileinfo = new FileInfo(_file.Path); FileStream _filestream = null; Stopwatch _speedtimer = new Stopwatch(); Stream _stream = null; Int32 _readings = 0; Exception _ex = null; int _packet = PacketSize; try { _size = _fileinfo.Length; } catch { } FtpWebRequest _request = null; FtpWebResponse _response = null; try { string _ftpaddress = Path.GetDirectoryName(Address).ToLower().Replace("ftp:\\", "ftp://").Replace("\\", "/") + "/" + Path.GetFileName(_file.Path); _request = (FtpWebRequest)WebRequest.Create(_ftpaddress); if (_credential != null) { _request.Credentials = _credential; } _request.KeepAlive = true; _request.UseBinary = true; _request.Method = WebRequestMethods.Ftp.UploadFile; _filestream = new FileStream(_file.Path, FileMode.Open); _request.ContentLength = VisualBasic.CLng(_size); _stream = _request.GetRequestStream(); } catch (Exception ex) { _ex = ex; } _currentuploadsize = _size; FireEventFromWorker(UploadTransitions.FileUploadStarted); if (_ex != null) { _uploaderworker.ReportProgress((int)UploadInvokations.FileUploadFailedRaiser, _ex); } else { _currentlyuploaded = 0; _currentpackagesize = 0; do { if (_uploaderworker.CancellationPending) { _filestream.Close(); _stream.Close(); _speedtimer.Stop(); if (_response != null) { _response.Close(); } return; } _trigger.WaitOne(); _speedtimer.Start(); if (_stream == null && _response != null) { _stream = _response.GetResponseStream(); } if (_readbytes.Length < PacketSize) { _packet = _readbytes.Length; } else { _packet = PacketSize; } _currentpackagesize = _filestream.Read(_readbytes, 0, _packet); _currentlyuploaded += _currentpackagesize; _totaluploaded += _currentpackagesize; FireEventFromWorker(UploadTransitions.ProgressChanged); _stream.Write(_readbytes, 0, _currentpackagesize); _readings += 1; if (_readings >= StopWatchCycle) { _uploadspeed = VisualBasic.CInt(_packet * StopWatchCycle * 1000 / (_speedtimer.ElapsedMilliseconds + 1)); _speedtimer.Reset(); _readings = 0; } } while (_currentpackagesize != 0); _stream.Close(); _filestream.Close(); _speedtimer.Stop(); FireEventFromWorker(UploadTransitions.FileUploadSucceeded); } FireEventFromWorker(UploadTransitions.FileUploadStopped); }
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 InitializeRestorePoints() { if (grdRestorePoints.Redraw) { grdRestorePoints.BeginUpdate(); } if (grdRestorePoints.DataSource != null) { try { grdRestorePoints.DataSource = null; } catch { } finally { Materia.RefreshAndManageCurrentProcess(); } } string _path = Application.StartupPath + "\\Xml\\restorepoints.xml"; DataTable _table = SCMS.XmlToTable(_path); if (_table != null) { DataTable _datasource = new DataTable(); DataColumn _pkcol = _datasource.Columns.Add("Id", typeof(int)); _pkcol.AutoIncrement = true; _pkcol.AutoIncrementSeed = 1; _pkcol.AutoIncrementStep = 1; _datasource.Columns.Add("Select", typeof(bool)); _datasource.Columns.Add("As Of", typeof(DateTime)); _datasource.Columns.Add("Info", typeof(RestorePointInfo)); DataRow[] _rows = _table.Select("[Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "' AND\n" + "[Server] LIKE '" + SCMS.ServerConnection.Server.ToSqlValidString(true) + "' AND\n" + "[Database] LIKE '" + SCMS.ServerConnection.Database.ToSqlValidString(true) + "'"); for (int i = 0; i <= (_rows.Length - 1); i++) { DataRow _row = _rows[i]; RestorePointInfo _restorepoint = new RestorePointInfo(VisualBasic.CLng(_row["DetailId"])); if (!String.IsNullOrEmpty(_restorepoint.Filename.RLTrim())) { if (File.Exists(_restorepoint.Filename)) { DataColumnCollection _cols = _datasource.Columns; object[] _values = new object[_cols.Count]; _values[_cols["Select"].Ordinal] = VisualBasic.CBool(i == 0); _values[_cols["As Of"].Ordinal] = _row["DateAndTime"]; _values[_cols["Info"].Ordinal] = _restorepoint; _datasource.Rows.Add(_values); } } } grdRestorePoints.DataSource = _datasource; grdRestorePoints.Rows[grdRestorePoints.Rows.Fixed - 1].Visible = false; grdRestorePoints.Cols["Id"].Visible = false; grdRestorePoints.Cols["Select"].Caption = ""; grdRestorePoints.Cols["As Of"].Format = "dd-MMM-yyyy hh:mm:ss tt"; grdRestorePoints.Cols["Info"].Visible = false; grdRestorePoints.AutoNumber(); grdRestorePoints.AutoSizeCols(); grdRestorePoints.ExtendLastCol = true; } else { grdRestorePoints.InitializeAppearance(); } while (!grdRestorePoints.Redraw) { grdRestorePoints.EndUpdate(); } }
private 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); }