示例#1
0
 ///<summary>Returns false if the backup, repair, or the optimze failed.
 ///Set isSilent to true to suppress the failure message boxes.  However, progress windows will always be shown.</summary>
 public static bool BackupRepairAndOptimize(bool isSilent, BackupLocation backupLocation, bool isSecurityLogged = true)
 {
     if (!MakeABackup(isSilent, backupLocation, isSecurityLogged))
     {
         return(false);
     }
     try {
         ODProgress.ShowAction(() => DatabaseMaintenances.RepairAndOptimize(),
                               eventType: typeof(MiscDataEvent),
                               odEventType: ODEventType.MiscData);
     }
     catch (Exception ex) {           //MiscData.MakeABackup() could have thrown an exception.
         //Show the user that something what went wrong when not in silent mode.
         if (!isSilent)
         {
             if (ex.Message != "")
             {
                 MessageBox.Show(ex.Message);
             }
             MsgBox.Show("FormDatabaseMaintenance", "Optimize and Repair failed.");
         }
         return(false);
     }
     return(true);
 }
        public void FeeSchedTools_CopyFeeSched_Clinics()
        {
            //Make sure there are no duplicate fees already present within the database.
            string dbmResult = DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Check);

            if (dbmResult.Trim() != _feeDeleteDuplicatesExpectedResult)
            {
                DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Fix);
            }
            //Make sure that there are more than six clinics
            ClinicT.ClearClinicTable();
            for (int i = 0; i < 10; i++)
            {
                ClinicT.CreateClinic(MethodBase.GetCurrentMethod().Name + "_" + i);
            }
            //Create two fee schedules; from and to
            FeeSched feeSchedNumFrom = FeeSchedT.GetNewFeeSched(FeeScheduleType.Normal, MethodBase.GetCurrentMethod().Name + "_FROM");
            FeeSched feeSchedNumTo   = FeeSchedT.GetNewFeeSched(FeeScheduleType.Normal, MethodBase.GetCurrentMethod().Name + "_TO");

            //Create a fee for every single procedure code in the database and associate it to the "from" fee schedule.
            foreach (ProcedureCode code in _listProcCodes)
            {
                FeeT.CreateFee(feeSchedNumFrom.FeeSchedNum, code.CodeNum, _rand.Next(5000));
            }
            //Copy the "from" fee schedule into the "to" fee schedule and do it for at least seven clinics.
            FeeScheds.CopyFeeSchedule(feeSchedNumFrom, 0, 0, feeSchedNumTo, Clinics.GetDeepCopy(true).Select(x => x.ClinicNum).ToList(), 0);
            //Make sure that there was NOT a duplicate fee inserted into the database.
            dbmResult = DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Check);
            Assert.AreEqual(dbmResult.Trim(), _feeDeleteDuplicatesExpectedResult, "Duplicate fees detected due to concurrent copying.");
        }
        private void FillGridOld()
        {
            _listDbmMethodsGridOld = DbmMethodsForGridHelper(isHidden: false, isOld: true);
            //Add the hidden methods if needed
            if (checkShowHidden.Checked)
            {
                _listDbmMethodsGridOld.AddRange(DbmMethodsForGridHelper(isHidden: true, isOld: true));
                //Adding hidden methods will cause the list to no longer be ordered by name
                _listDbmMethodsGridOld.Sort(new MethodInfoComparer());
            }
            gridOld.BeginUpdate();
            gridOld.ListGridColumns.Clear();
            gridOld.ListGridColumns.Add(new GridColumn(Lan.g(this, "Name"), 300));
            gridOld.ListGridColumns.Add(new GridColumn(Lan.g(this, "Hidden"), 45, HorizontalAlignment.Center));
            gridOld.ListGridColumns.Add(new GridColumn(Lan.g(this, BREAKDOWN_COLUMN_NAME), 40, HorizontalAlignment.Center));
            gridOld.ListGridColumns.Add(new GridColumn(Lan.g(this, RESULTS_COLUMN_NAME), 0));
            gridOld.ListGridRows.Clear();
            GridRow row;

            for (int i = 0; i < _listDbmMethodsGridOld.Count; i++)
            {
                bool isMethodHidden = _listDatabaseMaintenances.Any(x => x.MethodName == _listDbmMethodsGridOld[i].Name && x.IsHidden);
                row = new GridRow();
                row.Cells.Add(_listDbmMethodsGridOld[i].Name);
                row.Cells.Add(isMethodHidden ? "X" : "");
                row.Cells.Add(DatabaseMaintenances.MethodHasBreakDown(_listDbmMethodsGridOld[i]) ? "X" : "");
                row.Cells.Add("");
                row.Tag = _listDbmMethodsGridOld[i];
                gridOld.ListGridRows.Add(row);
            }
            gridOld.EndUpdate();
        }
