Example #1
0
        ///<summary>The main logic that sends Podium invitations.  Set isService true only when the calling method is the Open Dental Service.</summary>
        public static void ThreadPodiumSendInvitations(bool isService)
        {
            long programNum = Programs.GetProgramNum(ProgramName.Podium);

            //Consider blocking re-entrance if this hasn't finished.
            //Only send invitations if the program link is enabled, the computer name is set to this computer, and eConnector is not set to send invitations
            if (!Programs.IsEnabled(ProgramName.Podium) ||
                !ODEnvironment.IdIsThisComputer(ProgramProperties.GetPropVal(programNum, PropertyDescs.ComputerNameOrIP)) ||
                ProgramProperties.GetPropVal(programNum, PropertyDescs.UseService) != POut.Bool(isService))
            {
                return;
            }
            //Keep a consistant "Now" timestamp throughout this method.
            DateTime nowDT = MiscData.GetNowDateTime();

            if (Podium.DateTimeLastRan == DateTime.MinValue)           //First time running the thread.
            {
                Podium.DateTimeLastRan = nowDT.AddMilliseconds(-PodiumThreadIntervalMS);
            }
            ReviewInvitationTrigger newPatTrigger      = PIn.Enum <ReviewInvitationTrigger>(ProgramProperties.GetPropVal(programNum, PropertyDescs.NewPatientTriggerType));
            ReviewInvitationTrigger existingPatTrigger = PIn.Enum <ReviewInvitationTrigger>(ProgramProperties.GetPropVal(programNum, PropertyDescs.ExistingPatientTriggerType));
            List <Appointment>      listNewPatAppts    = GetAppointmentsToSendReview(newPatTrigger, programNum, true);

            foreach (Appointment apptCur in listNewPatAppts)
            {
                Podium.SendData(Patients.GetPat(apptCur.PatNum), apptCur.ClinicNum);
            }
            List <Appointment> listExistingPatAppts = GetAppointmentsToSendReview(existingPatTrigger, programNum, false);

            foreach (Appointment apptCur in listExistingPatAppts)
            {
                Podium.SendData(Patients.GetPat(apptCur.PatNum), apptCur.ClinicNum);
            }
            Podium.DateTimeLastRan = nowDT;
        }
Example #2
0
        private void butInstallEConnector_Click(object sender, EventArgs e)
        {
            DialogResult result;
            //Check to see if the update server preference is set.
            //If set, make sure that this is set to the computer currently logged on.
            string updateServerName = PrefC.GetString(PrefName.WebServiceServerName);

            if (!string.IsNullOrEmpty(updateServerName) && !ODEnvironment.IdIsThisComputer(updateServerName.ToLower()))
            {
                result = MessageBox.Show(Lan.g(this, "The eConnector service should be installed on the Update Server") + ": " + updateServerName + "\r\n"
                                         + Lan.g(this, "Are you trying to install the eConnector on a different computer by accident?"), "", MessageBoxButtons.YesNoCancel);
                //Only saying No to this message box pop up will allow the user to continue (meaning they fully understand what they are getting into).
                if (result != DialogResult.No)
                {
                    return;
                }
            }
            //Only ask the user if they want to set the Update Server Name preference if it is not already set.
            if (string.IsNullOrEmpty(updateServerName))
            {
                result = MessageBox.Show(Lan.g(this, "The computer that has the eConnector service installed should be set as the Update Server.") + "\r\n"
                                         + Lan.g(this, "Would you like to make this computer the Update Server?"), "", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Cancel)
                {
                    return;
                }
                else if (result == DialogResult.Yes)
                {
                    Prefs.UpdateString(PrefName.WebServiceServerName, Dns.GetHostName());
                }
                try {
                    WebServiceMainHQProxy.SetEConnectorOn();
                }
                catch {
                    MsgBox.Show(this, "The eConnector was disabled.  Please contact support.");
                    return;
                }
            }
            //At this point the user wants to install the eConnector service (or upgrade the old cust listener to the eConnector).
            bool isListening;

            if (!PrefL.UpgradeOrInstallEConnector(false, out isListening))
            {
                //Warning messages would have already been shown to the user, simply return.
                return;
            }
            //The eConnector service was successfully installed and is running, set the EConnectorEnabled flag true if false.
            Prefs.UpdateBool(PrefName.EConnectorEnabled, true);
            MsgBox.Show(this, "eConnector successfully installed");
            butInstallEConnector.Enabled = false;
            FillTextListenerServiceStatus();
            FillGridListenerService();
        }
