Esempio n. 1
0
        ///<summary>NO LONGER USED.
        ///Leaving function here in case we want to reuse the code in future.  We only support connecting to archive DB directly.</summary>
        public static T RunFuncOnArchiveDatabase <T>(Func <T> f)
        {
            //Makes a connection to the archive database, validates that the version of the database is the same as the current database version,
            //executes the func passed in, and then sets the connection back to the original database before returning the results of the func passed in.
            //Optionally pass in connection settings to override the archive preferences.  Throws exceptions.
            if (RemotingClient.RemotingRole.In(RemotingRole.ClientWeb, RemotingRole.ServerWeb))            //May already be behind a remoting role check.
            //This method will eventually invoke SetDB() which is unacceptable for the Middle Tier.
            {
                throw new ApplicationException(Lans.g(nameof(MiscData), "Archive databases are not available when using a Middle Tier connection.") + "\r\n" +
                                               Lans.g(nameof(MiscData), "Archive databases may only be created or accessed on a direct database connection."));
            }
            string         connectionStrOrig = DataConnection.GetCurrentConnectionString();
            DatabaseType   dbTypeOrig        = DataConnection.DBtype;
            DataConnection dcon = new DataConnection();

            try {
                //Keep track of the original connection settings so that we can revert back to them once finished archiving.
                Version versionDbOrig     = new Version(PrefC.GetString(PrefName.DataBaseVersion));
                string  archiveServerName = PrefC.GetString(PrefName.ArchiveServerName);
                string  archiveUserName   = PrefC.GetString(PrefName.ArchiveUserName);
                string  decryptedPass;
                CDT.Class1.Decrypt(PrefC.GetString(PrefName.ArchivePassHash), out decryptedPass);
                //Connect to the archive database.  This can throw many exceptions.
                dcon.SetDb(archiveServerName, MiscData.GetArchiveDatabaseName(), archiveUserName, decryptedPass, "", "", dbTypeOrig);
                #region Validate archive database version
                //At this point there is an active connection to the archive database, validate the DataBaseVersion.
                string version = PrefC.GetStringNoCache(PrefName.DataBaseVersion);
                if (string.IsNullOrEmpty(version))
                {
                    //Preference table does not have version information.  Somehow they have a database with proper structure but no data.
                    //This archive database can't be trusted and we have no idea what version the schema is at.
                    //They need to call support so that we can take a look or they need to delete the invalid archive (or remove it from the data dir)
                    //so that a new archive database can be made from scratch.
                    throw new ApplicationException("Invalid archive database detected.");
                }
                Version versionDbArchive = new Version(version);
                if (versionDbOrig > versionDbArchive)
                {
                    //The archive database needs to be updated before funcs can be invoked against it.
                    throw new ApplicationException("Archive database is at a lower version than the current database."
                                                   + "  Run the Archive tool in order to update the database.");
                }
                else if (versionDbArchive > versionDbOrig)
                {
                    throw new ApplicationException("Archive database version is higher than the current database.  Process cannot continue.");
                }
                #endregion
                //Invoke the func passed in.
                return(f());
            }
            finally {                                          //Always put the connection back to the original no matter what happened above when trying to make an archive.
                dcon.SetDb(connectionStrOrig, "", dbTypeOrig); //It is acceptable to crash the program if this fails.
            }
        }
Esempio n. 2
0
 ///<summary>Only called at startup if this dialog is not supposed to be shown.  Must call GetConfig first.</summary>
 public bool TryToConnect()
 {
     if (checkConnectServer.Checked)            // && checkUsingEcw.Checked){
     //js commented this portion out in version 12.0 on 1/7/11.  Must hunt down resulting bugs.
     //if(!checkUsingEcw.Checked) {//Can't silently connect unless using eCW.
     //	return false;
     //}
     {
         RemotingClient.ServerURI = textURI.Text;
         try{
             //ecw requires hash, but non-ecw requires actual password
             if (checkUsingEcw.Checked)
             {
                 //this handles situation where an eCW user passes in an actual OdPassword
                 string password = OdPassHash;
                 if (OdPassword != "")
                 {
                     password = Userods.EncryptPassword(OdPassword, true);
                 }
                 Security.CurUser       = Security.LogInWeb(textUser2.Text, password, "", Application.ProductVersion, true);
                 Security.PasswordTyped = password;                      //so we really store the encrypted pw if ecw user passes in their real password?
             }
             else
             {
                 Security.CurUser       = Security.LogInWeb(textUser2.Text, OdPassword, "", Application.ProductVersion, false);
                 Security.PasswordTyped = OdPassword;
             }
             RemotingClient.RemotingRole = RemotingRole.ClientWeb;
             return(true);
         }
         catch {
             return(false);
         }
     }
     OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
     //Try to connect to the database directly
     try {
         if (textConnectionString.Text.Length > 0)
         {
             dcon.SetDb(textConnectionString.Text, "", DataConnection.DBtype);
         }
         else
         {
             dcon.SetDb(comboComputerName.Text, comboDatabase.Text, textUser.Text, textPassword.Text, "", "", DataConnection.DBtype);
         }
         //a direct connection does not utilize lower privileges.
         RemotingClient.RemotingRole = RemotingRole.ClientDirect;
         return(true);
     }
     catch (Exception ex) {
         return(false);
     }
 }
Esempio n. 3
0
 private void FormWebCamOD_Load(object sender,EventArgs e)
 {
     datePurged=DateTime.MinValue;
     Process[] processes=Process.GetProcessesByName("WebCamOD");
     for(int p=0;p<processes.Length;p++) {
         if(Process.GetCurrentProcess().Id==processes[p].Id) {
             continue;
         }
         //another process was found
         MessageBox.Show("WebCamOD is already running.");
         Application.Exit();
         return;
     }
     //since this tool is only used at HQ, we hard code everything
     bool is192network=false;
     IPHostEntry iphostentry=Dns.GetHostEntry(Environment.MachineName);
     foreach(IPAddress ipaddress in iphostentry.AddressList) {
         if(ipaddress.ToString().StartsWith("192.")) {
             is192network=true;
         }
     }
     DataConnection dbcon=new DataConnection();
     try {
         if(is192network) {
             dbcon.SetDb("192.168.0.200","customers","root","","","",DatabaseType.MySql);
         }
         else {
             dbcon.SetDb("10.10.10.200","customers","root","","","",DatabaseType.MySql);
         }
     }
     catch {
         MessageBox.Show("This tool is not designed for general use.");
         return;
     }
     //get ipaddress on startup
     IpAddress192="";
     foreach(IPAddress ipaddress in iphostentry.AddressList) {
         if(ipaddress.ToString().Contains("192.168.0")) {
             IpAddress192=ipaddress.ToString();
         }
     }
     //if(IpAddress192=="") {
     //	MessageBox.Show("Could not locate ipaddress");
     //	Application.Exit();
     //}
     intPtrVideo=IntPtr.Zero;
     timerPhoneWebCam.Enabled=true;
     timerScreenShots.Enabled=true;
     timerScreenShots_Tick(this,new EventArgs());//force an initial screenshot
 }
Esempio n. 4
0
        /// <summary>
        /// being a static constructor this is only called when Init() is called the first time. Further calls to Init() does not call this constructor.
        /// </summary>
        static DbInit()
        {
            string connectStr = Properties.Settings.Default.DBMobileWeb;

            OpenDentBusiness.DataConnection dc = new OpenDentBusiness.DataConnection();
            dc.SetDb(connectStr, "", DatabaseType.MySql, true);
        }
Esempio n. 5
0
        //public static string DbName;

        //public static bool DbExists(){
        //	string command="";
        //}

        ///<summary>This is analogous to FormChooseDatabase.TryToConnect.  Empty string is allowed.</summary>
        public static bool SetDbConnection(string dbName, bool isOracle)
        {
            OpenDentBusiness.DataConnection dcon;
            //Try to connect to the database directly
            try {
                if (!isOracle)
                {
                    DataConnection.DBtype = DatabaseType.MySql;
                    dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
                    dcon.SetDb("Server=localhost;Database=" + dbName + ";User ID=root;Password=;CharSet=utf8;Treat Tiny As Boolean=false", "", DataConnection.DBtype, true);
                    RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                    return(true);
                }
                else
                {
                    DataConnection.DBtype = DatabaseType.Oracle;
                    dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
                    dcon.SetDb("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=Jason)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=unittest;Password=unittest;", "", DataConnection.DBtype, true);
                    RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                    return(true);
                }
            }
            catch (Exception ex) {
                //throw new Exception(ex.Message);
                //MessageBox.Show(ex.Message);
                //textResults.Text="Make a copy of any OD db and rename it to unittest.";
                if (isOracle)
                {
                    MessageBox.Show("May need to create a Fresh Db for Oracle.");
                }
                return(false);
            }
        }
Esempio n. 6
0
		//public static string DbName;

		//public static bool DbExists(){
		//	string command="";
		//}

		///<summary>This is analogous to FormChooseDatabase.TryToConnect.  Empty string is allowed.</summary>
		public static bool SetDbConnection(string dbName,bool isOracle){
			OpenDentBusiness.DataConnection dcon;
			//Try to connect to the database directly
			try {
				if(!isOracle) {
					DataConnection.DBtype=DatabaseType.MySql;
					dcon=new OpenDentBusiness.DataConnection(DataConnection.DBtype);
					dcon.SetDb("Server=localhost;Database="+dbName+";User ID=root;Password=;CharSet=utf8;Treat Tiny As Boolean=false","",DataConnection.DBtype,true);
					RemotingClient.RemotingRole=RemotingRole.ClientDirect;
					return true;
				}
				else { 
					DataConnection.DBtype=DatabaseType.Oracle;
					dcon=new OpenDentBusiness.DataConnection(DataConnection.DBtype);
					dcon.SetDb("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=Jason)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=unittest;Password=unittest;","",DataConnection.DBtype,true);
					RemotingClient.RemotingRole=RemotingRole.ClientDirect;
					return true;
				}
			}
			catch(Exception ex){
				//throw new Exception(ex.Message);
				//MessageBox.Show(ex.Message);
				//textResults.Text="Make a copy of any OD db and rename it to unittest.";
				if(isOracle) {
					MessageBox.Show("May need to create a Fresh Db for Oracle.");
				}
				return false;
			}
		}
Esempio n. 7
0
        ///<summary>Used when viewing various audit trails of specific types.  This overload will return security logs for multiple objects (or fKeys).  Typically you will only need a specific type audit log for one type.  However, for things like ortho charts, each row (FK) in the database represents just one part of a larger ortho chart "object".  Thus, to get the full experience of a specific type audit trail window, we need to get security logs for multiple objects (FKs) that comprise the larger object (what the user sees).  Only implemented with ortho chart so far.  FKeys can be null.</summary>
        public static SecurityLog[] Refresh(long patNum, List <Permissions> permTypes, List <long> fKeys, bool includeArchived)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <SecurityLog[]>(MethodBase.GetCurrentMethod(), patNum, permTypes, fKeys, includeArchived));
            }
            string types = "";

            for (int i = 0; i < permTypes.Count; i++)
            {
                if (i > 0)
                {
                    types += " OR";
                }
                types += " PermType=" + POut.Long((int)permTypes[i]);
            }
            string command = "SELECT * FROM securitylog "
                             + "WHERE (" + types + ") ";

            if (fKeys != null && fKeys.Count > 0)
            {
                command += "AND FKey IN (" + String.Join(",", fKeys) + ") ";
            }
            if (patNum != 0)           //appointments
            {
                command += " AND PatNum IN (" + string.Join(",",
                                                            PatientLinks.GetPatNumsLinkedToRecursive(patNum, PatientLinkType.Merge).Select(x => POut.Long(x))) + ")";
            }
            command += "ORDER BY LogDateTime";
            List <SecurityLog> listLogs = Crud.SecurityLogCrud.SelectMany(command);

            if (includeArchived)
            {
                string decryptedPass;
                CDT.Class1.Decrypt(PrefC.GetString(PrefName.ArchivePassHash), out decryptedPass);
                string         connectionStrOrig = DataConnection.GetCurrentConnectionString();
                DatabaseType   dbTypeOrig        = DataConnection.DBtype;
                DataConnection dcon = new DataConnection();
                //Connect to archive database
                dcon.SetDb(PrefC.GetString(PrefName.ArchiveServerName) == ""?PrefC.GetString(PrefName.ArchiveServerURI):PrefC.GetString(PrefName.ArchiveServerName),
                           "opendentalarchive", PrefC.GetString(PrefName.ArchiveUserName), decryptedPass, "", "", dbTypeOrig);
                listLogs.AddRange(Crud.SecurityLogCrud.SelectMany(command)); //Append results
                dcon.SetDb(connectionStrOrig, "", dbTypeOrig);               //Reconnect to initial db
            }
            return(listLogs.OrderBy(x => x.LogDateTime).ToArray());
        }
