private void mnuGlobalSettings_Click(object sender, EventArgs e)
        {
            if (!mnuGlobalSettings.Enabled)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;

            IAsyncResult _sync1 = Cache.SyncTableAsync(SCMS.Connection, "settings");

            _sync1.WaitToFinish();

            IAsyncResult _sync2 = Cache.SyncTableAsync(SCMS.Connection, "accounts");

            _sync2.WaitToFinish();

            IAsyncResult _sync3 = Cache.SyncTableAsync(SCMS.Connection, "companies");

            _sync3.WaitToFinish();

            Cursor = Cursors.Default; Materia.RefreshAndManageCurrentProcess();

            GlobalSettingDialog _dialog = new GlobalSettingDialog();

            if (_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                IAsyncResult _settingsync = GlobalSettings.RefreshAsync(SCMS.CurrentCompany.Company);
                _settingsync.WaitToFinish(); InitializeHeading();
            }
            _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
        }
        private void mnuUserManagement_Click(object sender, EventArgs e)
        {
            if (!mnuUserManagement.Enabled)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;

            IAsyncResult _sync1 = Cache.SyncTableAsync(SCMS.Connection, "departments");

            _sync1.WaitToFinish();

            IAsyncResult _sync2 = Cache.SyncTableAsync(SCMS.Connection, "positions");

            _sync2.WaitToFinish();

            IAsyncResult _sync3 = Cache.SyncTableAsync(SCMS.Connection, "companies");

            _sync3.WaitToFinish();

            Cursor = Cursors.Default; Materia.RefreshAndManageCurrentProcess();

            UserManagementDialog _dialog = new UserManagementDialog();

            if (_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
            }
            _dialog.Dispose(); _dialog = null; Materia.RefreshAndManageCurrentProcess();
        }
        private void mnuLogActivityViewer_Click(object sender, EventArgs e)
        {
            if (!mnuLogActivityViewer.Enabled)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;

            IAsyncResult _sync1 = Cache.SyncTableAsync(SCMS.Connection, "users");

            _sync1.WaitToFinish();

            IAsyncResult _sync2 = Cache.SyncTableAsync(SCMS.Connection, "userlogs");

            _sync2.WaitToFinish();

            Cursor = Cursors.Default;

            LogActivityViewerDialog _dialog = new LogActivityViewerDialog();

            _dialog.ShowDialog(); _dialog.Dispose(); _dialog = null;
            Materia.RefreshAndManageCurrentProcess();
        }
        private void InitializeUsersList()
        {
            pctLoad.Show(); pctLoad.BringToFront();
            if (grdUsers.Redraw)
            {
                grdUsers.BeginUpdate();
            }
            btnAdd.Enabled      = false; btnEdit.Enabled = false;
            btnDelete.Enabled   = false; btnRefresh.Enabled = false;
            txtSearch.Enabled   = false; txtSearch.Text = "";
            btnInformation.Text = " Gathering data...";

            IAsyncResult _cacheresult = Cache.SyncTableAsync(SCMS.Connection, "users");

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

            if (_cancelled)
            {
                try { _cacheresult = null; }
                catch { }
                finally { Materia.RefreshAndManageCurrentProcess(); }

                return;
            }
            else
            {
                DataTable _table = Cache.GetCachedTable("users");
                var       _query = from _users in _table.AsEnumerable()
                                   where _users.Field <Int16>("Voided") == 0
                                   select new
                {
                    Username     = _users.Field <string>("Username"),
                    FullName     = _users.Field <string>("FirstName") + " " + _users.Field <string>("LastName"),
                    Department   = _users.Field <string>("Department"),
                    Position     = _users.Field <string>("Position"),
                    Active       = _users.Field <Int16>("Active"),
                    DateCreated  = _users.Field <DateTime>("DateCreated"),
                    LastModified = _users.Field <DateTime>("LastModified")
                };

                DataTable _datasource = GetBlankDataSource();
                foreach (var _row in _query)
                {
                    _datasource.Rows.Add(new object[] {
                        _row.Username, _row.FullName,
                        _row.Department, _row.Position,
                        _row.Active, _row.DateCreated,
                        _row.LastModified
                    });
                }

                _datasource.DefaultView.Sort = "[Username]";
                grdUsers.ClearRowsAndColumns();
                grdUsers.DataSource = _datasource;
                FormatGrid(); ResizeGrid();
                while (!grdUsers.Redraw)
                {
                    grdUsers.EndUpdate();
                }
            }

            EnabledButtons(); pctLoad.Hide(); DisplayInfo();
        }
        /// <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);
        }