Example #3
0
        public void DataAction_WebChat_Override()
        {
            SiteT.ClearSiteTable();
            SiteLinkT.ClearSiteLinkTable();
            Site     site     = SiteT.CreateSite(MethodBase.GetCurrentMethod().Name);
            SiteLink siteLink = SiteLinkT.CreateSiteLink(site.SiteNum,
                                                         octetStart: ODEnvironment.GetLocalIPAddress(),
                                                         connectionSettingsHQOverrides: GetJsonSerializedConnectionOverride(ConnectionNames.WebChat, "127.0.0.1", _databaseNameWebChat, "root", ""));
            string serverName = "";

            DataAction.RunWebChat(() => { serverName = DataConnection.GetServerName(); });
            Assert.AreEqual("127.0.0.1", serverName);
            Assert.AreNotEqual(_dictConnectionDefaults[ConnectionNames.WebChat].ServerName, serverName);
        }
Example #4
0
        private void butCheckForUpdates_Click(object sender, EventArgs e)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                MsgBox.Show(this, "Updates are only allowed from the web server");
                return;
            }
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                  //and not on web server
            {
                MessageBox.Show(Lan.g(this, "Updates are only allowed from the web server") + ": " + PrefC.GetString(PrefName.WebServiceServerName));
                return;
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                MsgBox.Show(this, "Updates are not allowed on this replication server");
                return;
            }
            Cursor                     = Cursors.WaitCursor;
            groupBuild.Visible         = false;
            groupStable.Visible        = false;
            groupBeta.Visible          = false;
            groupAlpha.Visible         = false;
            textConnectionMessage.Text = Lan.g(this, "Attempting to connect to web service......");
            Application.DoEvents();
            string result = "";

            try {
                result = CustomerUpdatesProxy.SendAndReceiveUpdateRequestXml();
            }
            catch (Exception ex) {
                Cursor = Cursors.Default;
                string friendlyMessage = Lan.g(this, "Error checking for updates.");
                FriendlyException.Show(friendlyMessage, ex);
                textConnectionMessage.Text = friendlyMessage;
                return;
            }
            textConnectionMessage.Text = Lan.g(this, "Connection successful.");
            Cursor = Cursors.Default;
            try {
                ParseXml(result);
            }
            catch (Exception ex) {
                string friendlyMessage = Lan.g(this, "Error checking for updates.");
                FriendlyException.Show(friendlyMessage, ex);
                textConnectionMessage.Text = friendlyMessage;
                return;
            }
            if (!string.IsNullOrEmpty(_buildAvailableDisplay))
            {
                groupBuild.Visible = true;
                textBuild.Text     = _buildAvailableDisplay;
            }
            if (!string.IsNullOrEmpty(_stableAvailableDisplay))
            {
                groupStable.Visible = true;
                textStable.Text     = _stableAvailableDisplay;
            }
            if (!string.IsNullOrEmpty(_betaAvailableDisplay))
            {
                groupBeta.Visible = true;
                textBeta.Text     = _betaAvailableDisplay;
            }
            if (!string.IsNullOrEmpty(_alphaAvailableDisplay))
            {
                groupAlpha.Visible = true;
                textAlpha.Text     = _alphaAvailableDisplay;
            }
            if (string.IsNullOrEmpty(_betaAvailable) &&
                string.IsNullOrEmpty(_stableAvailable) &&
                string.IsNullOrEmpty(_buildAvailable) &&
                string.IsNullOrEmpty(_alphaAvailable))
            {
                textConnectionMessage.Text += Lan.g(this, "  There are no downloads available.");
            }
            else
            {
                textConnectionMessage.Text += Lan.g(this, "  The following downloads are available.\r\n"
                                                    + "Be sure to stop the program on all other computers in the office before installing.");
            }
        }
        ///<summary>Send a summary of eConnector statistics to OD HQ. This should only be called from the eConnector.</summary>
        public static void UpdateEConnectorStats()
        {
            EConnectorStatistics eConnStats = new EConnectorStatistics()
            {
                ListEServiceSignals = new List <EServiceSignal>(),
                ListEServicePrefs   = new List <Pref>(),
            };

            eConnStats.EConnectorComputerName   = Environment.MachineName;
            eConnStats.EConnectorDomainUserName = Environment.UserName;
            eConnStats.EConnectorIP             = ODEnvironment.GetLocalIPAddress();
            eConnStats.HasClinicsEnabled        = PrefC.HasClinicsEnabled;
            if (PrefC.HasClinicsEnabled)
            {
                eConnStats.CountActiveClinics   = OpenDentBusiness.Clinics.GetCount();
                eConnStats.CountInactiveClinics = OpenDentBusiness.Clinics.GetCount() - eConnStats.CountActiveClinics;
            }
            else
            {
                eConnStats.CountActiveClinics   = 0;
                eConnStats.CountInactiveClinics = OpenDentBusiness.Clinics.GetCount();
            }
            if (DateTime.Now.Hour == 0)            //These are heavy queries so only run them once a day around midnight.
            {
                eConnStats.CountActivePatients    = OpenDentBusiness.Procedures.GetCountPatsComplete(DateTime.Today.AddYears(-2), DateTime.Today);
                eConnStats.CountNonactivePatients = OpenDentBusiness.Patients.GetPatCountAll() - eConnStats.CountActivePatients;
                eConnStats.ListEServiceSignals    = OpenDentBusiness.EServiceSignals.GetServiceHistory(eServiceCode.ListenerService, DateTime.Today.AddDays(-30),
                                                                                                       DateTime.Today, 30);
            }
            eConnStats.DateTimeNow = DateTime.Now;
            foreach (PrefName prefName in Enum.GetValues(typeof(PrefName)))
            {
                if (prefName.In(
                        PrefName.RegistrationKey,
                        PrefName.ProgramVersion,
                        PrefName.DataBaseVersion,
                        PrefName.TextingDefaultClinicNum,
                        PrefName.WebServiceServerName,
                        PrefName.SendEmailsInDiffProcess,
                        PrefName.EmailAlertMaxConsecutiveFails,
                        PrefName.AutoCommNumClinicsParallel,
                        PrefName.AutomaticCommunicationTimeStart,
                        PrefName.AutomaticCommunicationTimeEnd) ||
                    prefName.ToString().StartsWith("WebSched") ||
                    prefName.ToString().StartsWith("ApptConfirm") ||
                    prefName.ToString().StartsWith("ApptRemind") ||
                    prefName.ToString().StartsWith("ApptEConfirm") ||
                    prefName.ToString().StartsWith("Recall") ||
                    prefName.ToString().StartsWith("PatientPortal") ||
                    prefName.ToString().StartsWith("Sms"))
                {
                    try {
                        eConnStats.ListEServicePrefs.Add(Prefs.GetPref(prefName.ToString()));
                    }
                    catch (Exception ex) {
                        ex.DoNothing();
                    }
                }
            }
            List <EConnectorStatistics> listStatsToSend = new List <EConnectorStatistics> {
                eConnStats
            };
            string dbStats = PrefC.GetString(PrefName.EConnectorStatistics);
            List <EConnectorStatistics> listDbStats = DeserializeListFromJson(dbStats) ?? new List <EConnectorStatistics>();
            bool doCreateAlert = false;

            foreach (EConnectorStatistics stats in listDbStats)
            {
                //If a different eConnector is saving stats, add that one to the list to be sent to HQ.
                if (!AreSameEConnector(eConnStats, stats) && (eConnStats.DateTimeNow - stats.DateTimeNow).TotalHours < 23)
                {
                    stats.ListEServicePrefs   = new List <Pref>();               //To save on bandwidth
                    stats.ListEServiceSignals = new List <EServiceSignal>();
                    listStatsToSend.Add(stats);
                    if ((eConnStats.DateTimeNow - stats.DateTimeNow).TotalHours < 3)
                    {
                        doCreateAlert = true;
                    }
                }
            }
            if (doCreateAlert && AlertItems.RefreshForType(AlertType.MultipleEConnectors).Count == 0)
            {
                AlertItem alert = new AlertItem {
                    Actions     = ActionType.MarkAsRead | ActionType.Delete,
                    Description = Lans.g("EConnectorStats", "eConnector services are being run on these computers:") + " "
                                  + string.Join(", ", listStatsToSend.Select(x => x.EConnectorComputerName)),
                    Severity = SeverityType.High,
                    Type     = AlertType.MultipleEConnectors,
                };
                AlertItems.Insert(alert);
            }
            string statsStr = SerializeToJson(listStatsToSend);

            OpenDentBusiness.Prefs.UpdateString(PrefName.EConnectorStatistics, statsStr);
            string payload = PayloadHelper.CreatePayload(PayloadHelper.CreatePayloadContent(statsStr, "EConnectorStatsStr"),
                                                         eServiceCode.ListenerService);

            WebServiceMainHQProxy.GetWebServiceMainHQInstance().SetEConnectorStatsAsync(payload);
        }
