Пример #1
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);
        }