/// <summary>
        /// Gets the actual sql execution result from an initialized BeginSave method call.
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public QueResult EndSave(IAsyncResult result)
        {
            QueResult _result = null;

            if (result != null)
            {
                if (_delegatetable.ContainsKey(result))
                {
                    Func <QueResult> _delegate = (Func <QueResult>)_delegatetable[result];
                    _result = _delegate.EndInvoke(result);
                    _delegatetable.Remove(result);
                }
            }

            return(_result);
        }
Ejemplo n.º 2
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

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

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

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

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

                if (_isnew)
                {
                    Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber);
                    IAsyncResult _result = _delegate.BeginInvoke("locations", true, null, _delegate);

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

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

                        return;
                    }

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

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

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

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

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

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

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

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

                        return;
                    }

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

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

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

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

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

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

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

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

                            Cursor = Cursors.Default;

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

                            _locations.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
Ejemplo n.º 3
0
        private void CreateInitialCurrencies(IDbConnection connection)
        {
            string    _path = Application.StartupPath + "\\Xml\\defaultcurrencies.xml";
            DataTable _defaultcurrencies = SCMS.XmlToTable(_path);

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

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

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

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

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

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

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

                _defaultcurrencies.Dispose(); _defaultcurrencies = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Retrieves the specified company's application settings and cofigurations.
        /// </summary>
        /// <param name="companycode"></param>
        public static void Refresh(string companycode)
        {
            ClearInformation(); _company = new CompanyInfo(companycode);
            Cache.SyncTable(SCMS.Connection, "settings");
            DataTable _settings = Cache.GetCachedTable("settings");

            if (_settings != null)
            {
                DataRow[] _rows = _settings.Select("[Company] LIKE '" + companycode.ToSqlValidString(true) + "'");

                if (_rows.Length <= 0)
                {
                    object[]             _values = new object[_settings.Columns.Count];
                    DataColumnCollection _cols   = _settings.Columns;

                    _values[_cols["Company"].Ordinal]     = companycode;
                    _values[_cols["Address"].Ordinal]     = "";
                    _values[_cols["Country"].Ordinal]     = "";
                    _values[_cols["Phone"].Ordinal]       = "";
                    _values[_cols["Mobile"].Ordinal]      = "";
                    _values[_cols["Fax"].Ordinal]         = "";
                    _values[_cols["Email"].Ordinal]       = "";
                    _values[_cols["CompanyLogo"].Ordinal] = Properties.Resources.CSPTColored.ToByteArray();
                    _values[_cols["ReportLogo"].Ordinal]  = Properties.Resources.CSPTBlackAndWhite.ToByteArray();

                    Cache.SyncTable(SCMS.Connection, "accounts");
                    DataTable _accounts = Cache.GetCachedTable("accounts");
                    if (_accounts != null)
                    {
                        long      _accountcode = 0; string _accountname = "Raw materials & consumables - spare parts";
                        DataRow[] _selrows = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["RawMaterialAccountCode"].Ordinal] = _accountcode;
                        }

                        _accountname = "Cash advances";
                        _selrows     = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["CashAdvanceAccountCode"].Ordinal] = _accountcode;
                        }

                        _accountname = "Parts consumption";
                        _selrows     = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["StockConsumptionAccountCode"].Ordinal] = _accountcode;
                        }

                        _accountname = "Stock adjustments";
                        _selrows     = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["StockAdjustmentAccountCode"].Ordinal] = _accountcode;
                        }

                        _accountname = "Unallocated payments / cheques";
                        _selrows     = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["UnallocatedPaymentAccountCode"].Ordinal] = _accountcode;
                        }

                        _accountname = "Result carried forward previous years";
                        _selrows     = _accounts.Select("[AccountName] LIKE '" + _accountname.ToSqlValidString(true) + "'");
                        if (_selrows.Length > 0)
                        {
                            _accountcode = (long)_selrows[0]["AccountCode"];
                            _values[_cols["RollForwardAccountCode"].Ordinal] = _accountcode;
                        }
                    }

                    _values[_cols["DateCreated"].Ordinal] = DateTime.Now;
                    _settings.Rows.Add(_values);

                    QueryGenerator _generator = new QueryGenerator(_settings);
                    _generator.ExcludedFields.Add("LastModified");
                    string _query = _generator.ToString();

                    if (!String.IsNullOrEmpty(_query.RLTrim()))
                    {
                        QueResult _result = Que.Execute(SCMS.Connection, _query);
                        if (String.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            _settings.AcceptChanges();
                        }
                        _result.Dispose(); _result = null; Materia.RefreshAndManageCurrentProcess();
                    }
                }

                _rows = _settings.Select("[Company] LIKE '" + companycode.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    DataRow _row = _rows[0];
                    if (!Materia.IsNullOrNothing(_row["Address"]))
                    {
                        _address = _row["Address"].ToString();
                    }
                    if (VisualBasic.IsNumeric(_row["CashAdvanceAccountCode"]))
                    {
                        _cashadvanceaccountcode = (long)_row["CashAdvanceAccountCode"];
                    }
                    if (!Materia.IsNullOrNothing(_row["CompanyLogo"]))
                    {
                        try { _companylogo = ((byte[])_row["CompanyLogo"]).ToImage(); }
                        catch { }
                    }
                    if (!Materia.IsNullOrNothing(_row["Country"]))
                    {
                        _country = _row["Country"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Email"]))
                    {
                        _email = _row["Email"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Fax"]))
                    {
                        _fax = _row["Fax"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Mobile"]))
                    {
                        _mobile = _row["Mobile"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Phone"]))
                    {
                        _phone = _row["Phone"].ToString();
                    }
                    if (VisualBasic.IsNumeric(_row["RawMaterialAccountCode"]))
                    {
                        _rawmaterialaccountcode = (long)_row["RawMaterialAccountCode"];
                    }
                    if (!Materia.IsNullOrNothing(_row["ReportLogo"]))
                    {
                        try { _reportlogo = ((byte[])_row["ReportLogo"]).ToImage(); }
                        catch { }
                    }
                    if (VisualBasic.IsNumeric(_row["RollForwardAccountCode"]))
                    {
                        _rollforwardaccountcode = (long)_row["RollForwardAccountCode"];
                    }
                    if (VisualBasic.IsNumeric(_row["StockAdjustmentAccountCode"]))
                    {
                        _stockadjustmentaccountcode = (long)_row["StockAdjustmentAccountCode"];
                    }
                    if (VisualBasic.IsNumeric(_row["StockConsumptionAccountCode"]))
                    {
                        _stockconsumptionaccountcode = (long)_row["StockConsumptionAccountCode"];
                    }
                    if (VisualBasic.IsNumeric(_row["UnallocatedPaymentAccountCode"]))
                    {
                        _unallocatedpaymentaccountcode = (long)_row["UnallocatedPaymentAccountCode"];
                    }
                }
            }
        }
Ejemplo n.º 5
0
        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();
        }
Ejemplo n.º 6
0
        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();
            }
        }
Ejemplo n.º 7
0
        private void CreateInitialUser(IDbConnection connection)
        {
            string    _path  = Application.StartupPath + "\\Xml\\defaultusers.xml";
            DataTable _table = SCMS.XmlToTable(_path);

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

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

                        string _query = "";  _exists = false;

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

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

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

                            _depttable.Rows.Add(_values);
                        }

                        _exists = false;

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

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

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

                            _postntable.Rows.Add(_values);
                        }

                        StringBuilder _privileges = new StringBuilder();

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

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

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

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

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

                _table.Dispose(); _table = null;
                Materia.RefreshAndManageCurrentProcess();
            }
        }