示例#4
0
        ///<summary>Returns false if the backup, repair, or the optimze failed.
        ///Set isSilent to true to suppress the failure message boxes.  However, progress windows will always be shown.</summary>
        public static bool BackupRepairAndOptimize(bool isSilent, BackupLocation backupLocation, bool isSecurityLogged = true)
        {
            if (!MakeABackup(isSilent, backupLocation, isSecurityLogged))
            {
                return(false);
            }
            //Create a thread that will show a window and then stay open until the closing phrase is thrown from this form.
            Action actionCloseRepairAndOptimizeProgress = ODProgressOld.ShowProgressStatus("RepairAndOptimizeProgress", null);

            try {
                DatabaseMaintenances.RepairAndOptimize();
                actionCloseRepairAndOptimizeProgress();
            }
            catch (Exception ex) {           //MiscData.MakeABackup() could have thrown an exception.
                actionCloseRepairAndOptimizeProgress();
                //Show the user that something what went wrong when not in silent mode.
                if (!isSilent)
                {
                    if (ex.Message != "")
                    {
                        MessageBox.Show(ex.Message);
                    }
                    MsgBox.Show("FormDatabaseMaintenance", "Optimize and Repair failed.");
                }
                return(false);
            }
            return(true);
        }
        public void FeeSchedTools_CopyFeeSched_Concurrency()
        {
            //Make sure there are no duplicate fees already present within the database.
            string dbmResult = DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Check);

            if (dbmResult.Trim() != _feeDeleteDuplicatesExpectedResult)
            {
                DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Fix);
            }
            //Create two fee schedules; from and to
            FeeSched feeSchedFrom = FeeSchedT.GetNewFeeSched(FeeScheduleType.Normal, MethodBase.GetCurrentMethod().Name + "_FROM");
            FeeSched feeSchedTo   = FeeSchedT.GetNewFeeSched(FeeScheduleType.Normal, MethodBase.GetCurrentMethod().Name + "_TO");

            //Create a single fee and associate it to the "from" fee schedule.
            FeeT.CreateFee(feeSchedFrom.FeeSchedNum, _listProcCodes[_rand.Next(_listProcCodes.Count - 1)].CodeNum, _defaultFeeAmt);
            //Create a helper action that will simply copy the "from" schedule into the "to" schedule for the given fee cache passed in.
            Action actionCopyFromTo = new Action(() => {
                FeeScheds.CopyFeeSchedule(feeSchedFrom, 0, 0, feeSchedTo, null, 0);
            });

            //Mimic each user clicking the "Copy" button from within the Fee Tools window one right after the other (before they click OK).
            actionCopyFromTo();
            actionCopyFromTo();
            //Make sure that there was NOT a duplicate fee inserted into the database.
            dbmResult = DatabaseMaintenances.FeeDeleteDuplicates(true, DbmMode.Check);
            Assert.AreEqual(dbmResult.Trim(), _feeDeleteDuplicatesExpectedResult, "Duplicate fees detected due to concurrent copying.");
        }
 ///<summary>Tries to log the text passed in to a centralized DBM log.  Displays an error message to the user if anything goes wrong.
 ///Always sets the current Cursor state back to Cursors.Default once finished.</summary>
 private void SaveLogToFile(string logText)
 {
     try {
         DatabaseMaintenances.SaveLogToFile(logText);
     }
     catch (Exception ex) {
         Cursor = Cursors.Default;
         MessageBox.Show(ex.Message);
     }
     Cursor = Cursors.Default;
 }
示例#7
0
        private void FillDatabaseNames()
        {
            comboDbs.Items.Clear();
            List <string> dbNames = DatabaseMaintenances.GetDatabaseNames();

            for (int i = 0; i < dbNames.Count; i++)
            {
                comboDbs.Items.Add(dbNames[i]);
            }
            //automatic selection will come later.
        }
