Exemplo n.º 1
0
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if (!btnSignIn.Enabled)
            {
                return;
            }

            Validator _validator = SCMS.Validators[this]; pnlNotification.Hide();

            if (!Materia.Valid(_validator, cboServers, cboServers.SelectedIndex >= 0, "Select a database server."))
            {
                return;
            }
            if (!Materia.Valid(_validator, cboCompanies, cboCompanies.SelectedIndex >= 0, "Select access company."))
            {
                return;
            }

            SCMS.ServerConnection = null; SCMS.Connection = null;
            Materia.RefreshAndManageCurrentProcess();

            if (String.IsNullOrEmpty(txtUsername.Text.RLTrim()) ||
                String.IsNullOrEmpty(txtPassword.Text.RLTrim()))
            {
                pnlNotification.Text = "Invalid account credentials.";
                pnlNotification.Show(); pnlNotification.BringToFront();
                return;
            }

            ServerConnectionInfo _info = new ServerConnectionInfo(cboServers.SelectedValue.ToString());

            pctLoad.Show(); pctLoad.BringToFront();
            btnSignIn.Enabled = false; cboServers.Enabled = false; cboCompanies.Enabled = false;

            IDbConnection _connection = Database.CreateConnection(_info.ToString());

            Func <IDbConnection, bool> _connectdelegate = new Func <IDbConnection, bool>(Materia.CanConnect);
            IAsyncResult _connectresult = _connectdelegate.BeginInvoke(_connection, null, _connectdelegate);

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

            bool _connected = false;

            if (_cancelled)
            {
                if (!_connectresult.IsCompleted)
                {
                    try { _connectresult = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }
            }
            else
            {
                _connected = _connectdelegate.EndInvoke(_connectresult);
                if (!_connected)
                {
                    MsgBoxEx.Alert("Failed to connect to the specified database server.", "Database Connection");
                }
            }

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

                    try { _connection.Dispose(); }
                    catch { }

                    _connection = null; Materia.RefreshAndManageCurrentProcess();
                }

                cboServers.Enabled = true; cboCompanies.Enabled = true;
                btnSignIn.Enabled  = true; pctLoad.Hide(); return;
            }

            SCMS.Connection     = _connection; SCMS.ServerConnection = new ServerConnectionInfo(cboServers.SelectedValue.ToString());
            SCMS.CurrentCompany = new CompanyInfo(cboCompanies.SelectedValue.ToString());

            Func <IDbConnection, string, DateTime> _getvaluedelegate = new Func <IDbConnection, string, DateTime>(Que.GetValue <DateTime>);
            IAsyncResult _getvalueresult = _getvaluedelegate.BeginInvoke(_connection, "SELECT MAX(`LastRestored`) AS `Date` FROM `settings`", null, _getvaluedelegate);

            _getvalueresult.WaitToFinish();
            DateTime _dbtimestamp = _getvaluedelegate.EndInvoke(_getvalueresult);
            DateTime _timestamp   = Cache.LastRestoration;

            if (_dbtimestamp > _timestamp)
            {
                Cache.Clear(); Cache.UpdateCacheTimeStamp(_dbtimestamp);
            }

            Action <IDbConnection> _inituserdelegate = new Action <IDbConnection>(CreateInitialUser);
            IAsyncResult           _inituserresult   = _inituserdelegate.BeginInvoke(SCMS.Connection, null, _inituserdelegate);

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

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

                return;
            }
            else
            {
                Action <IDbConnection> _initcompaniesdelegate = new Action <IDbConnection>(CreateInitialCompanies);
                IAsyncResult           _initcompaniesresult   = _initcompaniesdelegate.BeginInvoke(SCMS.Connection, null, _initcompaniesdelegate);

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

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

                    return;
                }
                else
                {
                    SCMS.CurrentSystemUser = null; Materia.RefreshAndManageCurrentProcess();
                    SystemUserInfo _userinfo = new SystemUserInfo(txtUsername.Text, txtPassword.Text);

                    IAsyncResult _loginasync = _userinfo.LogInAsync();

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

                    if (_cancelled)
                    {
                        if (!_loginasync.IsCompleted)
                        {
                            try { _loginasync = null; }
                            catch { }
                            finally { Materia.RefreshAndManageCurrentProcess(); }
                        }
                    }
                    else
                    {
                        if (_userinfo.IsSignedIn)
                        {
                            SCMS.CurrentSystemUser = _userinfo;
                            InitializerDialog _loader = new InitializerDialog();
                            _loader.Message  = "Gathering application settings for " + SCMS.CurrentCompany.Company + ".";
                            txtPassword.Text = ""; Hide(); _loader.Show();

                            IAsyncResult _gsresult = GlobalSettings.RefreshAsync(SCMS.CurrentCompany.Company);
                            _gsresult.WaitToFinish(); SCMS.CleanUp();

                            _loader.Close(); _loader.Dispose(); _loader = null;
                            Materia.RefreshAndManageCurrentProcess();
                            MainWindow _main = new MainWindow(); _main.Show();
                        }
                        else
                        {
                            if (_userinfo.IsValidUser &&
                                !_userinfo.IsActive)
                            {
                                pnlNotification.Text = "Account needs activation.";
                                pnlNotification.Show(); pnlNotification.BringToFront();
                            }
                            else
                            {
                                if (_userinfo.IsValidUser &&
                                    !_userinfo.AccessibleCompanies.Contains(SCMS.CurrentCompany.Company))
                                {
                                    pnlNotification.Text = "Account not allowed in selected company.";
                                    pnlNotification.Show(); pnlNotification.BringToFront();
                                }
                                else
                                {
                                    pnlNotification.Text = "Invalid account credentials.";
                                    pnlNotification.Show(); pnlNotification.BringToFront();
                                }
                            }

                            _userinfo = null; Materia.RefreshAndManageCurrentProcess();
                        }

                        cboCompanies.Enabled = true; cboServers.Enabled = true;
                        btnSignIn.Enabled    = true; pctLoad.Hide();
                    }
                }
            }
        }
