Ejemplo n.º 1
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (grdRestorePoints.DataSource == null)
     {
         return;
     }
     if (grdRestorePoints.RowSel < grdRestorePoints.Rows.Fixed)
     {
         return;
     }
     if (!Materia.IsNullOrNothing(grdRestorePoints.Rows[grdRestorePoints.RowSel]["Info"]))
     {
         _selectedrestorepoint = (RestorePointInfo)grdRestorePoints.Rows[grdRestorePoints.RowSel]["Info"];
         DialogResult          = System.Windows.Forms.DialogResult.OK; Close();
     }
 }
Ejemplo n.º 2
0
        private void InitializeRestorePoints()
        {
            if (grdRestorePoints.Redraw)
            {
                grdRestorePoints.BeginUpdate();
            }

            if (grdRestorePoints.DataSource != null)
            {
                try { grdRestorePoints.DataSource = null; }
                catch { }
                finally { Materia.RefreshAndManageCurrentProcess(); }
            }

            string    _path  = Application.StartupPath + "\\Xml\\restorepoints.xml";
            DataTable _table = SCMS.XmlToTable(_path);

            if (_table != null)
            {
                DataTable  _datasource = new DataTable();
                DataColumn _pkcol      = _datasource.Columns.Add("Id", typeof(int));
                _pkcol.AutoIncrement     = true; _pkcol.AutoIncrementSeed = 1;
                _pkcol.AutoIncrementStep = 1;
                _datasource.Columns.Add("Select", typeof(bool));
                _datasource.Columns.Add("As Of", typeof(DateTime));
                _datasource.Columns.Add("Info", typeof(RestorePointInfo));


                DataRow[] _rows = _table.Select("[Company] LIKE '" + SCMS.CurrentCompany.Company.ToSqlValidString(true) + "' AND\n" +
                                                "[Server] LIKE '" + SCMS.ServerConnection.Server.ToSqlValidString(true) + "' AND\n" +
                                                "[Database] LIKE '" + SCMS.ServerConnection.Database.ToSqlValidString(true) + "'");

                for (int i = 0; i <= (_rows.Length - 1); i++)
                {
                    DataRow          _row          = _rows[i];
                    RestorePointInfo _restorepoint = new RestorePointInfo(VisualBasic.CLng(_row["DetailId"]));

                    if (!String.IsNullOrEmpty(_restorepoint.Filename.RLTrim()))
                    {
                        if (File.Exists(_restorepoint.Filename))
                        {
                            DataColumnCollection _cols   = _datasource.Columns;
                            object[]             _values = new object[_cols.Count];
                            _values[_cols["Select"].Ordinal] = VisualBasic.CBool(i == 0);
                            _values[_cols["As Of"].Ordinal]  = _row["DateAndTime"];
                            _values[_cols["Info"].Ordinal]   = _restorepoint;
                            _datasource.Rows.Add(_values);
                        }
                    }
                }

                grdRestorePoints.DataSource = _datasource;
                grdRestorePoints.Rows[grdRestorePoints.Rows.Fixed - 1].Visible = false;
                grdRestorePoints.Cols["Id"].Visible     = false;
                grdRestorePoints.Cols["Select"].Caption = "";
                grdRestorePoints.Cols["As Of"].Format   = "dd-MMM-yyyy hh:mm:ss tt";
                grdRestorePoints.Cols["Info"].Visible   = false;
                grdRestorePoints.AutoNumber();
                grdRestorePoints.AutoSizeCols();
                grdRestorePoints.ExtendLastCol = true;
            }
            else
            {
                grdRestorePoints.InitializeAppearance();
            }

            while (!grdRestorePoints.Redraw)
            {
                grdRestorePoints.EndUpdate();
            }
        }
Ejemplo n.º 3
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.º 4
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);
        }