示例#8
0
 private void butRun_Click(object sender, EventArgs e)
 {
     if (comboDbs.SelectedIndex == -1)
     {
         MsgBox.Show(this, "Please select a backup database first.");
         return;
     }
     //make sure it's not this database
     if (comboDbs.SelectedItem.ToString() == MiscData.GetCurrentDatabase())
     {
         MsgBox.Show(this, "Please choose a database other than the current database.");
         return;
     }
     //make sure it's from before March 17th.
     //if(!DatabaseMaintenance.DatabaseIsOlderThanMarchSeventeenth(comboDbs.SelectedItem.ToString())){
     //	MsgBox.Show(this,"The backup database must be older than March 17, 2010.");
     //	return;
     //}
     Cursor                 = Cursors.WaitCursor;
     textResults.Text       = "";
     duplicateClaimProcInfo = DatabaseMaintenances.GetDuplicateClaimProcs();
     if (duplicateClaimProcInfo == "")
     {
         textResults.Text += "Duplicate claim payments: None found.  Database OK.\r\n\r\n";
     }
     else
     {
         textResults.Text += duplicateClaimProcInfo;
     }
     duplicateSuppInfo = DatabaseMaintenances.GetDuplicateSupplementalPayments();
     if (duplicateSuppInfo == "")
     {
         textResults.Text += "Duplicate supplemental payments: None found.  Database OK.\r\n\r\n";
     }
     else
     {
         textResults.Text += duplicateSuppInfo;
     }
     missingSuppInfo = DatabaseMaintenances.GetMissingClaimProcs(comboDbs.SelectedItem.ToString());
     if (missingSuppInfo == "")
     {
         textResults.Text += "Missing claim payments: None found.  Database OK.";
     }
     else
     {
         textResults.Text += missingSuppInfo;
     }
     Cursor = Cursors.Default;
 }
        private void FormDatabaseMaintenancePat_Load(object sender, EventArgs e)
        {
            //Get all patient specific DBM methods via reflection.
            _listDbmMethodInfos = DatabaseMaintenances.GetMethodsForDisplay(Clinics.ClinicNum, true);
            List <string> listPatDbmMethodNames = _listDbmMethodInfos.Select(x => x.Name).ToList();

            //Add any missing patient specific DBM methods to the database that are not currently present.
            DatabaseMaintenances.InsertMissingDBMs(listPatDbmMethodNames);
            //Get the DatabaseMaintenance objects from the db for all patient specific methods.  Need this for hidden and old grids.
            //Filtering on the method names list removes any non-patient specific DBM methods
            _listDatabaseMaintenances = DatabaseMaintenances.GetAll().FindAll(x => x.MethodName.In(listPatDbmMethodNames));
            UpdateTextPatient();
            FillGrid();
            FillGridOld();
            FillGridHidden();
        }
 ///<summary>Updates the result column for the specified row in gridMain with the text passed in.</summary>
 private void UpdateResultTextForRow(int index, string text)
 {
     gridMain.BeginUpdate();
     //Checks to see if it has a breakdown, and if it needs any maintenenece to decide whether or not to apply the "X"
     if (!DatabaseMaintenances.MethodHasBreakDown(_listDbmMethodsGrid[index]) || text == "Done.  No maintenance needed.")
     {
         gridMain.Rows[index].Cells[1].Text = "";
     }
     else
     {
         gridMain.Rows[index].Cells[1].Text = "X";
     }
     gridMain.Rows[index].Cells[2].Text = text;
     gridMain.EndUpdate();
     Application.DoEvents();
 }
        ///<summary>Updates the result column for the specified row in the grid with the text passed in.</summary>
        private void UpdateResultTextForRow(int index, string text, ODGrid gridCur)
        {
            int breakdownIndex = gridCur.ListGridColumns.GetIndex(BREAKDOWN_COLUMN_NAME);
            int resultsIndex   = gridCur.ListGridColumns.GetIndex(RESULTS_COLUMN_NAME);

            gridCur.BeginUpdate();
            //Checks to see if it has a breakdown, and if it needs any maintenance to decide whether or not to apply the "X"
            if (!DatabaseMaintenances.MethodHasBreakDown((MethodInfo)gridCur.ListGridRows[index].Tag) || text == "Done.  No maintenance needed.")
            {
                gridCur.ListGridRows[index].Cells[breakdownIndex].Text = "";
            }
            else
            {
                gridCur.ListGridRows[index].Cells[breakdownIndex].Text = "X";
            }
            gridCur.ListGridRows[index].Cells[resultsIndex].Text = text;
            gridCur.EndUpdate();
            Application.DoEvents();
        }
        private void gridMain_CellDoubleClick(object sender, ODGridClickEventArgs e)
        {
            MethodInfo method = _listDbmMethodsGrid[e.Row];

            if (!DatabaseMaintenances.MethodHasBreakDown(method))
            {
                return;
            }
            //We know that this method supports giving the user a break down and shall call the method's fix section where the break down results should be.
            //TODO: Make sure that DBM methods with break downs ALWAYS have the break down in the fix section.
            if (_patNum < 1)
            {
                MsgBox.Show(this, "Select a patient first.");
                return;
            }
            DbmMethodAttr methodAttributes = (DbmMethodAttr)Attribute.GetCustomAttribute(method, typeof(DbmMethodAttr));
            //We always send verbose and modeCur into all DBM methods.
            List <object> parameters = new List <object>()
            {
                checkShow.Checked, DbmMode.Breakdown
            };

            //There are optional paramaters available to some methods and adding them in the following order is very important.
            if (methodAttributes.HasPatNum)
            {
                parameters.Add(_patNum);
            }
            Cursor = Cursors.WaitCursor;
            string result = (string)method.Invoke(null, parameters.ToArray());

            if (result == "")           //Only possible if running a check / fix in non-verbose mode and nothing happened or needs to happen.
            {
                result = Lan.g("FormDatabaseMaintenance", "Done.  No maintenance needed.");
            }
            SaveLogToFile(method.Name + ":\r\n" + result);
            //Show the result of the dbm method in a simple copy paste msg box.
            MsgBoxCopyPaste msgBoxCP = new MsgBoxCopyPaste(result);

            Cursor = Cursors.Default;
            msgBoxCP.Show();            //Let this window be non-modal so that they can keep it open while they fix their problems.
        }
        private void FillGrid()
        {
            gridMain.BeginUpdate();
            gridMain.Columns.Clear();
            gridMain.Columns.Add(new ODGridColumn(Lan.g(this, "Name"), 300));
            gridMain.Columns.Add(new ODGridColumn(Lan.g(this, "Break\r\nDown"), 40, HorizontalAlignment.Center));
            gridMain.Columns.Add(new ODGridColumn(Lan.g(this, "Results"), 0));
            gridMain.Rows.Clear();
            ODGridRow row;

            //_listDbmMethodsGrid has already been filled on load with the correct methods to display in the grid.
            foreach (MethodInfo meth in _listDbmMethodsGrid)
            {
                row = new ODGridRow();
                row.Cells.Add(meth.Name);
                row.Cells.Add(DatabaseMaintenances.MethodHasBreakDown(meth) ? "X" : "");
                row.Cells.Add("");
                gridMain.Rows.Add(row);
            }
            gridMain.EndUpdate();
        }
        private void FillGrid()
        {
            _listDbmMethodsGrid = DbmMethodsForGridHelper(isHidden: false, isOld: false);
            gridMain.BeginUpdate();
            gridMain.ListGridColumns.Clear();
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g(this, "Name"), 300));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g(this, BREAKDOWN_COLUMN_NAME), 40, HorizontalAlignment.Center));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g(this, RESULTS_COLUMN_NAME), 0));
            gridMain.ListGridRows.Clear();
            GridRow row;

            //_listDbmMethodsGrid has already been filled on load with the correct methods to display in the grid.
            foreach (MethodInfo meth in _listDbmMethodsGrid)
            {
                row = new GridRow();
                row.Cells.Add(meth.Name);
                row.Cells.Add(DatabaseMaintenances.MethodHasBreakDown(meth) ? "X" : "");
                row.Cells.Add("");
                row.Tag = meth;
                gridMain.ListGridRows.Add(row);
            }
            gridMain.EndUpdate();
        }
        private void Run(ODGrid gridCur, DbmMode modeCur)
        {
            if (_patNum < 1)
            {
                MsgBox.Show(this, "Select a patient first.");
                return;
            }
            Cursor = Cursors.WaitCursor;
            //Clear out the result column for all rows before every "run"
            for (int i = 0; i < gridCur.ListGridRows.Count; i++)
            {
                //gridMain and gridOld have a different number of columns, but their matching columns will be named the same.
                gridCur.ListGridRows[i].Cells[gridCur.ListGridColumns.GetIndex(RESULTS_COLUMN_NAME)].Text = "";              //Don't use UpdateResultTextForRow here because users will see the rows clearing out one by one.
            }
            bool          verbose = checkShow.Checked;
            StringBuilder logText = new StringBuilder();

            //No longer uses a pre-check for tables.
            if (gridCur.SelectedIndices.Length < 1)
            {
                //No rows are selected so the user wants to run all checks.
                gridCur.SetSelected(true);
            }
            string result;

            int[] selectedIndices = gridCur.SelectedIndices;
            for (int i = 0; i < gridCur.SelectedGridRows.Count; i++)
            {
                DbmMethodAttr methodAttributes = (DbmMethodAttr)Attribute.GetCustomAttribute((MethodInfo)gridCur.SelectedGridRows[i].Tag, typeof(DbmMethodAttr));
                //We always send verbose and modeCur into all DBM methods.
                List <object> parameters = new List <object>()
                {
                    verbose, modeCur
                };
                //There are optional paramaters available to some methods and adding them in the following order is very important.
                if (methodAttributes.HasPatNum)
                {
                    parameters.Add(_patNum);
                }

                try {
                    gridCur.ScrollToIndexBottom(i);
                    UpdateResultTextForRow(i, Lan.g("FormDatabaseMaintenance", "Running") + "...", gridCur);
                    gridCur.SetSelected(selectedIndices, true);                   //Reselect all rows that were originally selected.
                    result = (string)((MethodInfo)gridCur.SelectedGridRows[i].Tag).Invoke(null, parameters.ToArray());
                    if (modeCur == DbmMode.Fix)
                    {
                        DatabaseMaintenances.UpdateDateLastRun(((MethodInfo)gridCur.SelectedGridRows[i].Tag).Name);
                    }
                }
                catch (Exception ex) {
                    if (ex.InnerException != null)
                    {
                        ExceptionDispatchInfo.Capture(ex.InnerException).Throw();                        //This preserves the stack trace of the InnerException.
                    }
                    throw;
                }
                string status = "";
                if (result == "")               //Only possible if running a check / fix in non-verbose mode and nothing happened or needs to happen.
                {
                    status = Lan.g("FormDatabaseMaintenance", "Done.  No maintenance needed.");
                }
                UpdateResultTextForRow(i, result + status, gridCur);
                logText.Append(result);
            }
            gridCur.SetSelected(selectedIndices, true);           //Reselect all rows that were originally selected.
            SaveLogToFile(logText.ToString());
            if (modeCur == DbmMode.Fix)
            {
                //_isCacheInvalid=true;//Flag cache to be invalidated on closing.  Some DBM fixes alter cached tables.
            }
        }