Esempio n. 8
0
 public void SetDbConnection()
 {
     try {
         string connectStr=Properties.Settings.Default.DBPatientPortal;
         OpenDentBusiness.DataConnection dc=new OpenDentBusiness.DataConnection();
         dc.SetDb(connectStr,"",DatabaseType.MySql,true);
     }
     catch(Exception ex) {
         Logger.LogError(ex);
     }
 }
Esempio n. 9
0
 public void SetDbConnection()
 {
     try {
         string connectStr = Properties.Settings.Default.DBPatientPortal;
         OpenDentBusiness.DataConnection dc = new OpenDentBusiness.DataConnection();
         dc.SetDb(connectStr, "", DatabaseType.MySql, true);
     }
     catch (Exception ex) {
         Logger.LogError(ex);
     }
 }
Esempio n. 10
0
        ///<summary>Gets the settings from the config file and attempts to connect.</summary>
        private bool GetConfigAndConnect()
        {
            string xmlPath = Path.Combine(Application.StartupPath, "CentralManagerConfig.xml");

            if (!File.Exists(xmlPath))
            {
                MessageBox.Show("Please create CentralManagerConfig.xml according to the manual before using this tool.");
                Application.Exit();
                return(false);
            }
            XmlDocument document     = new XmlDocument();
            string      computerName = "";
            string      database     = "";
            string      user         = "";
            string      password     = "";

            try{
                document.Load(xmlPath);
                XPathNavigator Navigator = document.CreateNavigator();
                XPathNavigator nav;
                DataConnection.DBtype = DatabaseType.MySql;
                //See if there's a DatabaseConnection
                nav = Navigator.SelectSingleNode("//DatabaseConnection");
                if (nav == null)
                {
                    MessageBox.Show("DatabaseConnection element missing from CentralManagerConfig.xml.");
                    Application.Exit();
                    return(false);
                }
                computerName = nav.SelectSingleNode("ComputerName").Value;
                database     = nav.SelectSingleNode("Database").Value;
                user         = nav.SelectSingleNode("User").Value;
                password     = nav.SelectSingleNode("Password").Value;
            }
            catch (Exception ex) {
                //Common error: root element is missing
                MessageBox.Show(ex.Message);
                Application.Exit();
                return(false);
            }
            DataConnection.DBtype = DatabaseType.MySql;
            OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
            //Try to connect to the database directly
            try {
                dcon.SetDb(computerName, database, user, password, "", "", DataConnection.DBtype);
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                return(true);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                Application.Exit();
                return(false);
            }
        }
Esempio n. 11
0
		///<summary>Updates the current data connection settings of the central manager to the connection settings passed in.  Setting refreshCache to true will cause the entire local cache to get updated with the cache from the connection passed in if the new connection settings are successful.</summary>
		public static bool UpdateCentralConnection(CentralConnection centralConnection,bool refreshCache) {
			UTF8Encoding enc=new UTF8Encoding();
			byte[] EncryptionKey=enc.GetBytes("mQlEGebnokhGFEFV");//Gotten from FormCentralManager constructor. Only place that does anything like this.
			string webServiceURI="";
			string computerName="";
			string database="";
			string user="";
			string password="";
			string odPassword="";
			if(centralConnection.DatabaseName!="") {
				computerName=centralConnection.ServerName;
				database=centralConnection.DatabaseName;
				user=centralConnection.MySqlUser;
				if(centralConnection.MySqlPassword!="") {
					password=CentralConnections.Decrypt(centralConnection.MySqlPassword,EncryptionKey);
				}
				RemotingClient.ServerURI="";
			}
			else if(centralConnection.ServiceURI!="") {
				webServiceURI=centralConnection.ServiceURI;
				RemotingClient.ServerURI=webServiceURI;
				try {
					odPassword=CentralConnections.Decrypt(centralConnection.OdPassword,EncryptionKey);
					Security.CurUser=Security.LogInWeb(centralConnection.OdUser,odPassword,"",Application.ProductVersion,centralConnection.WebServiceIsEcw);
					Security.PasswordTyped=odPassword;
				}
				catch {
					return false;
				}
			}
			else {
				MessageBox.Show("Either a database or a Middle Tier URI must be specified in the connection.");
				return false;
			}
			try {
				if(RemotingClient.ServerURI!="") {
					RemotingClient.RemotingRole=RemotingRole.ClientWeb;
				}
				else {
					DataConnection.DBtype=DatabaseType.MySql;
					OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
					dcon.SetDb(computerName,database,user,password,"","",DataConnection.DBtype);
					RemotingClient.RemotingRole=RemotingRole.ClientDirect;
				}
				if(refreshCache) {
					Cache.RefreshCache(((int)InvalidType.AllLocal).ToString());
				}
			}
			catch {
				return false;
			}
			return true;
		}
 ///<summary>Only called at startup if this dialog is not supposed to be shown.  Must call GetConfig first.</summary>
 public bool TryToConnect()
 {
     OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
     //Try to connect to the database directly
     try {
         if (textConnectionString.Text.Length > 0)
         {
             dcon.SetDb(textConnectionString.Text, "", DBtype);
         }
         else
         {
             dcon.SetDb(comboComputerName.Text, comboDatabase.Text, textUser.Text, textPassword.Text, "", "", DBtype);
         }
         //a direct connection does not utilize lower privileges.
         RemotingClient.OpenDentBusinessIsLocal = true;
         return(true);
     }
     catch {            //(Exception ex){
         return(false);
     }
 }
Esempio n. 13
0
        //public static string DbName;

        //public static bool DbExists(){
        //	string command="";
        //}

        ///<summary>This is analogous to FormChooseDatabase.TryToConnect.  Empty string is allowed.</summary>
        public static bool SetDbConnection(string dbName, string serverName)
        {
            try {
                OpenDentBusiness.DataConnection dcon;
                DataConnection.DBtype = DatabaseType.MySql;
                dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
                dcon.SetDb("Server=" + serverName + ";Database=" + dbName + ";User ID=root;Password=;CharSet=utf8;Treat Tiny As Boolean=false", "", DataConnection.DBtype, true);
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                return(true);
            }
            catch {
                return(false);
            }
        }
Esempio n. 14
0
		//public static string DbName;

		//public static bool DbExists(){
		//	string command="";
		//}

		///<summary>This is analogous to FormChooseDatabase.TryToConnect.  Empty string is allowed.</summary>
		public static bool SetDbConnection(string dbName){
			OpenDentBusiness.DataConnection dcon;
			//Try to connect to the database directly
			try {
				DataConnection.DBtype=DatabaseType.MySql;
				dcon=new OpenDentBusiness.DataConnection(DataConnection.DBtype);
				dcon.SetDb("Server=localhost;Database="+dbName+";User ID=root;Password=;CharSet=utf8;Treat Tiny As Boolean=false","",DataConnection.DBtype,true);
				RemotingClient.RemotingRole=RemotingRole.ClientDirect;
				return true;
			}
			catch{//(Exception ex){
				//throw new Exception(ex.Message);
				//MessageBox.Show(ex.Message);
				//textResults.Text="Make a copy of any OD db and rename it to canadatest.";
				return false;
			}
		}
Esempio n. 15
0
        //public static string DbName;

        //public static bool DbExists(){
        //	string command="";
        //}

        ///<summary>This is analogous to FormChooseDatabase.TryToConnect.  Empty string is allowed.</summary>
        public static bool SetDbConnection(string dbName)
        {
            OpenDentBusiness.DataConnection dcon;
            //Try to connect to the database directly
            try {
                DataConnection.DBtype = DatabaseType.MySql;
                dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
                dcon.SetDb("Server=localhost;Database=" + dbName + ";User ID=root;Password=;CharSet=utf8;Treat Tiny As Boolean=false", "", DataConnection.DBtype, true);
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                return(true);
            }
            catch {           //(Exception ex){
                //throw new Exception(ex.Message);
                //MessageBox.Show(ex.Message);
                //textResults.Text="Make a copy of any OD db and rename it to canadatest.";
                return(false);
            }
        }
Esempio n. 16
0
 //<summary>This function allows connecting to a specific server.</summary>
 public static bool SetDbConnection(string dbName, string serverAddr, string port, string userName, string password, bool isOracle)
 {
     OpenDentBusiness.DataConnection dcon;
     //Try to connect to the database directly
     try {
         if (!isOracle)
         {
             DataConnection.DBtype = DatabaseType.MySql;
             dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
             string connectStr = "Server=" + serverAddr
                                 + ";Port=" + port
                                 + ";Database=" + dbName
                                 + ";User ID=" + userName
                                 + ";Password="******";CharSet=utf8"
                                 + ";Treat Tiny As Boolean=false"
                                 + ";Allow User Variables=true"
                                 + ";Default Command Timeout=3600";
             dcon.SetDb(connectStr, "", DataConnection.DBtype, true);
             RemotingClient.RemotingRole = RemotingRole.ClientDirect;
             return(true);
         }
         else
         {
             DataConnection.DBtype = DatabaseType.Oracle;
             dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
             dcon.SetDb("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + serverAddr + ")(PORT=" + port + "))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=" + userName + ";Password="******";", "", DataConnection.DBtype, true);
             RemotingClient.RemotingRole = RemotingRole.ClientDirect;
             return(true);
         }
     }
     catch (Exception ex) {
         ex.DoNothing();
         if (isOracle)
         {
             throw new Exception("May need to create a Fresh Db for Oracle.");
         }
         return(false);
     }
 }