Example #6
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 silent)
        {
            FromVersion = new Version(fromVersion);
            ToVersion   = new Version(toVersion);        //Application.ProductVersion);
            if (FromVersion == ToVersion)
            {
                return(true);               //no conversion necessary
            }
            if (FromVersion >= new Version("3.4.0") && PrefC.GetBool(PrefName.CorruptedDatabase))
            {
                MsgBox.Show(this, "Your database is corrupted because a conversion failed.  Please contact us.  This database is unusable and you will need to restore from a backup.");
                return(false);                        //shuts program down.
            }
            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"))
            {
                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"))
            {
                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"))
            {
                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")
            {
                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)
            {
                MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                return(false);
            }
            if (FromVersion >= ConvertDatabases.LatestVersion)
            {
                return(true);               //no conversion necessary
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                MsgBox.Show(this, "Web client cannot convert database.  Must be using a direct connection.");
                return(false);
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                MsgBox.Show(this, "This replication server is blocked from performing updates.");
                return(false);
            }
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                   //and not on web server
            {
                MessageBox.Show(Lan.g(this, "Updates are only allowed from the web server: ") + PrefC.GetString(PrefName.WebServiceServerName));
                return(false);
            }
            //If MyISAM and InnoDb mix, then try to fix
            if (DataConnection.DBtype == DatabaseType.MySql)                    //not for Oracle
            {
                string namesInnodb = DatabaseMaintenance.GetInnodbTableNames(); //Or possibly some other format.
                int    numMyisam   = DatabaseMaintenance.GetMyisamTableCount();
                if (namesInnodb != "" && numMyisam > 0)
                {
                    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);
                    try {
                        MiscData.MakeABackup();                        //Does not work for Oracle, due to some MySQL specific commands inside.
                    }
                    catch (Exception e) {
                        Cursor.Current = Cursors.Default;
                        if (e.Message != "")
                        {
                            MessageBox.Show(e.Message);
                        }
                        MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                        return(false);
                    }
                    if (!DatabaseMaintenance.ConvertTablesToMyisam())
                    {
                        MessageBox.Show(Lan.g(this, "Failed to convert InnoDB tables to MyISAM format. Please contact support."));
                        return(false);
                    }
                    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 (DatabaseMaintenance.GetStorageEngineDefaultName().ToUpper() != "MYISAM")                    //Probably InnoDB but could be another format.
                    {
                        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 (!silent && 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 the newer code against the older database."
                                           , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(true);               //If user clicks cancel, then do nothing
            }
#else
            if (!silent && 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;
#if !DEBUG
            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);
            }
            try{
                if (DataConnection.DBtype == DatabaseType.MySql)
                {
                    MiscData.MakeABackup();                    //Does not work for Oracle, due to some MySQL specific commands inside.
                }
            }
            catch (Exception e) {
                Cursor.Current = Cursors.Default;
                if (e.Message != "")
                {
                    MessageBox.Show(e.Message);
                }
                MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                return(false);
            }
            try{
#endif
            if (FromVersion < new Version("7.5.17"))
            {
                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 (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, true);
            }
            ConvertDatabases.FromVersion = FromVersion;
            ConvertDatabases.To2_8_2();            //begins going through the chain of conversion steps
            Cursor.Current = Cursors.Default;
            if (!silent)
            {
                MsgBox.Show(this, "Conversion successful");
            }
            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);
            return(true);

#if !DEBUG
        }

        catch (System.IO.FileNotFoundException e) {
            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);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (System.IO.DirectoryNotFoundException) {
            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);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (Exception ex) {
            //	MessageBox.Show();
            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
        }
        ///<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
        }
Example #8
0
 ///<summary>Returns the first SiteLink that has a default gateway that matches the OctectStart value.  Returns null if no match found.</summary>
 public static SiteLink GetSiteLinkByGateway()
 {
     //No need to check RemotingRole; no call to db.
     return(GetFirstOrDefault(x => ODEnvironment.GetDefaultGateway().StartsWith(x.OctetStart)));
 }