示例#16
0
        ///<summary>Return false to indicate exit app.  Only called when program first starts up at the beginning of FormOpenDental.PrefsStartup.</summary>
        public bool Convert(string fromVersion, string toVersion, bool isSilent, Form currentForm = null)
        {
            FromVersion = new Version(fromVersion);
            ToVersion   = new Version(toVersion);        //Application.ProductVersion);
            if (FromVersion >= new Version("3.4.0") && PrefC.GetBool(PrefName.CorruptedDatabase))
            {
                FormOpenDental.ExitCode = 201;              //Database was corrupted due to an update failure
                if (!isSilent)
                {
                    MsgBox.Show(this, "Your database is corrupted because an update failed.  Please contact us.  This database is unusable and you will need to restore from a backup.");
                }
                return(false);               //shuts program down.
            }
            if (FromVersion == ToVersion)
            {
                return(true);                         //no conversion necessary
            }
            if (FromVersion.CompareTo(ToVersion) > 0) //"Cannot convert database to an older version."
            //no longer necessary to catch it here.  It will be handled soon enough in CheckProgramVersion
            {
                return(true);
            }
            if (FromVersion < new Version("2.8.0"))
            {
                FormOpenDental.ExitCode = 130;              //Database must be upgraded to 2.8 to continue
                if (!isSilent)
                {
                    MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 2.1 if necessary, then to 2.8.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                }
                return(false);
            }
            if (FromVersion < new Version("6.6.2"))
            {
                FormOpenDental.ExitCode = 131;              //Database must be upgraded to 11.1 to continue
                if (!isSilent)
                {
                    MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 11.1 first.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                }
                return(false);
            }
            if (FromVersion < new Version("3.0.1"))
            {
                if (!isSilent)
                {
                    MsgBox.Show(this, "This is an old database.  The conversion must be done using MySQL 4.1 (not MySQL 5.0) or it will fail.");
                }
            }
            if (FromVersion.ToString() == "2.9.0.0" || FromVersion.ToString() == "3.0.0.0" || FromVersion.ToString() == "4.7.0.0")
            {
                FormOpenDental.ExitCode = 190;              //Cannot convert this database version which was only for development purposes
                if (!isSilent)
                {
                    MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                }
                return(false);
            }
            if (FromVersion > new Version("4.7.0") && FromVersion.Build == 0)
            {
                FormOpenDental.ExitCode = 190;              //Cannot convert this database version which was only for development purposes
                if (!isSilent)
                {
                    MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                }
                return(false);
            }
            if (FromVersion >= LatestVersion)
            {
                return(true);               //no conversion necessary
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                FormOpenDental.ExitCode = 140;              //Web client cannot convert database
                if (!isSilent)
                {
                    MsgBox.Show(this, "Web client cannot convert database.  Must be using a direct connection.");
                }
                return(false);
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                FormOpenDental.ExitCode = 150;              //Replication server is blocked from performing updates
                if (!isSilent)
                {
                    MsgBox.Show(this, "This replication server is blocked from performing updates.");
                }
                return(false);
            }
#if TRIALONLY
            //Trial users should never be able to update a database.
            if (PrefC.GetString(PrefName.RegistrationKey) != "") //Allow databases with no reg key to update.  Needed by our conversion department.
            {
                FormOpenDental.ExitCode = 191;                   //Trial versions cannot connect to live databases
                if (!isSilent)
                {
                    MsgBox.Show(this, "Trial versions cannot connect to live databases.  Please run the Setup.exe in the AtoZ folder to reinstall your original version.");
                }
                return(false);
            }
#endif
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                   //and not on web server
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 141;   //Updates are only allowed from a designated web server
                    return(false);                   //if you are in debug mode and you really need to update the DB, you can manually clear the WebServiceServerName preference.
                }
                //This will be handled in CheckProgramVersion, giving the user option to downgrade or exit program.
                return(true);
            }
            //If MyISAM and InnoDb mix, then try to fix
            if (DataConnection.DBtype == DatabaseType.MySql)           //not for Oracle
            {
                string namesInnodb = InnoDb.GetInnodbTableNames();     //Or possibly some other format.
                int    numMyisam   = DatabaseMaintenances.GetMyisamTableCount();
                if (namesInnodb != "" && numMyisam > 0)
                {
                    if (!isSilent)
                    {
                        MessageBox.Show(Lan.g(this, "A mixture of database tables in InnoDB and MyISAM format were found.  A database backup will now be made, and then the following InnoDB tables will be converted to MyISAM format: ") + namesInnodb);
                    }
                    if (!Shared.MakeABackup(isSilent, BackupLocation.ConvertScript, false))
                    {
                        Cursor.Current          = Cursors.Default;
                        FormOpenDental.ExitCode = 101;                      //Database Backup failed
                        return(false);
                    }
                    if (!DatabaseMaintenances.ConvertTablesToMyisam())
                    {
                        FormOpenDental.ExitCode = 102;                      //Failed to convert InnoDB tables to MyISAM format
                        if (!isSilent)
                        {
                            MessageBox.Show(Lan.g(this, "Failed to convert InnoDB tables to MyISAM format. Please contact support."));
                        }
                        return(false);
                    }
                    if (!isSilent)
                    {
                        MessageBox.Show(Lan.g(this, "All tables converted to MyISAM format successfully."));
                    }
                    namesInnodb = "";
                }
                if (namesInnodb == "" && numMyisam > 0)             //if all tables are myisam
                //but default storage engine is innodb, then kick them out.
                {
                    if (DatabaseMaintenances.GetStorageEngineDefaultName().ToUpper() != "MYISAM") //Probably InnoDB but could be another format.
                    {
                        FormOpenDental.ExitCode = 103;                                            //Default database .ini setting is innoDB
                        if (!isSilent)
                        {
                            MessageBox.Show(Lan.g(this, "The database tables are in MyISAM format, but the default database engine format is InnoDB. You must change the default storage engine within the my.ini (or my.cnf) file on the database server and restart MySQL in order to fix this problem. Exiting."));
                        }
                        return(false);
                    }
                }
            }