Exemplo n.º 2
0
        private void InitializeDataSource()
        {
            if (grdRecords.Redraw)
            {
                grdRecords.BeginUpdate();
            }
            DisableButtons(); trvwModules.Enabled = false;

            Func <DataTable> _delegate = null;

            switch (_selectedsubmodule)
            {
            case SubModule.BankAccounts:
                _delegate = new Func <DataTable>(GetBankAccounts); break;

            case SubModule.Customers:
                _delegate = new Func <DataTable>(GetCustomers); break;

            case SubModule.PartsInventory:
                _delegate = new Func <DataTable>(GetPartInventory); break;

            default: break;
            }

            if (_delegate != null)
            {
                InitializerDialog _dialog = null;

                DataTable _datasource = null;
                if (grdRecords.DataSource != null)
                {
                    try { _datasource = (DataTable)grdRecords.DataSource; }
                    catch { }
                }

                grdRecords.Cursor = Cursors.WaitCursor;

                if (_datasource == null)
                {
                    _dialog         = new InitializerDialog();
                    _dialog.Message = "Loading... Please wait...";
                    _dialog.Show();
                }

                IAsyncResult _result = _delegate.BeginInvoke(null, _delegate);

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

                if (_cancelled)
                {
                    if (_dialog != null)
                    {
                        _dialog.Close(); _dialog.Dispose(); _dialog = null;
                    }

                    if (!_result.IsCompleted)
                    {
                        try { _result = null; }
                        catch { }
                    }

                    Materia.RefreshAndManageCurrentProcess(); return;
                }
                else
                {
                    DataTable _updates = _delegate.EndInvoke(_result);

                    if (_datasource != null)
                    {
                        try { _datasource.Merge(_updates, false); }
                        catch { }
                    }
                    else
                    {
                        grdRecords.DataSource = _updates;
                    }

                    FormatGrid(); ResizeGrid();
                    EnableButtons();

                    if (_dialog != null)
                    {
                        _dialog.Close(); _dialog.Dispose(); _dialog = null;
                    }
                    Materia.RefreshAndManageCurrentProcess();
                    trvwModules.Enabled = true;

                    if (grdRecords.DataSource != null)
                    {
                        while (!grdRecords.Redraw)
                        {
                            grdRecords.EndUpdate();
                        }
                    }

                    grdRecords.Cursor = Cursors.Default;
                }
            }
        }
Exemplo n.º 3
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);
        }