Esempio n. 17
0
        ///<summary>Gets the settings from the config file and attempts to connect.</summary>
        private bool GetConfigAndConnect()
        {
            string xmlPath = Path.Combine(Application.StartupPath, "CentralManagerConfig.xml");

            if (!File.Exists(xmlPath))
            {
                MessageBox.Show("Please create CentralManagerConfig.xml according to the manual before using this tool.");
                _hasFatalError = true;
                Application.Exit();
                return(false);
            }
            XmlDocument document     = new XmlDocument();
            string      computerName = "";
            string      database     = "";
            string      user         = "";
            string      password     = "";
            string      middleTier   = "";

            try {
                document.Load(xmlPath);
                XPathNavigator Navigator = document.CreateNavigator();
                XPathNavigator nav;
                DataConnection.DBtype = DatabaseType.MySql;
                //See if there's a DatabaseConnection
                nav = Navigator.SelectSingleNode("//DatabaseConnection");
                if (nav == null)
                {
                    MessageBox.Show("DatabaseConnection element missing from CentralManagerConfig.xml.");
                    Application.Exit();
                    return(false);
                }
                computerName = nav.SelectSingleNode("ComputerName").Value;
                database     = nav.SelectSingleNode("Database").Value;
                user         = nav.SelectSingleNode("User").Value;
                password     = nav.SelectSingleNode("Password").Value;
                XPathNavigator passHashNode = nav.SelectSingleNode("MySQLPassHash");
                string         decryptedPwd;
                if (password == "" && passHashNode != null && passHashNode.Value != "" && CDT.Class1.Decrypt(passHashNode.Value, out decryptedPwd))
                {
                    password = decryptedPwd;
                }
                XPathNavigator nodeMT = nav.SelectSingleNode("MiddleTierAddr");
                if (nodeMT != null)
                {
                    middleTier = nodeMT.Value;
                }
            }
            catch (Exception ex) {
                //Common error: root element is missing
                MessageBox.Show(ex.Message);
                Application.Exit();
                return(false);
            }
            DataConnection.DBtype = DatabaseType.MySql;
            OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
            //Try to connect to the database directly
            if (middleTier != "")
            {
                FormCentralChooseDatabase FormCCD = new FormCentralChooseDatabase(middleTier);
                if (FormCCD.ShowDialog() == DialogResult.Cancel)
                {
                    Application.Exit();
                    return(false);
                }
            }
            else
            {
                try {
                    dcon.SetDb(computerName, database, user, password, "", "", DataConnection.DBtype);
                    RemotingClient.RemotingRole = RemotingRole.ClientDirect;
                    FormCentralLogOn FormCLO = new FormCentralLogOn();
                    if (FormCLO.ShowDialog() != DialogResult.OK)
                    {
                        _hasFatalError = true;
                        Application.Exit();
                        return(false);
                    }
                    return(true);
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                    _hasFatalError = true;
                    Application.Exit();
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 18
0
		public static void ConnectToDatabaseM(string dbName) {
			OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
			dcon.SetDb("10.10.1.196",dbName,"root","","","",DatabaseType.MySql);
			RemotingClient.RemotingRole=RemotingRole.ClientDirect;
		}
Esempio n. 19
0
        public void StartManually()
        {
            //connect to OD db.
            XmlDocument document = new XmlDocument();
            string      pathXml  = Path.Combine(Application.StartupPath, "FreeDentalConfig.xml");

            try{
                document.Load(pathXml);
            }
            catch {
                EventLog.WriteEntry("OpenDentHL7", DateTime.Now.ToLongTimeString() + " - Could not find " + pathXml, EventLogEntryType.Error);
                throw new ApplicationException("Could not find " + pathXml);
            }
            XPathNavigator Navigator = document.CreateNavigator();
            XPathNavigator nav;

            DataConnection.DBtype = DatabaseType.MySql;
            nav = Navigator.SelectSingleNode("//DatabaseConnection");
            string         computerName = nav.SelectSingleNode("ComputerName").Value;
            string         database     = nav.SelectSingleNode("Database").Value;
            string         user         = nav.SelectSingleNode("User").Value;
            string         password     = nav.SelectSingleNode("Password").Value;
            XPathNavigator verboseNav   = Navigator.SelectSingleNode("//HL7verbose");

            if (verboseNav != null && verboseNav.Value == "True")
            {
                IsVerboseLogging = true;
                EventLog.WriteEntry("OpenDentHL7", "Verbose mode.", EventLogEntryType.Information);
            }
            OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
            //Try to connect to the database directly
            try {
                dcon.SetDb(computerName, database, user, password, "", "", DataConnection.DBtype);
                //a direct connection does not utilize lower privileges.
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
            }
            catch {            //(Exception ex){
                throw new ApplicationException("Connection to database failed.");
            }
            //check db version
            string dbVersion = PrefC.GetString(PrefName.ProgramVersion);

            if (Application.ProductVersion.ToString() != dbVersion)
            {
                EventLog.WriteEntry("OpenDentHL7", "Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString(), EventLogEntryType.Error);
                throw new ApplicationException("Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString());
            }
            //inform od via signal that this service is running
            IsStandalone = true;          //and for Mountainside
            if (Programs.UsingEcwTight())
            {
                IsStandalone = false;
            }
            //#if DEBUG//just so I don't forget to remove it later.
            //IsStandalone=false;
            //#endif
            hl7FolderOut = PrefC.GetString(PrefName.HL7FolderOut);
            if (!Directory.Exists(hl7FolderOut))
            {
                throw new ApplicationException(hl7FolderOut + " does not exist.");
            }
            //start polling the folder for waiting messages to import.  Every 5 seconds.
            TimerCallback timercallbackReceive = new TimerCallback(TimerCallbackReceiveFunction);

            timerReceive = new System.Threading.Timer(timercallbackReceive, null, 5000, 5000);
            if (IsStandalone)
            {
                return;                //do not continue with the HL7 sending code below
            }
            //start polling the db for new HL7 messages to send. Every 1.8 seconds.
            hl7FolderIn = PrefC.GetString(PrefName.HL7FolderIn);
            if (!Directory.Exists(hl7FolderIn))
            {
                throw new ApplicationException(hl7FolderIn + " does not exist.");
            }
            TimerCallback timercallbackSend = new TimerCallback(TimerCallbackSendFunction);

            timerSend = new System.Threading.Timer(timercallbackSend, null, 1800, 1800);
        }
Esempio n. 20
0
 private void butOK_Click(object sender, System.EventArgs e)
 {
     if (checkConnectServer.Checked)
     {
         string originalURI = RemotingClient.ServerURI;
         RemotingClient.ServerURI = textURI.Text;
         bool useEcwAlgorithm = checkUsingEcw.Checked;
         try{
             string password = textPassword2.Text;
             if (useEcwAlgorithm)
             {
                 password = Userods.EncryptPassword(password, true);
             }
             //ecw requires hash, but non-ecw requires actual password
             Userod user = Security.LogInWeb(textUser2.Text, password, "", Application.ProductVersion, useEcwAlgorithm);
             Security.CurUser            = user;
             Security.PasswordTyped      = password;             //for ecw, this is already encrypted.//textPassword2.Text;
             RemotingClient.RemotingRole = RemotingRole.ClientWeb;
         }
         catch (Exception ex) {
             RemotingClient.ServerURI = originalURI;
             MessageBox.Show(ex.Message);
             return;
         }
     }
     else
     {
         OpenDentBusiness.DataConnection dcon;
         //Try to connect to the database directly
         try {
             DataConnection.DBtype = DatabaseType.MySql;
             if (listType.SelectedIndex == 1)
             {
                 DataConnection.DBtype = DatabaseType.Oracle;
             }
             dcon = new OpenDentBusiness.DataConnection(DataConnection.DBtype);
             if (textConnectionString.Text.Length > 0)
             {
                 dcon.SetDb(textConnectionString.Text, "", DataConnection.DBtype);
             }
             else
             {
                 dcon.SetDb(comboComputerName.Text, comboDatabase.Text, textUser.Text, textPassword.Text, "", "", DataConnection.DBtype);
             }
             //a direct connection does not utilize lower privileges.
         }
         catch (Exception ex) {
             MessageBox.Show(                    //Lan.g(this,"Could not establish connection to database."));
                 ex.Message);
             return;
         }
         RemotingClient.RemotingRole = RemotingRole.ClientDirect;
     }
     try{
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.Indent      = true;
         settings.IndentChars = ("    ");
         using (XmlWriter writer = XmlWriter.Create(ODFileUtils.CombinePaths(Application.StartupPath, "FreeDentalConfig.xml"), settings)) {
             writer.WriteStartElement("ConnectionSettings");
             if (textConnectionString.Text != "")
             {
                 writer.WriteStartElement("ConnectionString");
                 writer.WriteString(textConnectionString.Text);
                 writer.WriteEndElement();
             }
             else if (RemotingClient.RemotingRole == RemotingRole.ClientDirect)
             {
                 writer.WriteStartElement("DatabaseConnection");
                 writer.WriteStartElement("ComputerName");
                 writer.WriteString(comboComputerName.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Database");
                 writer.WriteString(comboDatabase.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("User");
                 writer.WriteString(textUser.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Password");
                 writer.WriteString(textPassword.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("NoShowOnStartup");
                 if (checkNoShow.Checked)
                 {
                     writer.WriteString("True");
                 }
                 else
                 {
                     writer.WriteString("False");
                 }
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             else if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
             {
                 writer.WriteStartElement("ServerConnection");
                 writer.WriteStartElement("URI");
                 writer.WriteString(textURI.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("UsingEcw");
                 if (checkUsingEcw.Checked)
                 {
                     writer.WriteString("True");
                 }
                 else
                 {
                     writer.WriteString("False");
                 }
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             writer.WriteStartElement("DatabaseType");
             if (listType.SelectedIndex == 0)
             {
                 writer.WriteString("MySql");
             }
             else
             {
                 writer.WriteString("Oracle");
             }
             writer.WriteEndElement();
             writer.WriteEndElement();
             writer.Flush();
         }                //using writer
     }
     catch {
         //data not saved.
     }
     //fyiReporting.RDL.DataSource.SetOpenDentalConnectionString(
     //	"Server="+ComputerName+";Database="+Database+";User ID="+DbUser+";Password="******";CharSet=utf8");
     DialogResult = DialogResult.OK;
 }
Esempio n. 21
0
        ///<summary>Will throw an exception if it fails for any reason.  This will directly access the config file on the disk, read the values, and set the DataConnection to the new database.  This is only triggered when someone tries to log on.</summary>
        public static void LoadDatabaseInfoFromFile(string configFilePath)
        {
            //No need to check RemotingRole; no call to db.
            if (!File.Exists(configFilePath))
            {
                throw new Exception("Could not find " + configFilePath + " on the web server.");
            }
            XmlDocument doc = new XmlDocument();

            try {
                doc.Load(configFilePath);
            }
            catch {
                throw new Exception("Web server " + configFilePath + " could not be opened or is in an invalid format.");
            }
            XPathNavigator Navigator = doc.CreateNavigator();
            //always picks the first database entry in the file:
            XPathNavigator navConn = Navigator.SelectSingleNode("//DatabaseConnection");          //[Database='"+database+"']");

            if (navConn == null)
            {
                throw new Exception(configFilePath + " does not contain a valid database entry.");              //database+" is not an allowed database.");
            }
            string         connString = "", server = "", database = "", mysqlUser = "", mysqlPassword = "", mysqlUserLow = "", mysqlPasswordLow = "";
            XPathNavigator navConString = navConn.SelectSingleNode("ConnectionString");

            if (navConString != null)           //If there is a connection string then use it.
            {
                connString = navConString.Value;
            }
            else
            {
                //return navOne.SelectSingleNode("summary").Value;
                //now, get the values for this connection
                server           = navConn.SelectSingleNode("ComputerName").Value;
                database         = navConn.SelectSingleNode("Database").Value;
                mysqlUser        = navConn.SelectSingleNode("User").Value;
                mysqlPassword    = navConn.SelectSingleNode("Password").Value;
                mysqlUserLow     = navConn.SelectSingleNode("UserLow").Value;
                mysqlPasswordLow = navConn.SelectSingleNode("PasswordLow").Value;
            }
            XPathNavigator dbTypeNav = navConn.SelectSingleNode("DatabaseType");
            DatabaseType   dbtype    = DatabaseType.MySql;

            if (dbTypeNav != null)
            {
                if (dbTypeNav.Value == "Oracle")
                {
                    dbtype = DatabaseType.Oracle;
                }
            }
            DataConnection dcon = new DataConnection();

            if (connString != "")
            {
                try {
                    dcon.SetDb(connString, "", dbtype);
                }
                catch (Exception e) {
                    throw new Exception(e.Message + "\r\n" + "Connection to database failed.  Check the values in the config file on the web server " + configFilePath);
                }
            }
            else
            {
                try {
                    dcon.SetDb(server, database, mysqlUser, mysqlPassword, mysqlUserLow, mysqlPasswordLow, dbtype);
                }
                catch (Exception e) {
                    throw new Exception(e.Message + "\r\n" + "Connection to database failed.  Check the values in the config file on the web server " + configFilePath);
                }
            }
            //todo?: make sure no users have blank passwords.
        }
 ///<summary>Throws an exception to display to the user if anything goes wrong.</summary>
 public static void TryToConnect(CentralConnection centralConnection, DatabaseType dbType, string connectionString = "", bool noShowOnStartup = false,
                                 List <string> listAdminCompNames = null, bool isCommandLineArgs = false, bool useDynamicMode = false, bool allowAutoLogin = true)
 {
     if (!string.IsNullOrEmpty(centralConnection.ServiceURI))
     {
         LoadMiddleTierProxySettings();
         string originalURI = RemotingClient.ServerURI;
         RemotingClient.ServerURI = centralConnection.ServiceURI;
         bool         useEcwAlgorithm = centralConnection.WebServiceIsEcw;
         RemotingRole originalRole    = RemotingClient.RemotingRole;
         RemotingClient.RemotingRole = RemotingRole.ClientWeb;
         try {
             string password = centralConnection.OdPassword;
             if (useEcwAlgorithm)
             {
                 //It doesn't matter what Security.CurUser is when it is null because we are technically trying to set it for the first time.
                 //It cannot be null before invoking HashPassword for Middle Tier for creating credentials for DTOs.
                 if (Security.CurUser == null)
                 {
                     Security.CurUser = new Userod();
                 }
                 //Utilize the custom eCW MD5 hashing algorithm if no password hash was passed in via command line arguments.
                 if (string.IsNullOrEmpty(centralConnection.OdPassHash))
                 {
                     password = Authentication.HashPasswordMD5(password, true);
                 }
                 else                          //eCW gave us the password already hashed via command line arguments, simply use it.
                 {
                     password = centralConnection.OdPassHash;
                 }
             }
             string username = centralConnection.OdUser;
             //ecw requires hash, but non-ecw requires actual password
             Security.CurUser       = Security.LogInWeb(username, password, "", Application.ProductVersion, useEcwAlgorithm);
             Security.PasswordTyped = password;                  //for ecw, this is already encrypted.
             UserOdPrefs.SetThemeForUserIfNeeded();
         }
         catch (Exception ex) {
             RemotingClient.ServerURI    = originalURI;
             RemotingClient.RemotingRole = originalRole;
             throw ex;
         }
     }
     else
     {
         DataConnection.DBtype = dbType;
         DataConnection dcon = new DataConnection();
         if (connectionString.Length > 0)
         {
             dcon.SetDb(connectionString, "", DataConnection.DBtype);
         }
         else
         {
             //Password could be plain text password from the Password field of the config file, the decrypted password from the MySQLPassHash field
             //of the config file, or password entered by the user and can be blank (empty string) in all cases
             dcon.SetDb(centralConnection.ServerName, centralConnection.DatabaseName, centralConnection.MySqlUser
                        , centralConnection.MySqlPassword, "", "", DataConnection.DBtype);
         }
         //a direct connection does not utilize lower privileges.
         RemotingClient.RemotingRole = RemotingRole.ClientDirect;
     }
     //Only gets this far if we have successfully connected, thus, saving connection settings is appropriate.
     TrySaveConnectionSettings(centralConnection, dbType, connectionString, noShowOnStartup: noShowOnStartup, listAdminCompNames,
                               isCommandLineArgs: isCommandLineArgs, useDynamicMode: useDynamicMode, allowAutoLogin: allowAutoLogin);
 }
Esempio n. 23
0
 public static void ConnectToDatabaseM(string dbName)
 {
     OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
     dcon.SetDb("10.10.1.196", dbName, "root", "", "", "", DatabaseType.MySql);
     RemotingClient.RemotingRole = RemotingRole.ClientDirect;
 }
Esempio n. 24
0
		///<summary>Will throw an exception if it fails for any reason.  This will directly access the config file on the disk, read the values, and set the DataConnection to the new database.  This is only triggered when someone tries to log on.</summary>
		public static void LoadDatabaseInfoFromFile(string configFilePath){
			//No need to check RemotingRole; no call to db.
			if(!File.Exists(configFilePath)){
				throw new Exception("Could not find "+configFilePath+" on the web server.");
			}
			XmlDocument doc=new XmlDocument();
			try {
				doc.Load(configFilePath);
			}
			catch{
				throw new Exception("Web server "+configFilePath+" could not be opened or is in an invalid format.");
			}
			XPathNavigator Navigator=doc.CreateNavigator();
			//always picks the first database entry in the file:
			XPathNavigator navConn=Navigator.SelectSingleNode("//DatabaseConnection");//[Database='"+database+"']");
			if(navConn==null) {
				throw new Exception(configFilePath+" does not contain a valid database entry.");//database+" is not an allowed database.");
			}
			string connString="",server="",database="",mysqlUser="",mysqlPassword="",mysqlUserLow="",mysqlPasswordLow="";
			XPathNavigator navConString=navConn.SelectSingleNode("ConnectionString");
			if(navConString!=null) {//If there is a connection string then use it.
				connString=navConString.Value;
			}
			else {
				//return navOne.SelectSingleNode("summary").Value;
				//now, get the values for this connection
				server=navConn.SelectSingleNode("ComputerName").Value;
				database=navConn.SelectSingleNode("Database").Value;
				mysqlUser=navConn.SelectSingleNode("User").Value;
				mysqlPassword=navConn.SelectSingleNode("Password").Value;
				mysqlUserLow=navConn.SelectSingleNode("UserLow").Value;
				mysqlPasswordLow=navConn.SelectSingleNode("PasswordLow").Value;
			}
			XPathNavigator dbTypeNav=navConn.SelectSingleNode("DatabaseType");
			DatabaseType dbtype=DatabaseType.MySql;
			if(dbTypeNav!=null){
				if(dbTypeNav.Value=="Oracle"){
					dbtype=DatabaseType.Oracle;
				}
			}
			DataConnection dcon=new DataConnection();
			if(connString!="") {
				try {
					dcon.SetDb(connString,"",dbtype);
				}
				catch(Exception e) {
					throw new Exception(e.Message+"\r\n"+"Connection to database failed.  Check the values in the config file on the web server "+configFilePath);
				}
			}
			else {
				try {
					dcon.SetDb(server,database,mysqlUser,mysqlPassword,mysqlUserLow,mysqlPasswordLow,dbtype);
				}
				catch(Exception e) {
					throw new Exception(e.Message+"\r\n"+"Connection to database failed.  Check the values in the config file on the web server "+configFilePath);
				}
			}
			//todo?: make sure no users have blank passwords.
		}
Esempio n. 25
0
 ///<summary>Gets the settings from the config file and attempts to connect.</summary>
 private bool GetConfigAndConnect()
 {
     string xmlPath=Path.Combine(Application.StartupPath,"CentralManagerConfig.xml");
     if(!File.Exists(xmlPath)){
         MessageBox.Show("Please create CentralManagerConfig.xml according to the manual before using this tool.");
         Application.Exit();
         return false;
     }
     XmlDocument document=new XmlDocument();
     string computerName="";
     string database="";
     string user="";
     string password="";
     try{
         document.Load(xmlPath);
         XPathNavigator Navigator=document.CreateNavigator();
         XPathNavigator nav;
         DataConnection.DBtype=DatabaseType.MySql;
         //See if there's a DatabaseConnection
         nav=Navigator.SelectSingleNode("//DatabaseConnection");
         if(nav==null) {
             MessageBox.Show("DatabaseConnection element missing from CentralManagerConfig.xml.");
             Application.Exit();
             return false;
         }
         computerName=nav.SelectSingleNode("ComputerName").Value;
         database=nav.SelectSingleNode("Database").Value;
         user=nav.SelectSingleNode("User").Value;
         password=nav.SelectSingleNode("Password").Value;
     }
     catch(Exception ex) {
         //Common error: root element is missing
         MessageBox.Show(ex.Message);
         Application.Exit();
         return false;
     }
     DataConnection.DBtype=DatabaseType.MySql;
     OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
     //Try to connect to the database directly
     try {
         dcon.SetDb(computerName,database,user,password,"","",DataConnection.DBtype);
         RemotingClient.RemotingRole=RemotingRole.ClientDirect;
         return true;
     }
     catch(Exception ex){
         MessageBox.Show(ex.Message);
         Application.Exit();
         return false;
     }
 }
Esempio n. 26
0
 private void butOK_Click(object sender, System.EventArgs e)
 {
     if(checkConnectServer.Checked){
         string originalURI=RemotingClient.ServerURI;
         RemotingClient.ServerURI=textURI.Text;
         bool useEcwAlgorithm=checkUsingEcw.Checked;
         try{
             string password=textPassword2.Text;
             if(useEcwAlgorithm){
                 password=Userods.EncryptPassword(password,true);
             }
             //ecw requires hash, but non-ecw requires actual password
             Userod user=Security.LogInWeb(textUser2.Text,password,"",Application.ProductVersion,useEcwAlgorithm);
             Security.CurUser=user;
             Security.PasswordTyped=password;//for ecw, this is already encrypted.//textPassword2.Text;
             RemotingClient.RemotingRole=RemotingRole.ClientWeb;
         }
         catch(Exception ex){
             RemotingClient.ServerURI=originalURI;
             MessageBox.Show(ex.Message);
             return;
         }
     }
     else{
         OpenDentBusiness.DataConnection dcon;
         //Try to connect to the database directly
         try {
             DataConnection.DBtype=DatabaseType.MySql;
             if(listType.SelectedIndex==1) {
                 DataConnection.DBtype=DatabaseType.Oracle;
             }
             dcon=new OpenDentBusiness.DataConnection(DataConnection.DBtype);
             if(textConnectionString.Text.Length>0){
                 dcon.SetDb(textConnectionString.Text,"",DataConnection.DBtype);
             }
             else{
                 dcon.SetDb(comboComputerName.Text,comboDatabase.Text,textUser.Text,textPassword.Text,"","",DataConnection.DBtype);
             }
             //a direct connection does not utilize lower privileges.
         }
         catch(Exception ex){
             MessageBox.Show(//Lan.g(this,"Could not establish connection to database."));
                 ex.Message);
             return;
         }
         RemotingClient.RemotingRole=RemotingRole.ClientDirect;
     }
     try{
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.Indent = true;
         settings.IndentChars = ("    ");
         using(XmlWriter writer=XmlWriter.Create(ODFileUtils.CombinePaths(Application.StartupPath,"FreeDentalConfig.xml"),settings)) {
             writer.WriteStartElement("ConnectionSettings");
             if(textConnectionString.Text!="") {
                 writer.WriteStartElement("ConnectionString");
                 writer.WriteString(textConnectionString.Text);
                 writer.WriteEndElement();
             }
             else if(RemotingClient.RemotingRole==RemotingRole.ClientDirect){
                 writer.WriteStartElement("DatabaseConnection");
                 writer.WriteStartElement("ComputerName");
                 writer.WriteString(comboComputerName.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Database");
                 writer.WriteString(comboDatabase.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("User");
                 writer.WriteString(textUser.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Password");
                 writer.WriteString(textPassword.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("NoShowOnStartup");
                 if(checkNoShow.Checked) {
                     writer.WriteString("True");
                 }
                 else {
                     writer.WriteString("False");
                 }
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             else if(RemotingClient.RemotingRole==RemotingRole.ClientWeb){
                 writer.WriteStartElement("ServerConnection");
                 writer.WriteStartElement("URI");
                 writer.WriteString(textURI.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("UsingEcw");
                 if(checkUsingEcw.Checked) {
                     writer.WriteString("True");
                 }
                 else {
                     writer.WriteString("False");
                 }
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             writer.WriteStartElement("DatabaseType");
             if(listType.SelectedIndex==0){
                 writer.WriteString("MySql");
             }
             else{
                 writer.WriteString("Oracle");
             }
             writer.WriteEndElement();
             writer.WriteEndElement();
             writer.Flush();
         }//using writer
     }
     catch{
         //data not saved.
     }
     //fyiReporting.RDL.DataSource.SetOpenDentalConnectionString(
     //	"Server="+ComputerName+";Database="+Database+";User ID="+DbUser+";Password="******";CharSet=utf8");
     DialogResult=DialogResult.OK;
 }
Esempio n. 27
0
 private void butSynch_Click(object sender,EventArgs e)
 {
     if(textUsername.Text=="") {
         MsgBox.Show(this,"Please enter a username first.");
         return;
     }
     if(ReplicationServers.Listt.Count==0) {
         MsgBox.Show(this,"Please add at servers to the list first");
         return;
     }
     Cursor=Cursors.WaitCursor;
     string currentDatabaseName=MiscData.GetCurrentDatabase();
     for(int i=0;i<ReplicationServers.Listt.Count;i++) {
         string compName=ReplicationServers.Listt[i].Descript;
         DataConnection dc=new DataConnection();
         try {
             //try {
             dc.SetDb(compName,currentDatabaseName,textUsername.Text,textPassword.Text,"","",DataConnection.DBtype);
             //}
             //catch(MySql.Data.MySqlClient.MySqlException ex) {
             //	if(ex.Number==1042) {//The error 1042 is issued when the connection could not be made.
             //		throw ex;//Pass the exception along.
             //	}
             //	DataConnection.cmd.Connection.Close();
             //}
             //Connection is considered to be successfull at this point. Now restart the slave process to force replication.
             string command="SLAVE STOP; START SLAVE; SHOW SLAVE STATUS;";
             DataTable slaveStatus=dc.GetTable(command);
             //Wait for the slave process to become active again.
             for(int j=0;j<40 && slaveStatus.Rows[0]["Slave_IO_Running"].ToString().ToLower()!="yes";j++) {
                 Thread.Sleep(1000);
                 command="SHOW SLAVE STATUS";
                 slaveStatus=dc.GetTable(command);
             }
             if(slaveStatus.Rows[0]["Slave_IO_Running"].ToString().ToLower()!="yes") {
                 throw new Exception("Slave IO is not running on computer "+compName);
             }
             if(slaveStatus.Rows[0]["Slave_SQL_Running"].ToString().ToLower()!="yes") {
                 throw new Exception("Slave SQL is not running on computer "+compName);
             }
             //Wait for replication to complete.
             while(slaveStatus.Rows[0]["Slave_IO_State"].ToString().ToLower()!="waiting for master to send event" ||
                 slaveStatus.Rows[0]["Seconds_Behind_Master"].ToString()!="0") {
                 slaveStatus=dc.GetTable(command);
             }
         }
         catch(Exception ex) {
             Cursor=Cursors.Default;
             MessageBox.Show(Lan.g(this,"Error forcing replication on computer")+" "+compName+": "+ex.Message);
             return;//Cancel operation.
         }
     }
     Cursor=Cursors.Default;
     MessageBox.Show(Lan.g(this,"Database synch completed successfully."));
 }
Esempio n. 28
0
 ///<summary>Only called at startup if this dialog is not supposed to be shown.  Must call GetConfig first.</summary>
 public bool TryToConnect()
 {
     if(checkConnectServer.Checked){// && checkUsingEcw.Checked){
         //js commented this portion out in version 12.0 on 1/7/11.  Must hunt down resulting bugs.
         //if(!checkUsingEcw.Checked) {//Can't silently connect unless using eCW.
         //	return false;
         //}
         RemotingClient.ServerURI=textURI.Text;
         try{
             //ecw requires hash, but non-ecw requires actual password
             if(checkUsingEcw.Checked) {
                 //this handles situation where an eCW user passes in an actual OdPassword
                 string password=OdPassHash;
                 if(OdPassword!="") {
                     password=Userods.EncryptPassword(OdPassword,true);
                 }
                 Security.CurUser=Security.LogInWeb(textUser2.Text,password,"",Application.ProductVersion,true);
                 Security.PasswordTyped=password;//so we really store the encrypted pw if ecw user passes in their real password?
             }
             else {
                 Security.CurUser=Security.LogInWeb(textUser2.Text,OdPassword,"",Application.ProductVersion,false);
                 Security.PasswordTyped=OdPassword;
             }
             RemotingClient.RemotingRole=RemotingRole.ClientWeb;
             return true;
         }
         catch{
             return false;
         }
     }
     OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
     //Try to connect to the database directly
     try {
         if(textConnectionString.Text.Length>0){
             dcon.SetDb(textConnectionString.Text,"",DataConnection.DBtype);
         }
         else{
             dcon.SetDb(comboComputerName.Text,comboDatabase.Text,textUser.Text,textPassword.Text,"","",DataConnection.DBtype);
         }
         //a direct connection does not utilize lower privileges.
         RemotingClient.RemotingRole=RemotingRole.ClientDirect;
         return true;
     }
     catch(Exception ex){
         return false;
     }
 }
Esempio n. 29
0
 public void StartManually()
 {
     //connect to OD db.
     XmlDocument document=new XmlDocument();
     string pathXml=Path.Combine(Application.StartupPath,"FreeDentalConfig.xml");
     try{
         document.Load(pathXml);
     }
     catch{
         EventLog.WriteEntry("OpenDentHL7",DateTime.Now.ToLongTimeString()+" - Could not find "+pathXml,EventLogEntryType.Error);
         throw new ApplicationException("Could not find "+pathXml);
     }
     XPathNavigator Navigator=document.CreateNavigator();
     XPathNavigator nav;
     DataConnection.DBtype=DatabaseType.MySql;
     nav=Navigator.SelectSingleNode("//DatabaseConnection");
     string computerName=nav.SelectSingleNode("ComputerName").Value;
     string database=nav.SelectSingleNode("Database").Value;
     string user=nav.SelectSingleNode("User").Value;
     string password=nav.SelectSingleNode("Password").Value;
     XPathNavigator verboseNav=Navigator.SelectSingleNode("//HL7verbose");
     if(verboseNav!=null && verboseNav.Value=="True") {
         IsVerboseLogging=true;
         EventLog.WriteEntry("OpenDentHL7","Verbose mode.",EventLogEntryType.Information);
     }
     OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
     //Try to connect to the database directly
     try {
         dcon.SetDb(computerName,database,user,password,"","",DataConnection.DBtype);
         //a direct connection does not utilize lower privileges.
         RemotingClient.RemotingRole=RemotingRole.ClientDirect;
     }
     catch {//(Exception ex){
         throw new ApplicationException("Connection to database failed.");
     }
     //check db version
     string dbVersion=PrefC.GetString(PrefName.ProgramVersion);
     if(Application.ProductVersion.ToString() != dbVersion) {
         EventLog.WriteEntry("OpenDentHL7","Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString(),EventLogEntryType.Error);
         throw new ApplicationException("Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString());
     }
     //inform od via signal that this service is running
     IsStandalone=true;//and for Mountainside
     if(Programs.UsingEcwTight()){
         IsStandalone=false;
     }
     //#if DEBUG//just so I don't forget to remove it later.
     //IsStandalone=false;
     //#endif
     hl7FolderOut=PrefC.GetString(PrefName.HL7FolderOut);
     if(!Directory.Exists(hl7FolderOut)) {
         throw new ApplicationException(hl7FolderOut+" does not exist.");
     }
     //start polling the folder for waiting messages to import.  Every 5 seconds.
     TimerCallback timercallbackReceive=new TimerCallback(TimerCallbackReceiveFunction);
     timerReceive=new System.Threading.Timer(timercallbackReceive,null,5000,5000);
     if(IsStandalone) {
         return;//do not continue with the HL7 sending code below
     }
     //start polling the db for new HL7 messages to send. Every 1.8 seconds.
     hl7FolderIn=PrefC.GetString(PrefName.HL7FolderIn);
     if(!Directory.Exists(hl7FolderIn)) {
         throw new ApplicationException(hl7FolderIn+" does not exist.");
     }
     TimerCallback timercallbackSend=new TimerCallback(TimerCallbackSendFunction);
     timerSend=new System.Threading.Timer(timercallbackSend,null,1800,1800);
 }
Esempio n. 30
0
 ///<summary>Decrypt the connection string and try to connect to the database directly. Only called if using a connection string and ChooseDatabase is not to be shown. Must call GetOraConfig first.</summary>
 public bool TryWithConnStr()
 {
     OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
     try {
         if(connStr!=null) {
     #if ORA_DB
             OD_CRYPTO.Decryptor crypto=new OD_CRYPTO.Decryptor();
             dconnStr=crypto.Decrypt(connStr,key);
             crypto=null;
             dcon.SetDb(dconnStr,"",DatabaseType.Oracle);
     #endif
         }
         //a direct connection does not utilize lower privileges.
         RemotingClient.RemotingRole=RemotingRole.ClientDirect;
         return true;
     }
     catch(Exception ex) {
         MessageBox.Show(ex.Message);
         return false;
     }
 }
Esempio n. 31
0
		public void StartManually() {
			//connect to OD db.
			XmlDocument document=new XmlDocument();
			string pathXml=Path.Combine(Application.StartupPath,"FreeDentalConfig.xml");
			try {
				document.Load(pathXml);
			}
			catch {
				EventLog.WriteEntry("OpenDentHL7",DateTime.Now.ToLongTimeString()+" - Could not find "+pathXml,EventLogEntryType.Error);
				throw new ApplicationException("Could not find "+pathXml);
			}
			XPathNavigator Navigator=document.CreateNavigator();
			XPathNavigator nav;
			DataConnection.DBtype=DatabaseType.MySql;
			nav=Navigator.SelectSingleNode("//DatabaseConnection");
			string computerName=nav.SelectSingleNode("ComputerName").Value;
			string database=nav.SelectSingleNode("Database").Value;
			string user=nav.SelectSingleNode("User").Value;
			string password=nav.SelectSingleNode("Password").Value;
			XPathNavigator verboseNav=Navigator.SelectSingleNode("//HL7verbose");
			if(verboseNav!=null && verboseNav.Value=="True") {
				IsVerboseLogging=true;
				EventLog.WriteEntry("OpenDentHL7","Verbose mode.",EventLogEntryType.Information);
			}
			OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
			//Try to connect to the database directly
			try {
				dcon.SetDb(computerName,database,user,password,"","",DataConnection.DBtype);
				//a direct connection does not utilize lower privileges.
				RemotingClient.RemotingRole=RemotingRole.ClientDirect;
			}
			catch {//(Exception ex){
				throw new ApplicationException("Connection to database failed.");
			}
			//check db version
			string dbVersion=PrefC.GetString(PrefName.ProgramVersion);
			if(Application.ProductVersion.ToString() != dbVersion) {
				EventLog.WriteEntry("OpenDentHL7","Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString(),EventLogEntryType.Error);
				throw new ApplicationException("Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString());
			}
			#region MedLab HL7
			_medLabHL7DefEnabled=HL7Defs.GetOneDeepEnabled(true);
			if(_medLabHL7DefEnabled!=null) {
				if(_medLabHL7DefEnabled.HL7Server=="") {
					_medLabHL7DefEnabled.HL7Server=System.Environment.MachineName;
					HL7Defs.Update(_medLabHL7DefEnabled);
				}
				if(_medLabHL7DefEnabled.HL7ServiceName=="") {
					_medLabHL7DefEnabled.HL7ServiceName=this.ServiceName;
					HL7Defs.Update(_medLabHL7DefEnabled);
				}
				if(_medLabHL7DefEnabled.HL7Server.ToLower()!=System.Environment.MachineName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The HL7 Server name does not match the name in the enabled MedLab HL7Def Setup.  Server name: "
						+System.Environment.MachineName+", Server name in MedLab HL7Def: "+_medLabHL7DefEnabled.HL7Server,EventLogEntryType.Error);
					throw new ApplicationException("The HL7 Server name does not match the name in the enabled MedLab HL7Def Setup.  Server name: "
						+System.Environment.MachineName+", Server name in MedLab HL7Def: "+_medLabHL7DefEnabled.HL7Server);
				}
				if(_medLabHL7DefEnabled.HL7ServiceName.ToLower()!=this.ServiceName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The MedLab HL7 Service Name does not match the name in the enabled MedLab HL7Def Setup.  Service name: "
						+this.ServiceName+", Service name in MedLab HL7Def: "+_medLabHL7DefEnabled.HL7ServiceName,EventLogEntryType.Error);
					throw new ApplicationException("The MedLab HL7 Service Name does not match the name in the enabled MedLab HL7Def Setup.  Service name: "
						+this.ServiceName+", Service name in MedLab HL7Def: "+_medLabHL7DefEnabled.HL7ServiceName);
				}
				_sftpModeIsReceiving=false;
				TimerCallback timerCallbackSftpGetFiles=new TimerCallback(TimerCallbackSftpGetFiles);
				_timerSftpGetFiles=new System.Threading.Timer(timerCallbackSftpGetFiles,null,1000,60000);//attempt to connect to the sftp server once a minute
			}
			#endregion MedLab HL7
			#region eCW Send and Receive OLD
			if(Programs.IsEnabled(ProgramName.eClinicalWorks) && !HL7Defs.IsExistingHL7Enabled()) {//eCW enabled, and no HL7def enabled.
				//prevent startup:
				long progNum=Programs.GetProgramNum(ProgramName.eClinicalWorks);
				string hl7Server=ProgramProperties.GetPropVal(progNum,"HL7Server");
				string hl7ServiceName=ProgramProperties.GetPropVal(progNum,"HL7ServiceName");
				if(hl7Server=="") {//for the first time run
					ProgramProperties.SetProperty(progNum,"HL7Server",System.Environment.MachineName);
					hl7Server=System.Environment.MachineName;
				}
				if(hl7ServiceName=="") {//for the first time run
					ProgramProperties.SetProperty(progNum,"HL7ServiceName",this.ServiceName);
					hl7ServiceName=this.ServiceName;
				}
				if(hl7Server.ToLower()!=System.Environment.MachineName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: "+System.Environment.MachineName
						+", Server name in Program Links: "+hl7Server,EventLogEntryType.Error);
					throw new ApplicationException("The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: "+System.Environment.MachineName
						+", Server name in Program Links: "+hl7Server);
				}
				if(hl7ServiceName.ToLower()!=this.ServiceName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: "+this.ServiceName+", Service name in Program Links: "
						+hl7ServiceName,EventLogEntryType.Error);
					throw new ApplicationException("The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: "+this.ServiceName+", Service name in Program Links: "
						+hl7ServiceName);
				}
				EcwOldSendAndReceive();
				return;
			}
			#endregion eCW Send and Receive OLD
			#region HL7 Send and Receive New Defs
			HL7Def hL7Def=HL7Defs.GetOneDeepEnabled();
			if(hL7Def==null) {
				return;
			}
			if(hL7Def.HL7Server=="") {
				hL7Def.HL7Server=System.Environment.MachineName;
				HL7Defs.Update(hL7Def);
			}
			if(hL7Def.HL7ServiceName=="") {
				hL7Def.HL7ServiceName=this.ServiceName;
				HL7Defs.Update(hL7Def);
			}
			if(hL7Def.HL7Server.ToLower()!=System.Environment.MachineName.ToLower()) {
				EventLog.WriteEntry("OpenDentHL7","The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: "+System.Environment.MachineName+", Server name in HL7Def: "+hL7Def.HL7Server,
					EventLogEntryType.Error);
				throw new ApplicationException("The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: "+System.Environment.MachineName+", Server name in HL7Def: "+hL7Def.HL7Server);
			}
			if(hL7Def.HL7ServiceName.ToLower()!=this.ServiceName.ToLower()) {
				EventLog.WriteEntry("OpenDentHL7","The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: "+this.ServiceName+", Service name in HL7Def: "+hL7Def.HL7ServiceName,
					EventLogEntryType.Error);
				throw new ApplicationException("The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: "+this.ServiceName+", Service name in HL7Def: "+hL7Def.HL7ServiceName);
			}
			HL7DefEnabled=hL7Def;//so we can access it later from other methods
			#region File Mode
			if(HL7DefEnabled.ModeTx==ModeTxHL7.File) {
				hl7FolderOut=HL7DefEnabled.OutgoingFolder;
				hl7FolderIn=HL7DefEnabled.IncomingFolder;
				if(!Directory.Exists(hl7FolderOut)) {
					EventLog.WriteEntry("OpenDentHL7","The outgoing HL7 folder does not exist.  Path is set to: "+hl7FolderOut,EventLogEntryType.Error);
					throw new ApplicationException("The outgoing HL7 folder does not exist.  Path is set to: "+hl7FolderOut);
				}
				if(!Directory.Exists(hl7FolderIn)) {
					EventLog.WriteEntry("OpenDentHL7","The incoming HL7 folder does not exist.  Path is set to: "+hl7FolderIn,EventLogEntryType.Error);
					throw new ApplicationException("The incoming HL7 folder does not exist.  Path is set to: "+hl7FolderIn);
				}
				_ecwDateTimeOldMsgsDeleted=DateTime.MinValue;
				_ecwFileModeIsSending=false;
				//start polling the folder for waiting messages to import.  Every 5 seconds.
				TimerCallback timercallbackReceive=new TimerCallback(TimerCallbackReceiveFiles);
				timerReceiveFiles=new System.Threading.Timer(timercallbackReceive,null,5000,5000);
				//start polling the db for new HL7 messages to send. Every 1.8 seconds.
				TimerCallback timercallbackSend=new TimerCallback(TimerCallbackSendFiles);
				timerSendFiles=new System.Threading.Timer(timercallbackSend,null,1800,1800);
			}
			#endregion File Mode
			#region TCP/IP Mode
			else {//TCP/IP
				CreateIncomingTcpListener();//this method spawns a new thread for receiving, the main thread returns to perform the sending below
				_ecwTCPSendSocketIsConnected=false;
				_ecwTCPModeIsSending=false;
				//start a timer to connect to the send socket every 20 seconds.  The socket will be reused, so if _ecwTCPSendSocketIsConnected is true, this will just return
				TimerCallback timercallbackSendConnectTCP=new TimerCallback(TimerCallbackSendConnectTCP);
				timerSendConnectTCP=new System.Threading.Timer(timercallbackSendConnectTCP,null,1800,20000);//every 20 seconds, re-connect to the socket if the connection has been closed
			}
			#endregion TCP/IP Mode
			#endregion HL7 Send and Receive New Defs
		}
Esempio n. 32
0
        ///<summary>Throws an exception to display to the user if anything goes wrong.</summary>
        public static void TryToConnect(CentralConnection centralConnection, DatabaseType dbType, string connectionString = "", bool noShowOnStartup = false
                                        , List <string> listAdminCompNames = null, bool isCommandLineArgs = false)
        {
            if (!string.IsNullOrEmpty(centralConnection.ServiceURI))
            {
                LoadMiddleTierProxySettings();
                string originalURI = RemotingClient.ServerURI;
                RemotingClient.ServerURI = centralConnection.ServiceURI;
                bool         useEcwAlgorithm = centralConnection.WebServiceIsEcw;
                RemotingRole originalRole    = RemotingClient.RemotingRole;
                RemotingClient.RemotingRole = RemotingRole.ClientWeb;
                try {
                    string password = centralConnection.OdPassword;
                    if (useEcwAlgorithm)
                    {
                        //Userods.HashPassword explicitly goes over to middle tier in order to use it's MD5 algorithm.
                        //It doesn't matter what Security.CurUser is when it is null because we are technically trying to set it for the first time.
                        //It cannot be null before invoking HashPassword because middle needs it to NOT be null when creating the credentials for DtoGetString.
                        if (Security.CurUser == null)
                        {
                            Security.CurUser = new Userod();
                        }
                        password = Userods.HashPassword(password, true);
                    }
                    string username = centralConnection.OdUser;
#if DEBUG
                    if (username == "")
                    {
                        username = "******";
                        password = "******";
                    }
#endif
                    //ecw requires hash, but non-ecw requires actual password
                    Security.CurUser       = Security.LogInWeb(username, password, "", Application.ProductVersion, useEcwAlgorithm);
                    Security.PasswordTyped = password;                  //for ecw, this is already encrypted.
                }
                catch (Exception ex) {
                    RemotingClient.ServerURI    = originalURI;
                    RemotingClient.RemotingRole = originalRole;
                    throw ex;
                }
            }
            else
            {
                DataConnection.DBtype = dbType;
                DataConnection dcon = new DataConnection();
                if (connectionString.Length > 0)
                {
                    dcon.SetDb(connectionString, "", DataConnection.DBtype);
                }
                else
                {
                    //Password could be plain text password from the Password field of the config file, the decrypted password from the MySQLPassHash field
                    //of the config file, or password entered by the user and can be blank (empty string) in all cases
                    dcon.SetDb(centralConnection.ServerName, centralConnection.DatabaseName, centralConnection.MySqlUser
                               , centralConnection.MySqlPassword, "", "", DataConnection.DBtype);
                }
                //a direct connection does not utilize lower privileges.
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
            }
            TrySaveConnectionSettings(centralConnection, dbType, connectionString, noShowOnStartup, listAdminCompNames, isCommandLineArgs);
        }
 private void butOK_Click(object sender, System.EventArgs e)
 {
     if (checkConnectServer.Checked)
     {
         if (textPort.errorProvider1.GetError(textPort) != "")
         {
             MsgBox.Show(this, "Please fix data entry errors first.");
             return;
         }
         string originalServer = RemotingClient.ServerName;
         int    originalPort   = RemotingClient.ServerPort;
         RemotingClient.ServerName = comboServerName2.Text;
         RemotingClient.ServerPort = PIn.PInt(textPort.Text);
         DtoLogin dto = new DtoLogin();
         dto.Database   = comboDatabase2.Text;
         dto.OdUser     = textUser2.Text;
         dto.OdPassHash = UserodB.EncryptPassword(textPassword2.Text);
         try{
             RemotingClient.ProcessCommand(dto);
             RemotingClient.OpenDentBusinessIsLocal = false;
         }
         catch (Exception ex) {
             RemotingClient.ServerName = originalServer;
             RemotingClient.ServerPort = originalPort;
             MessageBox.Show(ex.Message);
             return;
         }
     }
     else
     {
         OpenDentBusiness.DataConnection dcon;
         //Try to connect to the database directly
         try {
             DBtype = DatabaseType.MySql;
             if (listType.SelectedIndex == 1)
             {
                 DBtype = DatabaseType.Oracle;
             }
             dcon = new OpenDentBusiness.DataConnection(DBtype);
             if (textConnectionString.Text.Length > 0)
             {
                 dcon.SetDb(textConnectionString.Text, "", DBtype);
             }
             else
             {
                 dcon.SetDb(comboComputerName.Text, comboDatabase.Text, textUser.Text, textPassword.Text, "", "", DBtype);
             }
             //a direct connection does not utilize lower privileges.
         }
         catch (Exception ex) {
             MessageBox.Show(                    //Lan.g(this,"Could not establish connection to database."));
                 ex.Message);
             return;
         }
         RemotingClient.OpenDentBusinessIsLocal = true;
     }
     try{
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.Indent      = true;
         settings.IndentChars = ("    ");
         using (XmlWriter writer = XmlWriter.Create("FreeDentalConfig.xml", settings)) {
             writer.WriteStartElement("ConnectionSettings");
             if (RemotingClient.OpenDentBusinessIsLocal)
             {
                 writer.WriteStartElement("DatabaseConnection");
                 writer.WriteStartElement("ComputerName");
                 writer.WriteString(comboComputerName.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Database");
                 writer.WriteString(comboDatabase.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("User");
                 writer.WriteString(textUser.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Password");
                 writer.WriteString(textPassword.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("NoShowOnStartup");
                 if (checkNoShow.Checked)
                 {
                     writer.WriteString("True");
                 }
                 else
                 {
                     writer.WriteString("False");
                 }
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             else
             {
                 writer.WriteStartElement("ServerConnection");
                 writer.WriteStartElement("ComputerName");
                 writer.WriteString(comboServerName2.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("ServerPort");
                 writer.WriteString(textPort.Text);
                 writer.WriteEndElement();
                 writer.WriteStartElement("Database");
                 writer.WriteString(comboDatabase2.Text);
                 writer.WriteEndElement();
                 writer.WriteEndElement();
             }
             writer.WriteStartElement("DatabaseType");
             if (listType.SelectedIndex == 0)
             {
                 writer.WriteString("MySql");
             }
             else
             {
                 writer.WriteString("Oracle");
             }
             writer.WriteEndElement();
             writer.WriteEndElement();
             writer.Flush();
         }                //using writer
     }
     catch {
         //data not saved.
     }
     //fyiReporting.RDL.DataSource.SetOpenDentalConnectionString(
     //	"Server="+ComputerName+";Database="+Database+";User ID="+DbUser+";Password="******";CharSet=utf8");
     DialogResult = DialogResult.OK;
 }
Esempio n. 34
0
        public void StartManually()
        {
            //connect to OD db.
            XmlDocument document = new XmlDocument();
            string      pathXml  = Path.Combine(Application.StartupPath, "FreeDentalConfig.xml");

            try{
                document.Load(pathXml);
            }
            catch {
                EventLog.WriteEntry("OpenDentHL7", DateTime.Now.ToLongTimeString() + " - Could not find " + pathXml, EventLogEntryType.Error);
                throw new ApplicationException("Could not find " + pathXml);
            }
            XPathNavigator Navigator = document.CreateNavigator();
            XPathNavigator nav;

            DataConnection.DBtype = DatabaseType.MySql;
            nav = Navigator.SelectSingleNode("//DatabaseConnection");
            string         computerName = nav.SelectSingleNode("ComputerName").Value;
            string         database     = nav.SelectSingleNode("Database").Value;
            string         user         = nav.SelectSingleNode("User").Value;
            string         password     = nav.SelectSingleNode("Password").Value;
            XPathNavigator verboseNav   = Navigator.SelectSingleNode("//HL7verbose");

            if (verboseNav != null && verboseNav.Value == "True")
            {
                IsVerboseLogging = true;
                EventLog.WriteEntry("OpenDentHL7", "Verbose mode.", EventLogEntryType.Information);
            }
            OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
            //Try to connect to the database directly
            try {
                dcon.SetDb(computerName, database, user, password, "", "", DataConnection.DBtype);
                //a direct connection does not utilize lower privileges.
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
            }
            catch {            //(Exception ex){
                throw new ApplicationException("Connection to database failed.");
            }
            //check db version
            string dbVersion = PrefC.GetString(PrefName.ProgramVersion);

            if (Application.ProductVersion.ToString() != dbVersion)
            {
                EventLog.WriteEntry("OpenDentHL7", "Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString(), EventLogEntryType.Error);
                throw new ApplicationException("Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString());
            }
            if (Programs.IsEnabled(ProgramName.eClinicalWorks) && !HL7Defs.IsExistingHL7Enabled())             //eCW enabled, and no HL7def enabled.
            //prevent startup:
            {
                long   progNum        = Programs.GetProgramNum(ProgramName.eClinicalWorks);
                string hl7Server      = ProgramProperties.GetPropVal(progNum, "HL7Server");
                string hl7ServiceName = ProgramProperties.GetPropVal(progNum, "HL7ServiceName");
                if (hl7Server == "")               //for the first time run
                {
                    ProgramProperties.SetProperty(progNum, "HL7Server", System.Environment.MachineName);
                    hl7Server = System.Environment.MachineName;
                }
                if (hl7ServiceName == "")               //for the first time run
                {
                    ProgramProperties.SetProperty(progNum, "HL7ServiceName", this.ServiceName);
                    hl7ServiceName = this.ServiceName;
                }
                if (hl7Server.ToLower() != System.Environment.MachineName.ToLower())
                {
                    EventLog.WriteEntry("OpenDentHL7", "The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: " + System.Environment.MachineName
                                        + ", Server name in Program Links: " + hl7Server, EventLogEntryType.Error);
                    throw new ApplicationException("The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: " + System.Environment.MachineName
                                                   + ", Server name in Program Links: " + hl7Server);
                }
                if (hl7ServiceName.ToLower() != this.ServiceName.ToLower())
                {
                    EventLog.WriteEntry("OpenDentHL7", "The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: " + this.ServiceName + ", Service name in Program Links: "
                                        + hl7ServiceName, EventLogEntryType.Error);
                    throw new ApplicationException("The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: " + this.ServiceName + ", Service name in Program Links: "
                                                   + hl7ServiceName);
                }
                EcwOldSendAndReceive();
                return;
            }
            HL7Def hL7Def = HL7Defs.GetOneDeepEnabled();

            if (hL7Def == null)
            {
                return;
            }
            if (hL7Def.HL7Server == "")
            {
                hL7Def.HL7Server = System.Environment.MachineName;
                HL7Defs.Update(hL7Def);
            }
            if (hL7Def.HL7ServiceName == "")
            {
                hL7Def.HL7ServiceName = this.ServiceName;
                HL7Defs.Update(hL7Def);
            }
            if (hL7Def.HL7Server.ToLower() != System.Environment.MachineName.ToLower())
            {
                EventLog.WriteEntry("OpenDentHL7", "The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: " + System.Environment.MachineName + ", Server name in HL7Def: " + hL7Def.HL7Server,
                                    EventLogEntryType.Error);
                throw new ApplicationException("The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: " + System.Environment.MachineName + ", Server name in HL7Def: " + hL7Def.HL7Server);
            }
            if (hL7Def.HL7ServiceName.ToLower() != this.ServiceName.ToLower())
            {
                EventLog.WriteEntry("OpenDentHL7", "The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: " + this.ServiceName + ", Service name in HL7Def: " + hL7Def.HL7ServiceName,
                                    EventLogEntryType.Error);
                throw new ApplicationException("The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: " + this.ServiceName + ", Service name in HL7Def: " + hL7Def.HL7ServiceName);
            }
            HL7DefEnabled = hL7Def;          //so we can access it later from other methods
            if (HL7DefEnabled.ModeTx == ModeTxHL7.File)
            {
                hl7FolderOut = HL7DefEnabled.OutgoingFolder;
                hl7FolderIn  = HL7DefEnabled.IncomingFolder;
                if (!Directory.Exists(hl7FolderOut))
                {
                    EventLog.WriteEntry("OpenDentHL7", "The outgoing HL7 folder does not exist.  Path is set to: " + hl7FolderOut, EventLogEntryType.Error);
                    throw new ApplicationException("The outgoing HL7 folder does not exist.  Path is set to: " + hl7FolderOut);
                }
                if (!Directory.Exists(hl7FolderIn))
                {
                    EventLog.WriteEntry("OpenDentHL7", "The incoming HL7 folder does not exist.  Path is set to: " + hl7FolderIn, EventLogEntryType.Error);
                    throw new ApplicationException("The incoming HL7 folder does not exist.  Path is set to: " + hl7FolderIn);
                }
                //start polling the folder for waiting messages to import.  Every 5 seconds.
                TimerCallback timercallbackReceive = new TimerCallback(TimerCallbackReceiveFiles);
                timerReceiveFiles = new System.Threading.Timer(timercallbackReceive, null, 5000, 5000);
                //start polling the db for new HL7 messages to send. Every 1.8 seconds.
                TimerCallback timercallbackSend = new TimerCallback(TimerCallbackSendFiles);
                timerSendFiles = new System.Threading.Timer(timercallbackSend, null, 1800, 1800);
            }
            else              //TCP/IP
            {
                CreateIncomingTcpListener();
                //start a timer to poll the database and to send messages as needed.  Every 6 seconds.  We increased the time between polling the database from 3 seconds to 6 seconds because we are now waiting 5 seconds for a message acknowledgment from eCW.
                TimerCallback timercallbackSendTCP = new TimerCallback(TimerCallbackSendTCP);
                timerSendTCP = new System.Threading.Timer(timercallbackSendTCP, null, 1800, 6000);
            }
        }
Esempio n. 35
0
File: Util.cs Progetto: mnisl/OD
		public void SetMobileDbConnection() {
			string connectStr=Properties.Settings.Default.DBMobileWeb;
			OpenDentBusiness.DataConnection dc=new OpenDentBusiness.DataConnection();
			dc.SetDb(connectStr,"",DatabaseType.MySql,true);
		}
Esempio n. 36
0
        ///<summary>Used when viewing securityLog from the security admin window.  PermTypes can be length 0 to get all types.</summary>
        public static SecurityLog[] Refresh(DateTime dateFrom, DateTime dateTo, Permissions permType, long patNum, long userNum,
                                            DateTime datePreviousFrom, DateTime datePreviousTo, bool includeArchived, int limit = 0)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <SecurityLog[]>(MethodBase.GetCurrentMethod(), dateFrom, dateTo, permType, patNum, userNum, datePreviousFrom, datePreviousTo, includeArchived, limit));
            }
            string command = "SELECT securitylog.*,LName,FName,Preferred,MiddleI,LogHash FROM securitylog "
                             + "LEFT JOIN patient ON patient.PatNum=securitylog.PatNum "
                             + "LEFT JOIN securityloghash ON securityloghash.SecurityLogNum=securitylog.SecurityLogNum "
                             + "WHERE LogDateTime >= " + POut.Date(dateFrom) + " "
                             + "AND LogDateTime <= " + POut.Date(dateTo.AddDays(1)) + " "
                             + "AND DateTPrevious >= " + POut.Date(datePreviousFrom) + " "
                             + "AND DateTPrevious <= " + POut.Date(datePreviousTo.AddDays(1));

            if (patNum != 0)
            {
                command += " AND securitylog.PatNum IN (" + string.Join(",",
                                                                        PatientLinks.GetPatNumsLinkedToRecursive(patNum, PatientLinkType.Merge).Select(x => POut.Long(x))) + ")";
            }
            if (permType != Permissions.None)
            {
                command += " AND PermType=" + POut.Long((int)permType);
            }
            if (userNum != 0)
            {
                command += " AND UserNum=" + POut.Long(userNum);
            }
            command += " ORDER BY LogDateTime DESC";          //Using DESC so that the most recent ones appear in the list
            if (limit > 0)
            {
                command = DbHelper.LimitOrderBy(command, limit);
            }
            DataTable          table    = Db.GetTable(command);
            List <SecurityLog> listLogs = Crud.SecurityLogCrud.TableToList(table);

            for (int i = 0; i < listLogs.Count; i++)
            {
                if (table.Rows[i]["PatNum"].ToString() == "0")
                {
                    listLogs[i].PatientName = "";
                }
                else
                {
                    listLogs[i].PatientName = table.Rows[i]["PatNum"].ToString() + "-"
                                              + Patients.GetNameLF(table.Rows[i]["LName"].ToString()
                                                                   , table.Rows[i]["FName"].ToString()
                                                                   , table.Rows[i]["Preferred"].ToString()
                                                                   , table.Rows[i]["MiddleI"].ToString());
                }
                listLogs[i].LogHash = table.Rows[i]["LogHash"].ToString();
            }
            if (includeArchived && dateFrom <= PrefC.GetDate(PrefName.ArchiveDate))           //They are attempting to find security logs that are prior to archived date.
            {
                string decryptedPass;
                CDT.Class1.Decrypt(PrefC.GetString(PrefName.ArchivePassHash), out decryptedPass);
                string         connectionStrOrig = DataConnection.GetCurrentConnectionString();
                DatabaseType   dbTypeOrig        = DataConnection.DBtype;
                DataConnection dcon = new DataConnection();
                //Connect to archive database
                dcon.SetDb(PrefC.GetString(PrefName.ArchiveServerName) == ""?PrefC.GetString(PrefName.ArchiveServerURI):PrefC.GetString(PrefName.ArchiveServerName),
                           "opendentalarchive", PrefC.GetString(PrefName.ArchiveUserName), decryptedPass, "", "", dbTypeOrig);
                DataTable          tableArchive    = Db.GetTable(command);  //Query the archive
                List <SecurityLog> listLogsArchive = Crud.SecurityLogCrud.TableToList(tableArchive);
                dcon.SetDb(connectionStrOrig, "", dbTypeOrig);              //Reconnect to initial db
                Dictionary <long, Patient> dictPats = Patients.GetMultPats(listLogsArchive.Select(x => x.PatNum).Distinct().ToList())
                                                      .ToDictionary(x => x.PatNum);
                for (int i = 0; i < listLogsArchive.Count; i++)
                {
                    Patient pat;
                    if (listLogsArchive[i].PatNum == 0 || !dictPats.TryGetValue(listLogsArchive[i].PatNum, out pat))
                    {
                        listLogsArchive[i].PatientName = "";
                    }
                    else
                    {
                        listLogsArchive[i].PatientName = listLogsArchive[i].PatNum + "-" + pat.GetNameLF();
                    }
                    listLogsArchive[i].LogHash = tableArchive.Rows[i]["LogHash"].ToString();
                }
                listLogs.AddRange(listLogsArchive);                //Add archived entries to returned list.
            }
            return(listLogs.OrderBy(x => x.LogDateTime).ToArray());
        }
Esempio n. 37
0
		public void StartManually() {
			//connect to OD db.
			XmlDocument document=new XmlDocument();
			string pathXml=Path.Combine(Application.StartupPath,"FreeDentalConfig.xml");
			try{
				document.Load(pathXml);
			}
			catch{
				EventLog.WriteEntry("OpenDentHL7",DateTime.Now.ToLongTimeString()+" - Could not find "+pathXml,EventLogEntryType.Error);
				throw new ApplicationException("Could not find "+pathXml);
			}
			XPathNavigator Navigator=document.CreateNavigator();
			XPathNavigator nav;
			DataConnection.DBtype=DatabaseType.MySql;
			nav=Navigator.SelectSingleNode("//DatabaseConnection");
			string computerName=nav.SelectSingleNode("ComputerName").Value;
			string database=nav.SelectSingleNode("Database").Value;
			string user=nav.SelectSingleNode("User").Value;
			string password=nav.SelectSingleNode("Password").Value;
			XPathNavigator verboseNav=Navigator.SelectSingleNode("//HL7verbose");
			if(verboseNav!=null && verboseNav.Value=="True") {
				IsVerboseLogging=true;
				EventLog.WriteEntry("OpenDentHL7","Verbose mode.",EventLogEntryType.Information);
			}
			OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
			//Try to connect to the database directly
			try {
				dcon.SetDb(computerName,database,user,password,"","",DataConnection.DBtype);
				//a direct connection does not utilize lower privileges.
				RemotingClient.RemotingRole=RemotingRole.ClientDirect;
			}
			catch {//(Exception ex){
				throw new ApplicationException("Connection to database failed.");
			}
			//check db version
			string dbVersion=PrefC.GetString(PrefName.ProgramVersion);
			if(Application.ProductVersion.ToString() != dbVersion) {
				EventLog.WriteEntry("OpenDentHL7","Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString(),EventLogEntryType.Error);
				throw new ApplicationException("Versions do not match.  Db version:"+dbVersion+".  Application version:"+Application.ProductVersion.ToString());
			}
			if(Programs.IsEnabled(ProgramName.eClinicalWorks) && !HL7Defs.IsExistingHL7Enabled()) {//eCW enabled, and no HL7def enabled.
				//prevent startup:
				long progNum=Programs.GetProgramNum(ProgramName.eClinicalWorks);
				string hl7Server=ProgramProperties.GetPropVal(progNum,"HL7Server");
				string hl7ServiceName=ProgramProperties.GetPropVal(progNum,"HL7ServiceName");
				if(hl7Server=="") {//for the first time run
					ProgramProperties.SetProperty(progNum,"HL7Server",System.Environment.MachineName);
					hl7Server=System.Environment.MachineName;
				}
				if(hl7ServiceName=="") {//for the first time run
					ProgramProperties.SetProperty(progNum,"HL7ServiceName",this.ServiceName);
					hl7ServiceName=this.ServiceName;
				}
				if(hl7Server.ToLower()!=System.Environment.MachineName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: "+System.Environment.MachineName
						+", Server name in Program Links: "+hl7Server,EventLogEntryType.Error);
					throw new ApplicationException("The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: "+System.Environment.MachineName
						+", Server name in Program Links: "+hl7Server);
				}
				if(hl7ServiceName.ToLower()!=this.ServiceName.ToLower()) {
					EventLog.WriteEntry("OpenDentHL7","The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: "+this.ServiceName+", Service name in Program Links: "
						+hl7ServiceName,EventLogEntryType.Error);
					throw new ApplicationException("The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: "+this.ServiceName+", Service name in Program Links: "
						+hl7ServiceName);
				}
				EcwOldSendAndReceive();
				return;
			}
			HL7Def hL7Def=HL7Defs.GetOneDeepEnabled();
			if(hL7Def==null) {
				return;
			}
			if(hL7Def.HL7Server=="") {
				hL7Def.HL7Server=System.Environment.MachineName;
				HL7Defs.Update(hL7Def);
			}
			if(hL7Def.HL7ServiceName=="") {
				hL7Def.HL7ServiceName=this.ServiceName;
				HL7Defs.Update(hL7Def);
			}
			if(hL7Def.HL7Server.ToLower()!=System.Environment.MachineName.ToLower()) {
				EventLog.WriteEntry("OpenDentHL7","The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: "+System.Environment.MachineName+", Server name in HL7Def: "+hL7Def.HL7Server,
					EventLogEntryType.Error);
				throw new ApplicationException("The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: "+System.Environment.MachineName+", Server name in HL7Def: "+hL7Def.HL7Server);
			}
			if(hL7Def.HL7ServiceName.ToLower()!=this.ServiceName.ToLower()) {
				EventLog.WriteEntry("OpenDentHL7","The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: "+this.ServiceName+", Service name in HL7Def: "+hL7Def.HL7ServiceName,
					EventLogEntryType.Error);
				throw new ApplicationException("The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: "+this.ServiceName+", Service name in HL7Def: "+hL7Def.HL7ServiceName);
			}
			HL7DefEnabled=hL7Def;//so we can access it later from other methods
			if(HL7DefEnabled.ModeTx==ModeTxHL7.File) {
				hl7FolderOut=HL7DefEnabled.OutgoingFolder;
				hl7FolderIn=HL7DefEnabled.IncomingFolder;
				if(!Directory.Exists(hl7FolderOut)) {
					EventLog.WriteEntry("OpenDentHL7","The outgoing HL7 folder does not exist.  Path is set to: "+hl7FolderOut,EventLogEntryType.Error);
					throw new ApplicationException("The outgoing HL7 folder does not exist.  Path is set to: "+hl7FolderOut);
				}
				if(!Directory.Exists(hl7FolderIn)) {
					EventLog.WriteEntry("OpenDentHL7","The incoming HL7 folder does not exist.  Path is set to: "+hl7FolderIn,EventLogEntryType.Error);
					throw new ApplicationException("The incoming HL7 folder does not exist.  Path is set to: "+hl7FolderIn);
				}
				//start polling the folder for waiting messages to import.  Every 5 seconds.
				TimerCallback timercallbackReceive=new TimerCallback(TimerCallbackReceiveFiles);
				timerReceiveFiles=new System.Threading.Timer(timercallbackReceive,null,5000,5000);
				//start polling the db for new HL7 messages to send. Every 1.8 seconds.
				TimerCallback timercallbackSend=new TimerCallback(TimerCallbackSendFiles);
				timerSendFiles=new System.Threading.Timer(timercallbackSend,null,1800,1800);
			}
			else {//TCP/IP
				CreateIncomingTcpListener();
				//start a timer to poll the database and to send messages as needed.  Every 6 seconds.  We increased the time between polling the database from 3 seconds to 6 seconds because we are now waiting 5 seconds for a message acknowledgment from eCW.
				TimerCallback timercallbackSendTCP=new TimerCallback(TimerCallbackSendTCP);
				timerSendTCP=new System.Threading.Timer(timercallbackSendTCP,null,1800,6000);
			}
		}
Esempio n. 38
0
		private void RunAnnual() {
			_dateFrom=PIn.Date(textDateFrom.Text);
			_dateTo=PIn.Date(textDateTo.Text);
			List<DataSet> listProdData=new List<DataSet>();
			List<string> listServerNames=new List<string>();
			List<long> listProvNums=new List<long>();
			List<long> listClinicNums=new List<long>();
			string computerName="";
			string database="";
			string user="";
			string mySqlPassword="";
			string strFailedConn="";
			string webServiceURI="";
			string odPassword="";
			for(int i=0;i<ConnList.Count;i++) {
				if(ConnList[i].DatabaseName!="") {
					//ServerName=localhost DatabaseName=opendental MySqlUser=root MySqlPassword=
					computerName=ConnList[i].ServerName;
					database=ConnList[i].DatabaseName;
					user=ConnList[i].MySqlUser;
					if(ConnList[i].MySqlPassword!="") {
						mySqlPassword=CentralConnections.Decrypt(ConnList[i].MySqlPassword,EncryptionKey);
					}
					RemotingClient.ServerURI="";
				}
				else if(ConnList[i].ServiceURI!="") {
					webServiceURI=ConnList[i].ServiceURI;
					RemotingClient.ServerURI=webServiceURI;
					try {
						odPassword=CentralConnections.Decrypt(ConnList[i].OdPassword,EncryptionKey);
						Security.CurUser=Security.LogInWeb(ConnList[i].OdUser,odPassword,"",Application.ProductVersion,ConnList[i].WebServiceIsEcw);
						Security.PasswordTyped=odPassword;
					}
					catch {
						//Not sure if anything needs to be here
					}
				}
				else {
					MessageBox.Show("Either a database or a Middle Tier URI must be specified in the connection.");
					return;
				}
				DataConnection.DBtype=DatabaseType.MySql;
				OpenDentBusiness.DataConnection dcon=new OpenDentBusiness.DataConnection();
				try {
					if(RemotingClient.ServerURI!="") {
						RemotingClient.RemotingRole=RemotingRole.ClientWeb;
					}
					else {
						dcon.SetDb(computerName,database,user,mySqlPassword,"","",DataConnection.DBtype);
						RemotingClient.RemotingRole=RemotingRole.ClientDirect;
					}
					Cache.RefreshCache(((int)InvalidType.AllLocal).ToString());
				}
				catch(Exception ex) {
					if(strFailedConn=="") {
						strFailedConn+="Some connections could not successfully be created for this report:\r\n";
					}
					if(RemotingClient.ServerURI!="") {
						strFailedConn+="WebService: "+webServiceURI+"\r\n";
					}
					else {
						strFailedConn+="Server: "+computerName+" DataBase: "+database+"\r\n";
					}
					continue;
				}
				listProvNums=new List<long>();
				for(int j=0;j<ProviderC.ListShort.Count;j++) {
					listProvNums.Add(ProviderC.ListShort[j].ProvNum);
				}
				listClinicNums=new List<long>();
				listClinicNums.Add(0);//Unassigned
				for(int j=0;j<Clinics.List.Length;j++) {
					listClinicNums.Add(Clinics.List[j].ClinicNum);
				}
				listProdData.Add(RpProdInc.GetAnnualDataForClinics(_dateFrom,_dateTo,listProvNums,listClinicNums,radioWriteoffPay.Checked,true,true));
				if(ConnList[i].ServiceURI!="") {
					listServerNames.Add(ConnList[i].ServiceURI);
				}
				else {
					listServerNames.Add(ConnList[i].ServerName);
				}
				//Cleaning up after WebService connections.
				Security.CurUser=null;
				Security.PasswordTyped=null;
			}
			ReportComplex report=new ReportComplex(true,true);
			report.ReportName="Appointments";
			report.AddTitle("Title",Lan.g(this,"Annual Production and Income"));
			report.AddSubTitle("PracName",PrefC.GetString(PrefName.PracticeTitle));
			report.AddSubTitle("Date",_dateFrom.ToShortDateString()+" - "+_dateTo.ToShortDateString());
			report.AddSubTitle("Providers",Lan.g(this,"All Providers"));
			report.AddSubTitle("Clinics",Lan.g(this,"All Clinics"));
			//setup query
			QueryObject query;
			DataSet dsTotal=new DataSet();
			for(int i=0;i<listProdData.Count;i++) {
				DataTable dt=listProdData[i].Tables["Clinic"];
				DataTable dtTot=listProdData[i].Tables["Total"].Copy();
				dtTot.TableName=dtTot.TableName+"_"+i;
				dsTotal.Tables.Add(dtTot);
				query=report.AddQuery(dt,listServerNames[i],"Clinic",SplitByKind.Value,1,true);
				// add columns to report
				query.AddColumn("Month",75,FieldValueType.String);
				query.AddColumn("Production",120,FieldValueType.Number);
				query.AddColumn("Adjustments",120,FieldValueType.Number);
				query.AddColumn("Writeoff",120,FieldValueType.Number);
				query.AddColumn("Tot Prod",120,FieldValueType.Number);
				query.AddColumn("Pt Income",120,FieldValueType.Number);
				query.AddColumn("Ins Income",120,FieldValueType.Number);
				query.AddColumn("Total Income",120,FieldValueType.Number);
			}
			if(dsTotal.Tables.Count==0) {
				MsgBox.Show(this,"This report returned no values");
				return;
			}
			DataTable dtTotal;
			decimal production;
			decimal adjust;
			decimal inswriteoff;	//spk 5/19/05
			decimal totalproduction;
			decimal ptincome;
			decimal insincome;
			decimal totalincome;
			DateTime[] dates=new DateTime[_dateTo.Month-_dateFrom.Month+1];
			dtTotal=dsTotal.Tables[0].Clone();
			for(int i=0;i<dates.Length;i++) {//usually 12 months in loop
				dates[i]=_dateFrom.AddMonths(i);
				DataRow row=dtTotal.NewRow();
				row[0]=dates[i].ToString("MMM yy");//JAN 14
				production=0;
				adjust=0;
				inswriteoff=0;	//spk 5/19/05
				totalproduction=0;
				ptincome=0;
				insincome=0;
				totalincome=0;
				for(int j=0;j<dsTotal.Tables.Count;j++) {
					for(int k=0;k<dsTotal.Tables[j].Rows.Count;k++) {
						if(dsTotal.Tables[j].Rows[k][0].ToString()==dates[i].ToString("MMM yy")) {
							production+=PIn.Decimal(dsTotal.Tables[j].Rows[k]["Production"].ToString());
							adjust+=PIn.Decimal(dsTotal.Tables[j].Rows[k]["Adjustments"].ToString());
							inswriteoff-=PIn.Decimal(dsTotal.Tables[j].Rows[k]["WriteOff"].ToString());
							ptincome+=PIn.Decimal(dsTotal.Tables[j].Rows[k]["Pt Income"].ToString());
							insincome+=PIn.Decimal(dsTotal.Tables[j].Rows[k]["Ins Income"].ToString());
						}
					}
				}
				totalproduction=production+adjust+inswriteoff;
				totalincome=ptincome+insincome;
				row[1]=production.ToString("n");
				row[2]=adjust.ToString("n");
				row[3]=inswriteoff.ToString("n");
				row[4]=totalproduction.ToString("n");
				row[5]=ptincome.ToString("n");
				row[6]=insincome.ToString("n");
				row[7]=totalincome.ToString("n");
				dtTotal.Rows.Add(row);
			}
			//For clinics only, we want to add one last table to the end of the report that totals all clinics together.
			query=report.AddQuery(dtTotal,"Totals","",SplitByKind.None,2,true);
			query.AddColumn("Month",75,FieldValueType.String);
			query.AddColumn("Production",120,FieldValueType.Number);
			query.AddColumn("Adjustments",120,FieldValueType.Number);
			query.AddColumn("Writeoff",120,FieldValueType.Number);
			query.AddColumn("Tot Prod",120,FieldValueType.Number);
			query.AddColumn("Pt Income",120,FieldValueType.Number);
			query.AddColumn("Ins Income",120,FieldValueType.Number);
			query.AddColumn("Total Income",120,FieldValueType.Number);
			report.AddPageNum();
			// execute query
			if(!report.SubmitQueries()) {//Does not actually submit queries because we use datatables in the central management tool.
				return;
			}
			if(strFailedConn!="") {
				MsgBoxCopyPaste msgBoxCP=new MsgBoxCopyPaste(strFailedConn);
				msgBoxCP.ShowDialog();
			}
			// display the report
			FormReportComplex FormR=new FormReportComplex(report);
			FormR.ShowDialog();
			DialogResult=DialogResult.OK;
		}