#if DEBUG
            if (!isSilent && MessageBox.Show("You are in Debug mode.  Your database can now be converted" + "\r"
                                             + "from version" + " " + FromVersion.ToString() + "\r"
                                             + "to version" + " " + ToVersion.ToString() + "\r"
                                             + "You can click Cancel to skip conversion and attempt to run the newer code against the older database."
                                             , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(true);               //If user clicks cancel, then do nothing
            }
#else
            if (!isSilent && MessageBox.Show(Lan.g(this, "Your database will now be converted") + "\r"
                                             + Lan.g(this, "from version") + " " + FromVersion.ToString() + "\r"
                                             + Lan.g(this, "to version") + " " + ToVersion.ToString() + "\r"
                                             + Lan.g(this, "The conversion works best if you are on the server.  Depending on the speed of your computer, it can be as fast as a few seconds, or it can take as long as 10 minutes.")
                                             , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(false);               //If user clicks cancel, then close the program
            }
#endif
            Cursor.Current = Cursors.WaitCursor;
            Action actionCloseConvertProgress = null;
#if !DEBUG
            if (!isSilent)
            {
                if (DataConnection.DBtype != DatabaseType.MySql &&
                    !MsgBox.Show(this, true, "If you have not made a backup, please Cancel and backup before continuing.  Continue?"))
                {
                    return(false);
                }
            }
            if (DataConnection.DBtype == DatabaseType.MySql)
            {
                if (!Shared.MakeABackup(isSilent, BackupLocation.ConvertScript, false))
                {
                    Cursor.Current          = Cursors.Default;
                    FormOpenDental.ExitCode = 101;                  //Database Backup failed
                    return(false);
                }
            }
            //We've been getting an increasing number of phone calls with databases that have duplicate preferences which is impossible
            //unless a user has gotten this far and another computer in the office is in the middle of an update as well.
            //The issue is most likely due to the blocking messageboxes above which wait indefinitely for user input right before upgrading the database.
            //This means that the cache for this computer could be stale and we need to manually refresh our cache to double check
            //that the database isn't flagged as corrupt, an update isn't in progress, or that the database version hasn't changed (someone successfully updated already).
            Prefs.RefreshCache();
            //Now check the preferences that should stop this computer from executing an update.
            if (PrefC.GetBool(PrefName.CorruptedDatabase) ||
                (PrefC.GetString(PrefName.UpdateInProgressOnComputerName) != "" && PrefC.GetString(PrefName.UpdateInProgressOnComputerName) != Environment.MachineName))
            {
                //At this point, the pref "corrupted database" being true means that a computer is in the middle of running the upgrade script.
                //There will be another corrupted database check on start up which will take care of the scenario where this is truly a corrupted database.
                //Also, we need to make sure that the update in progress preference is set to this computer because we JUST set it to that value before entering this method.
                //If it has changed, we absolutely know without a doubt that another computer is trying to update at the same time.
                FormOpenDental.ExitCode = 142;              //Update is already in progress from another computer
                if (!isSilent)
                {
                    MsgBox.Show(this, "An update is already in progress from another computer.");
                }
                return(false);
            }
            //Double check that the database version has not changed.  This check is here just in case another computer has successfully updated the database already.
            Version versionDatabase = new Version(PrefC.GetString(PrefName.DataBaseVersion));
            if (FromVersion != versionDatabase)
            {
                FormOpenDental.ExitCode = 143;              //Database has already been updated from another computer
                if (!isSilent)
                {
                    MsgBox.Show(this, "The database has already been updated from another computer.");
                }
                return(false);
            }
            try {
#endif
            if (FromVersion < new Version("7.5.17"))                     //Insurance Plan schema conversion
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 139;                          //Update must be done manually to fix Insurance Plan Schema
                    Application.Exit();
                    return(false);
                }
                Cursor.Current = Cursors.Default;
                YN InsPlanConverstion_7_5_17_AutoMergeYN = YN.Unknown;
                if (FromVersion < new Version("7.5.1"))
                {
                    FormInsPlanConvert_7_5_17 form = new FormInsPlanConvert_7_5_17();
                    if (PrefC.GetBoolSilent(PrefName.InsurancePlansShared, true))
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.Yes;
                    }
                    else
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.No;
                    }
                    form.ShowDialog();
                    if (form.DialogResult == DialogResult.Cancel)
                    {
                        MessageBox.Show("Your database has not been altered.");
                        return(false);
                    }
                    InsPlanConverstion_7_5_17_AutoMergeYN = form.InsPlanConverstion_7_5_17_AutoMergeYN;
                }
                ConvertDatabases.Set_7_5_17_AutoMerge(InsPlanConverstion_7_5_17_AutoMergeYN);                        //does nothing if this pref is already present for some reason.
                Cursor.Current = Cursors.WaitCursor;
            }
            if (!isSilent && FromVersion > new Version("16.3.0") && FromVersion < new Version("16.3.29") && ApptReminderRules.IsReminders)
            {
                //16.3.29 is more strict about reminder rule setup. Prompt the user and allow them to exit the update if desired.
                //Get all currently enabled reminder rules.
                List <bool> listReminderFlags = ApptReminderRules.Get_16_3_29_ConversionFlags();
                if (listReminderFlags?[0] ?? false)                        //2 reminders scheduled for same day of appointment. 1 will be converted to future day reminder.
                {
                    MsgBox.Show(this, "You have multiple appointment reminders set to send on the same day of the appointment. One of these will be converted to send 1 day prior to the appointment.  Please review automated reminder rule setup after update has finished.");
                }
                if (listReminderFlags?[1] ?? false)                        //2 reminders scheduled for future day of appointment. 1 will be converted to same day reminder.
                {
                    MsgBox.Show(this, "You have multiple appointment reminders set to send 1 or more days prior to the day of the appointment. One of these will be converted to send 1 hour prior to the appointment.  Please review automated reminder rule setup after update has finished.");
                }
            }
            if (FromVersion >= new Version("17.3.1") && FromVersion < new Version("17.3.23") && DataConnection.DBtype == DatabaseType.MySql &&
                (Tasks.HasAnyLongDescripts() || TaskNotes.HasAnyLongNotes() || Commlogs.HasAnyLongNotes()))
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 138;                          //Update must be done manually in order to get data loss notification(s).
                    Application.Exit();
                    return(false);
                }
                if (!MsgBox.Show(this, true, "Data will be lost during this update."
                                 + "\r\nContact support in order to retrieve the data from a backup after the update."
                                 + "\r\n\r\nContinue?"))
                {
                    MessageBox.Show("Your database has not been altered.");
                    return(false);
                }
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, true);
            }
            ConvertDatabases.FromVersion = FromVersion;