Ejemplo n.º 8
0
        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();
                }
            }
        }
Ejemplo n.º 9
0
        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();
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Executes the specified sql commandtext using MySql application itself.
        /// </summary>
        /// <param name="connectionstring">MySql database connection string</param>
        /// <param name="sql">Sql command statements</param>
        /// <param name="parameters">Additional MySql parameters</param>
        /// <returns></returns>
        public static MySqlResult Execute(string connectionstring, string sql, MySqlParameterCollection parameters)
        {
            MySqlResult _result = null; ExtractResourceApplications();

            if (File.Exists(Application.StartupPath + "\\mysql.exe"))
            {
                string   _filename = Application.StartupPath + "\\tempsql.sql";
                FileInfo _file     = Materia.WriteToFile(_filename, sql);

                if (_file != null)
                {
                    string _batfilepath = Application.StartupPath + "\\execsql.bat";
                    string _server      = connectionstring.ConnectionStringValue(ConnectionStringSection.Server);
                    string _database    = connectionstring.ConnectionStringValue(ConnectionStringSection.Database);
                    string _uid         = connectionstring.ConnectionStringValue(ConnectionStringSection.UID);
                    string _pwd         = connectionstring.ConnectionStringValue(ConnectionStringSection.PWD);
                    string _parameters  = "";

                    if (parameters != null)
                    {
                        foreach (string _parameter in parameters)
                        {
                            if (!String.IsNullOrEmpty(_parameter.RLTrim()))
                            {
                                _parameters += (String.IsNullOrEmpty(_parameters.RLTrim()) ? "" : " ") + _parameter;
                            }
                        }
                    }

                    string   _contents = "\"" + Application.StartupPath + "\\mysql\" -h " + _server + " -u " + _uid + " -p" + _pwd + " " + _database + (String.IsNullOrEmpty(_parameters.RLTrim()) ? "" : " ") + _parameters + " --max_allowed_packet=" + MaxAllowedPacket + "M --default-character-set=utf8 < \"" + _filename.RLTrim().Replace("\\", "/") + "\"";
                    FileInfo _batfile  = Materia.WriteToFile(_batfilepath, _contents);

                    if (_batfile != null)
                    {
                        string _error = ""; Process _process = new Process();

                        IDbConnection _connection = Database.CreateConnection(connectionstring);
                        QueResult     _qresult    = Que.Execute(_connection, "SET GLOBAL max_allowed_packet=(1024 * 1024) * " + MaxAllowedPacket.ToString() + ";");
                        _qresult.Dispose(QueResultDisposition.WithAssociatedQue);

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

                        _process.StartInfo.FileName              = _batfilepath;
                        _process.StartInfo.CreateNoWindow        = true; _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        _process.StartInfo.RedirectStandardError = true; _process.StartInfo.UseShellExecute = false;
                        _process.Start();

                        while (!_process.HasExited)
                        {
                            Application.DoEvents();
                        }

                        if (_process.StandardError != null)
                        {
                            try { _error = _process.StandardError.ReadToEnd().Replace("The handle is invalid.\n", "").Replace("The handle is invalid.", "").RLTrim(); }
                            catch { _error = ""; }
                        }
                        else
                        {
                            _error = "";
                        }

                        _process.Dispose(); Materia.RefreshAndManageCurrentProcess();
                        RemoveResourceApplications(); _result = new MySqlResult(_filename, _error, sql);

                        int _counter = 0;

                        while (_counter < 30 &&
                               File.Exists(_batfilepath))
                        {
                            try { File.Delete(_batfilepath); }
                            catch { }
                            Materia.RefreshAndManageCurrentProcess();
                            Thread.Sleep(100); Application.DoEvents();
                            _counter += 1;
                        }

                        _counter = 0;

                        while (_counter < 30 &&
                               File.Exists(_filename))
                        {
                            try { File.Delete(_filename); }
                            catch { }
                            Materia.RefreshAndManageCurrentProcess();
                            Thread.Sleep(100); Application.DoEvents();
                            _counter += 1;
                        }
                    }
                    else
                    {
                        _result = new MySqlResult("", "Can't completely initialize database execution.");
                    }
                }
                else
                {
                    _result = new MySqlResult("", "Can't completely initialize sql statement.");
                }
            }
            else
            {
                _result = new MySqlResult("", "Can't extract MySql application resources into default directory : " + Application.StartupPath + ".");
            }

            return(_result);
        }
