Пример #1
0
 private void InitializeTimeAndKeyboardInfo()
 {
     btnDate.Text    = " " + VisualBasic.Format(DateTime.Now, "dd-MMM-yyyy");
     btnTime.Text    = " " + VisualBasic.Format(DateTime.Now, "hh:mm:ss tt");
     btnCaps.Enabled = Control.IsKeyLocked(Keys.CapsLock);
     btnNum.Enabled  = Control.IsKeyLocked(Keys.NumLock);
     btnScrl.Enabled = Control.IsKeyLocked(Keys.Scroll);
 }
Пример #2
0
        private void InitializeInfo()
        {
            DataTable _scripts = Cache.GetCachedTable("scripts");

            if (_scripts != null)
            {
                DataRow[] _rows = _scripts.Select("[ReferenceNo] LIKE '" + _referenceno.ToSqlValidString(true) + "'");
                if (_rows.Length > 0)
                {
                    DataRow _row = _rows[0];

                    if (!Materia.IsNullOrNothing(_row["ReferenceNo"]))
                    {
                        txtReferenceNo.Text = _row["ReferenceNo"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["SystemVersion"]))
                    {
                        txtSystemVersion.Text = _row["SystemVersion"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Author"]))
                    {
                        txtAuthor.Text = _row["Author"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Title"]))
                    {
                        txtTitle.Text = _row["Title"].ToString();
                    }
                    if (!Materia.IsNullOrNothing(_row["Script"]))
                    {
                        txtScript.Text = _row["Script"].ToString();
                    }
                    if (VisualBasic.IsNumeric(_row["RequireBackup"]))
                    {
                        chkBackup.Checked = VisualBasic.CBool(_row["RequireBackup"]);
                    }
                    if (VisualBasic.IsNumeric(_row["RequireAppRestart"]))
                    {
                        chkRestartApp.Checked = VisualBasic.CBool(_row["RequireAppRestart"]);
                    }
                    if (VisualBasic.IsNumeric(_row["RequirePcRestart"]))
                    {
                        chkRestartPc.Checked = VisualBasic.CBool(_row["RequirePcRestart"]);
                    }
                    if (!Materia.IsNullOrNothing(_row["Description"]))
                    {
                        txtDescription.Text = _row["Description"].ToString();
                    }
                    if (VisualBasic.IsNumeric(_row["Executed"]))
                    {
                        if (VisualBasic.CBool(_row["Executed"]))
                        {
                            if (VisualBasic.IsDate(_row["DateExecuted"]))
                            {
                                lblExecuted.Text = "Last Executed : " + VisualBasic.Format(VisualBasic.CDate(_row["DateExecuted"]), "dd-MMM-yyyy");
                                lblExecuted.Show(); lblExecuted.BringToFront();
                            }
                            else
                            {
                                lblExecuted.Hide();
                            }
                        }
                        else
                        {
                            lblExecuted.Hide();
                        }
                    }

                    if (VisualBasic.IsNumeric(_row["AutoScript"]))
                    {
                        if (VisualBasic.CBool(_row["AutoScript"]))
                        {
                            lblAutoScript.Show(); lblAutoScript.BringToFront();
                        }
                        else
                        {
                            lblAutoScript.Hide();
                        }
                    }
                    else
                    {
                        lblAutoScript.Hide();
                    }
                }
            }
        }
        /// <summary>
        /// Applies table updates from the specified DataTable object into the current DataObjectMap's table.
        /// </summary>
        /// <param name="table"></param>
        public void ApplyUpdatesFromTable(DataTable table)
        {
            if (_table != null &&
                table != null)
            {
                DataTable _updates = table.GetChanges();
                if (_updates != null)
                {
                    foreach (DataRow _row in _updates.Rows)
                    {
                        string _pk = "";

                        foreach (DataColumn _col in _table.Columns)
                        {
                            if (_col.Unique)
                            {
                                _pk = _col.ColumnName; break;
                            }
                        }

                        if (String.IsNullOrEmpty(_pk.RLTrim()))
                        {
                            _pk = _table.Columns[0].ColumnName;
                        }

                        object _pkvalue = null;

                        if (_row.RowState == DataRowState.Deleted ||
                            _row.RowState == DataRowState.Detached ||
                            _row.RowState == DataRowState.Modified)
                        {
                            try { _pkvalue = _row[_pk, DataRowVersion.Original]; }
                            catch { _pkvalue = null; }
                        }
                        else
                        {
                            _pkvalue = _row[_pk];
                        }

                        if (!Materia.IsNullOrNothing(_pkvalue))
                        {
                            string     _filter = "[" + _pk + "] = ";
                            DataColumn _pkcol  = _table.Columns[_pk];
                            object[]   _values = null;

                            switch (_row.RowState)
                            {
                            case DataRowState.Added:
                                _values = new object[_table.Columns.Count];
                                foreach (DataColumn _col in _table.Columns)
                                {
                                    if (!_col.AutoIncrement)
                                    {
                                        if (table.Columns.Contains(_col.ColumnName))
                                        {
                                            _values[_col.Ordinal] = _row[_col.ColumnName];
                                        }
                                    }
                                }
                                AddRow(_values);
                                break;

                            case DataRowState.Deleted:
                            case DataRowState.Detached:
                            case DataRowState.Modified:
                                if (_pkcol.DataType.Name == typeof(string).Name ||
                                    _pkcol.DataType.Name == typeof(String).Name)
                                {
                                    _filter += "'" + _pkvalue.ToString().ToSqlValidString(true) + "'";
                                }
                                else if (_pkcol.DataType.Name == typeof(DateTime).Name)
                                {
                                    if (VisualBasic.IsDate(_pkvalue))
                                    {
                                        _filter += "#" + VisualBasic.Format(VisualBasic.CDate(_pkvalue), "MM/dd/yyyy hh:mm:ss tt") + "#";
                                    }
                                    else
                                    {
                                        _filter = "";
                                    }
                                }
                                else if (_pkcol.DataType.Name == typeof(bool).Name ||
                                         _pkcol.DataType.Name == typeof(Boolean).Name)
                                {
                                    bool _value = VisualBasic.CBool(_pkvalue);
                                    _filter += _value.ToString();
                                }
                                else if (_pkcol.DataType.Name == typeof(byte).Name ||
                                         _pkcol.DataType.Name == typeof(Byte).Name ||
                                         _pkcol.DataType.Name == typeof(decimal).Name ||
                                         _pkcol.DataType.Name == typeof(Decimal).Name ||
                                         _pkcol.DataType.Name == typeof(double).Name ||
                                         _pkcol.DataType.Name == typeof(Double).Name ||
                                         _pkcol.DataType.Name == typeof(int).Name ||
                                         _pkcol.DataType.Name == typeof(Int16).Name ||
                                         _pkcol.DataType.Name == typeof(Int32).Name ||
                                         _pkcol.DataType.Name == typeof(Int64).Name ||
                                         _pkcol.DataType.Name == typeof(long).Name ||
                                         _pkcol.DataType.Name == typeof(sbyte).Name ||
                                         _pkcol.DataType.Name == typeof(SByte).Name ||
                                         _pkcol.DataType.Name == typeof(short).Name ||
                                         _pkcol.DataType.Name == typeof(Single).Name)
                                {
                                    if (VisualBasic.IsNumeric(_pkvalue))
                                    {
                                        _filter += _pkvalue.ToString();
                                    }
                                    else
                                    {
                                        _filter = "";
                                    }
                                }

                                if (!String.IsNullOrEmpty(_filter.RLTrim()))
                                {
                                    if (_row.RowState == DataRowState.Deleted ||
                                        _row.RowState == DataRowState.Detached)
                                    {
                                        DeleteRow(_filter);
                                    }
                                    else
                                    {
                                        DataRow[] _rows = Select(_filter);
                                        if (_rows.Length > 0)
                                        {
                                            DataRow _actualrow = _rows[0];
                                            if (_actualrow.RowState != DataRowState.Deleted &&
                                                _actualrow.RowState != DataRowState.Detached)
                                            {
                                                foreach (DataColumn _col in _table.Columns)
                                                {
                                                    if (!_col.AutoIncrement)
                                                    {
                                                        if (table.Columns.Contains(_col.ColumnName))
                                                        {
                                                            _actualrow[_col.ColumnName] = _row[_col.ColumnName];
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            _values = new object[_table.Columns.Count];
                                            foreach (DataColumn _col in _table.Columns)
                                            {
                                                if (!_col.AutoIncrement)
                                                {
                                                    if (table.Columns.Contains(_col.ColumnName))
                                                    {
                                                        _values[_col.Ordinal] = _row[_col.ColumnName];
                                                    }
                                                }
                                            }
                                            AddRow(_values);
                                        }
                                    }
                                }
                                break;

                            default: break;
                            }
                        }
                    }
                }
            }
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (!btnBrowse.Enabled)
            {
                return;
            }

            SaveFileDialog _dialog = new SaveFileDialog();

            _dialog.DefaultExt = "scmsiv";
            _dialog.Filter     = "SCMS Database Backup Files (*.scmsiv)|*.scmsiv";
            _dialog.Title      = "Select Output Path";
            _dialog.FileName   = SCMS.ServerConnection.Database.ToUpper() + "_BACKUP_" + VisualBasic.Format(DateTime.Now, "dd_MM_yyyy_HH_mm_ss") + ".scmsiv";
            if (_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (!String.IsNullOrEmpty(_dialog.FileName.RLTrim()))
                {
                    lblPath.Text = _dialog.FileName;
                }
            }
            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
        }
        private void DatabaseBackupDialog_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false; this.ManageOnDispose();
            pctLoad.Hide(); grdStatus.InitializeAppearance();
            grdStatus.BorderStyle = C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None;
            InitializeEventGrid();

            if (IsFileBrowsingEnabled)
            {
                string _dir = GlobalSettings.AutomaticBackupPath;
                if (string.IsNullOrEmpty(_dir.RLTrim()))
                {
                    _dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }
                else
                {
                    if (!Directory.Exists(_dir))
                    {
                        _dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    }
                }
                lblPath.Text = _dir + "\\" + SCMS.ServerConnection.Database.ToUpper() + "_BACKUP_" + VisualBasic.Format(DateTime.Now, "dd_MM_yyyy_HH_mm_ss") + ".scmsiv";
                AddEvent(BackupEvent.Information, "Ready, press 'Backup' to proceed.");
            }
        }
        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;
                        }
                    }
                }
            }
        }
Пример #7
0
        private void btnBrowseRestorePoint_Click(object sender, EventArgs e)
        {
            if (!btnBrowseRestorePoint.Enabled)
            {
                return;
            }
            RestorePointSelectionDialog _dialog = new RestorePointSelectionDialog();

            if (_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (_dialog.SelectedRestorePoint != null)
                {
                    lblPath.Text       = "Restore Point : " + _dialog.SelectedRestorePoint.Server + "\\" + _dialog.SelectedRestorePoint.Database + " as of " + VisualBasic.Format(_dialog.SelectedRestorePoint.AsOf, "dd-MMM-yyyy hh:mm:ss tt");
                    _backupfilename    = _dialog.SelectedRestorePoint.Filename;
                    btnRestore.Enabled = File.Exists(_backupfilename);
                }
            }
            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
        }
Пример #8
0
        private RestorePointInfo MakeRestorePoint()
        {
            RestorePointInfo _restorepoint = null;

            AddEvent(BackupEvent.Information, "Creating database restore point...");

            string _rpdir = Application.StartupPath + "\\Restore Points";

            if (!Directory.Exists(_rpdir))
            {
                try { Directory.CreateDirectory(_rpdir); }
                catch (Exception ex)
                {
                    SCMS.LogError(this.GetType().Name, ex);
                    AddEvent(BackupEvent.Error, "Can't create database restore point directory.");
                }
            }

            if (Directory.Exists(_rpdir))
            {
                Func <IDbConnection, DateTime> _serverdatedelegate = new Func <IDbConnection, DateTime>(MySql.GetServerDateAndTime);
                IAsyncResult _serverdateresult = _serverdatedelegate.BeginInvoke(SCMS.Connection, null, _serverdatedelegate);
                _serverdateresult.WaitToFinish();
                DateTime _serverdatetime = _serverdatedelegate.EndInvoke(_serverdateresult);
                string   _rpfilename     = _rpdir + "\\" + SCMS.ServerConnection.Database.ToUpper() + "_" + SCMS.CurrentCompany.Company + "_RESTORE_POINT_" + VisualBasic.Format(_serverdatetime, "dd_MM_yyyy_HH_mm_ss") + ".sql";
                int      _trycounter     = 0;

                MySqlDumpParameterCollection _parameters = new MySqlDumpParameterCollection();
                _parameters.Add(MySqlDumpParameters.CompleteInsert);
                _parameters.Add(MySqlDumpParameters.HexBlob);
                _parameters.Add(MySqlDumpParameters.Routines);
                _parameters.Add("--skip-extended-insert");
                _parameters.Add(MySqlDumpParameters.Triggers);
                _parameters.Add(MySqlDumpParameters.Quick);

                Func <string, string, MySqlDumpParameterCollection, MySqlResult> _dumpdelegate = new Func <string, string, MySqlDumpParameterCollection, MySqlResult>(MySql.Dump);
                IAsyncResult _dumpresult = _dumpdelegate.BeginInvoke(SCMS.ServerConnection.ToString(), _rpfilename, _parameters, null, _dumpdelegate);

                AddEvent(BackupEvent.Information, "Restore point creation started.");

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

                if (_cancelled)
                {
                    AddEvent(BackupEvent.Warning, "Cancelling restore point creation...");

                    _trycounter = 0;

                    while (File.Exists(_rpfilename) &&
                           _trycounter <= 30)
                    {
                        try { File.Delete(_rpfilename); }
                        catch { }

                        _trycounter += 1;
                        Thread.Sleep(100); Application.DoEvents();
                    }

                    Materia.RefreshAndManageCurrentProcess();
                    AddEvent(BackupEvent.Information, "Restore point creation cancelled.");
                }
                else
                {
                    MySqlResult _result = _dumpdelegate.EndInvoke(_dumpresult);
                    if (_result.Succeeded)
                    {
                        string    _path  = Application.StartupPath + "\\Xml\\restorepoints.xml";
                        DataTable _table = SCMS.XmlToTable(_path);

                        if (_table != null)
                        {
                            bool _created = false; DataRow _newrow = null;

                            object[]             _values = new object[_table.Columns.Count];
                            DataColumnCollection _cols = _table.Columns;
                            _values[_cols["DateAndTime"].Ordinal] = _serverdatetime;
                            _values[_cols["Filename"].Ordinal]    = _rpfilename;
                            _values[_cols["Company"].Ordinal]     = SCMS.CurrentCompany.Company;
                            _values[_cols["Server"].Ordinal]      = SCMS.ServerConnection.Server;
                            _values[_cols["Database"].Ordinal]    = SCMS.ServerConnection.Database;

                            try
                            {
                                _newrow = _table.Rows.Add(_values);
                                _table.AcceptChanges();
                                _table.WriteXml(_path, XmlWriteMode.WriteSchema);
                                _created = true;
                            }
                            catch (Exception ex)
                            {
                                SCMS.LogError(this.GetType().Name, ex);
                                AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point.");

                                _trycounter = 0;

                                while (File.Exists(_rpfilename) &&
                                       _trycounter <= 30)
                                {
                                    try { File.Delete(_rpfilename); }
                                    catch { }

                                    _trycounter += 1;
                                    Thread.Sleep(100); Application.DoEvents();
                                }
                            }

                            if (_created)
                            {
                                _restorepoint = new RestorePointInfo(VisualBasic.CLng(_newrow["DetailId"]));
                            }

                            _table.Dispose(); _table = null;
                            Materia.RefreshAndManageCurrentProcess();
                        }
                        else
                        {
                            AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point.");

                            _trycounter = 0;

                            while (File.Exists(_rpfilename) &&
                                   _trycounter <= 30)
                            {
                                try { File.Delete(_rpfilename); }
                                catch { }

                                _trycounter += 1;
                                Thread.Sleep(100); Application.DoEvents();
                            }

                            Materia.RefreshAndManageCurrentProcess();
                        }
                    }
                    else
                    {
                        SCMS.LogError(this.GetType().Name, new Exception(_result.Error));
                        AddEvent(BackupEvent.Error, "Failed to create and / or complete database restore point.");

                        _trycounter = 0;

                        while (File.Exists(_rpfilename) &&
                               _trycounter <= 30)
                        {
                            try { File.Delete(_rpfilename); }
                            catch { }

                            _trycounter += 1;
                            Thread.Sleep(100); Application.DoEvents();
                        }

                        Materia.RefreshAndManageCurrentProcess();
                    }
                }
            }

            return(_restorepoint);
        }
Пример #9
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);
        }