#if !DEBUG
            //Typically the UpdateInProgressOnComputerName preference will have already been set within FormUpdate.
            //However, the user could have cancelled out of FormUpdate after successfully downloading the Setup.exe
            //OR the Setup.exe could have been manually sent to our customer (during troubleshooting with HQ).
            //For those scenarios, the preference will be empty at this point and we need to let other computers know that an update going to start.
            //Updating the string (again) here will guarantee that all computers know an update is in fact in progress from this machine.
            Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName, Environment.MachineName);
#endif
            //Show a progress window that will indecate to the user that there is an active update in progress.  Currently okay to show during isSilent.
            actionCloseConvertProgress = ODProgressOld.ShowProgressStatus("ConvertDatabases", hasMinimize: false, currentForm: currentForm);
            ConvertDatabases.To2_8_2();                //begins going through the chain of conversion steps
            InvokeConvertMethods();                    //continues going through the chain of conversion steps starting at v17.1.1 via reflection.
            actionCloseConvertProgress();
            Cursor.Current = Cursors.Default;
            if (FromVersion >= new Version("3.4.0"))
            {
                //CacheL.Refresh(InvalidType.Prefs);//or it won't know it has to update in the next line.
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false, true);                      //more forceful refresh in order to properly change flag
            }
            Cache.Refresh(InvalidType.Prefs);
            if (!isSilent)
            {
                MsgBox.Show(this, "Database update successful");
            }
            return(true);