Ejemplo n.º 11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

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

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

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

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

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

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

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

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

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

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

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

                            Cursor = Cursors.WaitCursor;

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

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

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

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

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

                        _result.Dispose(); _result = null; Materia.RefreshAndManageCurrentProcess();
                        btnSave.Enabled            = true; btnSaveAndClose.Enabled = true;
                    }
                }
                else
                {
                    if (_updated)
                    {
                        _updated = false;
                    }
                    Text = Text.Replace(" *", "").Replace("*", "");
                    if (sender == btnSaveAndClose)
                    {
                        DialogResult = System.Windows.Forms.DialogResult.OK; Close();
                    }
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
Ejemplo n.º 12
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!btnDelete.Enabled)
            {
                return;
            }
            if (!grdStockAdjustments.Redraw)
            {
                return;
            }
            if (grdStockAdjustments.DataSource == null)
            {
                return;
            }
            if (grdStockAdjustments.RowSel < grdStockAdjustments.Rows.Fixed)
            {
                return;
            }
            if (Materia.IsNullOrNothing(grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"]))
            {
                return;
            }

            string    _referenceno      = grdStockAdjustments[grdStockAdjustments.RowSel, "ReferenceNo"].ToString();
            DataTable _stockadjustments = Cache.GetCachedTable("stockadjustments");

            if (_stockadjustments != null)
            {
                DataRow[] _rows = _stockadjustments.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    DataRow _row = _rows[0];
                    if (VisualBasic.IsNumeric(_row["Closed"]))
                    {
                        if (VisualBasic.CBool(_row["Closed"]))
                        {
                            MsgBoxEx.Shout("Cannot delete stock adjustment : <font color=\"blue\">" + _referenceno + "</font> because it is already marked as final.", "Delete Stock Adjustment");
                            return;
                        }
                    }

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

                    string       _query      = "DELETE FROM `stockadjustments` WHERE (`ReferenceNo` LIKE '" + _referenceno.ToSqlValidString(true) + "')";
                    IAsyncResult _execresult = Que.BeginExecution(SCMS.Connection, _query);

                    btnNew.Enabled     = false; btnEdit.Enabled = false; btnDelete.Enabled = false;
                    btnRefresh.Enabled = false; txtSearch.Enabled = false;

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

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

                        return;
                    }
                    else
                    {
                        QueResult _result = Que.EndExecution(_execresult);
                        if (string.IsNullOrEmpty(_result.Error.RLTrim()))
                        {
                            _row.Delete(); _stockadjustments.AcceptChanges();

                            if (grdStockAdjustments.Redraw)
                            {
                                grdStockAdjustments.BeginUpdate();
                            }

                            DataTable _datasource = null;

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

                            if (_datasource != null)
                            {
                                DataRow[] _currows = _datasource.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                                if (_currows.Length > 0)
                                {
                                    _currows[0].Delete();
                                }
                                _datasource.AcceptChanges();
                            }

                            FormatGrid(); ResizeGrid();

                            Cursor = Cursors.WaitCursor;
                            IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.Delete, "Deletes stock adjustment : " + _referenceno + ".", _referenceno);
                            _logresult.WaitToFinish(); Cursor = Cursors.Default;

                            while (!grdStockAdjustments.Redraw)
                            {
                                grdStockAdjustments.EndUpdate();
                            }
                        }
                        else
                        {
                            SCMS.LogError(this.GetType().Name, new Exception(_result.Error));
                            MsgBoxEx.Alert("Failed to delete the specified stock adjustment.", "Delete Stock Adjustment");
                        }

                        _result.Dispose(); EnableButtons(); DisplayInfo();
                    }
                }
            }
        }
Ejemplo n.º 13
0
        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;
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        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();
                    }
                }
            }
        }
Ejemplo n.º 15
0
        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;
        }
Ejemplo n.º 16
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

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

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

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

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

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

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

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

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

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

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

                        return;
                    }

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

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

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

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

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

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

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

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

                            Cursor = Cursors.Default;

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

                            _brands.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
Ejemplo n.º 17
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!btnSave.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this];

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

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

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

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

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

                if (_isnew)
                {
                    Func <string, bool, string> _delegate = new Func <string, bool, string>(SCMS.GetTableSeriesNumber);
                    IAsyncResult _result = _delegate.BeginInvoke("bankaccounts", true, null, _delegate);

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

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

                        return;
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

                            Cursor = Cursors.Default;

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

                            _bankaccounts.RejectChanges();
                        }

                        _queresult.Dispose();
                    }

                    btnSave.Enabled = true; btnSaveAndClose.Enabled = true;
                }
            }
            else
            {
                if (sender == btnSaveAndClose)
                {
                    DialogResult = System.Windows.Forms.DialogResult.None; Close();
                }
            }
        }
        private void 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();
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Executes the current database script.
        /// </summary>
        /// <returns></returns>
        public DatabaseScriptExecutionResult Execute()
        {
            DatabaseScriptExecutionResult _result = new DatabaseScriptExecutionResult(this);

            string _message = "You are about to execute a database script with the following information<br /><br />" +
                              "<b>Reference No.</b>  " + _referenceno + "<br />" +
                              "<b>System Version</b>  " + (_systemversion != Application.ProductVersion ? "<font color=\"red\">" : "") + _systemversion + (_systemversion != Application.ProductVersion ? "<\font>" : "") + "<br />" +
                              "<b>Author</b>  " + _author + "<br />" +
                              "<b>Date Created</b>  " + VisualBasic.Format(_datecreated, "dd-MMM-yyyy") + "<br />" +
                              "<b>Title</b>" + _title + "<br />" +
                              "<b>Description</b>  " + _description + "<br />" +
                              (_requiresapprestartafterexecution ||
                               _requiresbackupbeforeexecution ||
                               _requirespcrestartafterexecution ?
                               "<b>Transitions</b><br />" : "") +
                              (_requiresbackupbeforeexecution ? "  Perform database backup before execution<br />" : "") +
                              (_requiresapprestartafterexecution ? "  Restart application after execution<br />" : "") +
                              (_requirespcrestartafterexecution ? "  Restart workstation after execution<br />" : "") +
                              "<br />" +
                              "Press <font color=\"blue\">OK</font> to continue.";

            DialogResult _dialogresult = MsgBoxEx.Shout(_message, "Execute Database Script", MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button2);

            if (_dialogresult == DialogResult.OK)
            {
                if (_requiresbackupbeforeexecution)
                {
                    string _backupdir = GlobalSettings.AutomaticBackupPath;
                    if (string.IsNullOrEmpty(_backupdir.RLTrim()))
                    {
                        _backupdir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    }
                    else
                    {
                        if (!Directory.Exists(_backupdir))
                        {
                            _backupdir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        }
                    }

                    string _filename = _backupdir + "\\" + SCMS.ServerConnection.Database.ToUpper() + "_BACKUP_" + VisualBasic.Format(DateTime.Now, "dd_MM_yyyy_HH_mm_ss") + ".scmsiv";

                    DatabaseBackupDialog _dialog = new DatabaseBackupDialog(true);
                    _dialog.BackupPath = _filename;

                    DialogResult _backupresult = _dialog.ShowDialog();
                    _dialog.Dispose(); _dialog = null;
                    Materia.RefreshAndManageCurrentProcess();

                    if (_backupresult != DialogResult.OK)
                    {
                        return(_result);
                    }
                }

                InitializerDialog _loader = new InitializerDialog();
                _loader.Message = "Executing database script into " + SCMS.ServerConnection.Server + " / " + SCMS.ServerConnection.Database + "...";
                _loader.Show();  _result.Execute();

                if (_result.Executed)
                {
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.ExecuteScript, "Executed a database script" + (!string.IsNullOrEmpty(_filename.RLTrim()) ? " : " + _filename : "") + ".", _referenceno);
                    _logresult.WaitToFinish();

                    IAsyncResult _syncresult = Cache.SyncTableAsync(SCMS.Connection, "scripts");
                    _syncresult.WaitToFinish();

                    DataTable _scripts = Cache.GetCachedTable("scripts");
                    DataRow[] _rows    = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                    if (_rows.Length <= 0)
                    {
                        DataColumnCollection _cols   = _scripts.Columns;
                        object[]             _values = new object[_cols.Count];
                        _values[_cols["ReferenceNo"].Ordinal]       = _referenceno;
                        _values[_cols["Author"].Ordinal]            = _author;
                        _values[_cols["Title"].Ordinal]             = _title;
                        _values[_cols["ReferenceNo"].Ordinal]       = _referenceno;
                        _values[_cols["SystemVersion"].Ordinal]     = _systemversion;
                        _values[_cols["Description"].Ordinal]       = _description;
                        _values[_cols["Script"].Ordinal]            = _sqlstatement;
                        _values[_cols["DateCreated"].Ordinal]       = _datecreated;
                        _values[_cols["Executed"].Ordinal]          = 1;
                        _values[_cols["DateExecuted"].Ordinal]      = DateTime.Now;
                        _values[_cols["RequireBackup"].Ordinal]     = (_requiresbackupbeforeexecution ? 1 : 0);
                        _values[_cols["RequireAppRestart"].Ordinal] = (_requiresapprestartafterexecution ? 1 : 0);
                        _values[_cols["RequirePcRestart"].Ordinal]  = (_requiresapprestartafterexecution ? 1 : 0);
                        _scripts.Rows.Add(_values);
                    }
                    else
                    {
                        _rows[0]["Executed"]     = 1;
                        _rows[0]["DateExecuted"] = DateTime.Now;
                    }

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

                    if (!string.IsNullOrEmpty(_query.RLTrim()))
                    {
                        IAsyncResult _queresult = Que.BeginExecution(SCMS.Connection, _query);
                        _queresult.WaitToFinish();
                        QueResult _execresult = Que.EndExecution(_queresult);

                        if (!string.IsNullOrEmpty(_execresult.Error.RLTrim()))
                        {
                            _scripts.RejectChanges();
                        }
                        else
                        {
                            _scripts.AcceptChanges();
                        }

                        _execresult.Dispose();
                    }
                }

                _loader.Close(); _loader.Dispose(); _loader = null;
                Materia.RefreshAndManageCurrentProcess();

                if (_result.Executed)
                {
                    if (_requiresapprestartafterexecution)
                    {
                        FormCollection _forms   = Application.OpenForms;
                        int            _counter = _forms.Count;

                        for (int i = (_counter - 1); i >= 0; i--)
                        {
                            Form _form = _forms[i];
                            if (!(_form is MainWindow) &&
                                !(_form is LoginDialog))
                            {
                                if (_form.TopMost)
                                {
                                    try
                                    {
                                        _form.Close(); _form.Dispose();
                                        _counter = _forms.Count;
                                    }
                                    catch { }
                                    finally { Materia.RefreshAndManageCurrentProcess(); }
                                }
                            }
                        }

                        IAsyncResult _logoutresult = SCMS.CurrentSystemUser.LogOutAsync();
                        _logoutresult.WaitToFinish();

                        Form _mainform = null;
                        System.Collections.IEnumerator _enumerators = _forms.GetEnumerator();

                        while (_enumerators.MoveNext())
                        {
                            Form _form = (Form)_enumerators.Current;
                            if (_form is MainWindow)
                            {
                                _mainform = _form; break;
                            }
                        }

                        if (_mainform != null)
                        {
                            _mainform.Close();
                        }
                    }
                    else
                    {
                        if (_requirespcrestartafterexecution)
                        {
                            IAsyncResult _logoutresult = SCMS.CurrentSystemUser.LogOutAsync();
                            _logoutresult.WaitToFinish();

                            Process.Start("cmd", "/C shutdown -f -r -t 0");
                        }
                    }
                }
                else
                {
                    MsgBoxEx.Alert("Failed to either complete or fully execute the database script.", "Execute Database Script");
                }
            }

            return(_result);
        }