#if !DEBUG
        }

        catch (System.IO.FileNotFoundException e) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 160;                  //File not found exception
            if (!isSilent)
            {
                MessageBox.Show(e.FileName + " " + Lan.g(this, "could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            return(false);
        }
        catch (System.IO.DirectoryNotFoundException) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 160;                  //ConversionFiles folder could not be found
            if (!isSilent)
            {
                MessageBox.Show(Lan.g(this, "ConversionFiles folder could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            return(false);
        }
        catch (Exception ex) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 201;                  //Database was corrupted due to an update failure
            if (!isSilent)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n"
                                + Lan.g(this, "Conversion unsuccessful. Your database is now corrupted and you cannot use it.  Please contact us."));
            }
            //Then, application will exit, and database will remain tagged as corrupted.
            return(false);
        }
#endif
        }
示例#17
0
 private void butFix3_Click(object sender, EventArgs e)
 {
     Cursor           = Cursors.WaitCursor;
     textResults.Text = DatabaseMaintenances.FixMissingClaimProcs(comboDbs.SelectedItem.ToString());
     Cursor           = Cursors.Default;
 }
示例#18
0
 private void butFix1_Click(object sender, EventArgs e)
 {
     Cursor           = Cursors.WaitCursor;
     textResults.Text = DatabaseMaintenances.FixClaimProcDeleteDuplicates();
     Cursor           = Cursors.Default;
 }
        private void Run(DbmMode modeCur)
        {
            if (_patNum < 1)
            {
                MsgBox.Show(this, "Select a patient first.");
                return;
            }
            Cursor = Cursors.WaitCursor;
            //Clear out the result column for all rows before every "run"
            for (int i = 0; i < gridMain.Rows.Count; i++)
            {
                gridMain.Rows[i].Cells[2].Text = "";              //Don't use UpdateResultTextForRow here because users will see the rows clearing out one by one.
            }
            bool          verbose = checkShow.Checked;
            StringBuilder logText = new StringBuilder();
            //Create a thread that will show a window and then stay open until the closing phrase is thrown from this form.
            Action actionCloseCheckTableProgress    = ODProgressOld.ShowProgressStatus("CheckTableProgress", this);
            ODTuple <string, bool> tableCheckResult = DatabaseMaintenances.MySQLTables(verbose, modeCur);

            actionCloseCheckTableProgress();
            logText.Append(tableCheckResult.Item1);
            //No database maintenance methods should be run unless this passes.
            if (!tableCheckResult.Item2)
            {
                Cursor = Cursors.Default;
                MsgBoxCopyPaste msgBoxCP = new MsgBoxCopyPaste(tableCheckResult.Item1); //the Tuples result is already translated.
                msgBoxCP.Show();                                                        //Let this window be non-modal so that they can keep it open while they fix their problems.
                return;
            }
            if (gridMain.SelectedIndices.Length < 1)
            {
                //No rows are selected so the user wants to run all checks.
                gridMain.SetSelected(true);
            }
            string result;

            int[] selectedIndices = gridMain.SelectedIndices;
            for (int i = 0; i < selectedIndices.Length; i++)
            {
                long          userNum          = 0;
                DbmMethodAttr methodAttributes = (DbmMethodAttr)Attribute.GetCustomAttribute(_listDbmMethodsGrid[selectedIndices[i]], typeof(DbmMethodAttr));
                //We always send verbose and modeCur into all DBM methods.
                List <object> parameters = new List <object>()
                {
                    verbose, modeCur
                };
                //There are optional paramaters available to some methods and adding them in the following order is very important.
                if (methodAttributes.HasUserNum)
                {
                    parameters.Add(userNum);
                }
                if (methodAttributes.HasPatNum)
                {
                    parameters.Add(_patNum);
                }
                gridMain.ScrollToIndexBottom(selectedIndices[i]);
                UpdateResultTextForRow(selectedIndices[i], Lan.g("FormDatabaseMaintenance", "Running") + "...");
                try {
                    result = (string)_listDbmMethodsGrid[selectedIndices[i]].Invoke(null, parameters.ToArray());
                    if (modeCur == DbmMode.Fix)
                    {
                        DatabaseMaintenances.UpdateDateLastRun(_listDbmMethodsGrid[selectedIndices[i]].Name);
                    }
                }
                catch (Exception ex) {
                    if (ex.InnerException != null)
                    {
                        ExceptionDispatchInfo.Capture(ex.InnerException).Throw();                        //This preserves the stack trace of the InnerException.
                    }
                    throw;
                }
                string status = "";
                if (result == "")               //Only possible if running a check / fix in non-verbose mode and nothing happened or needs to happen.
                {
                    status = Lan.g("FormDatabaseMaintenance", "Done.  No maintenance needed.");
                }
                UpdateResultTextForRow(selectedIndices[i], result + status);
                logText.Append(result);
            }
            gridMain.SetSelected(selectedIndices, true);           //Reselect all rows that were originally selected.
            try {
                DatabaseMaintenances.SaveLogToFile(logText.ToString());
            }
            catch (Exception ex) {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message);
            }
            Cursor = Cursors.Default;
            if (modeCur == DbmMode.Fix)
            {
                //_isCacheInvalid=true;//Flag cache to be invalidated on closing.  Some DBM fixes alter cached tables.
            }
        }