Esempio n. 1
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. 2
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. 3
0
File: DataCore.cs Progetto: mnisl/OD
		///<summary>Only used if using the server component.  This is used for queries written by the user.  It uses the user with lower privileges  to prevent injection attack.</summary>
		public static DataTable GetTableLow(string command) {
			DataConnection dcon=new DataConnection(true);
			DataTable table=dcon.GetTable(command);
			//DataSet retVal=new DataSet();
			//retVal.Tables.Add(table);
			return table;
		}
Esempio n. 4
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
			IPHostEntry iphostentry=Dns.GetHostEntry(Environment.MachineName);
			DataConnection dbcon=new DataConnection();
			try {
				dbcon.SetDb("10.10.1.200","customers","root","","","",DatabaseType.MySql);
			}
			catch {
				MessageBox.Show("This tool is not designed for general use.");
				return;
			}
			//get ipaddress on startup
			IpAddressCur="";
			foreach(IPAddress ipaddress in iphostentry.AddressList) {
				if(ipaddress.ToString().Contains("10.10.2")) {
					IpAddressCur=ipaddress.ToString();
				}
			}
			intPtrVideo=IntPtr.Zero;
			timerPhoneWebCam.Enabled=true;
			timerScreenShots.Enabled=true;
			timerScreenShots_Tick(this,new EventArgs());//force an initial screenshot
		}
Esempio n. 5
0
 ///<summary>Returns a collection of unique AtoZ folders for the array of dbnames passed in.  It will not include the current AtoZ folder for this database, even if shared by another db.</summary>
 public static List<string> GetAtoZforDb(string[] dbNames)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         throw new ApplicationException("MiscData.GetAtoZforDb failed.  Updates not allowed from ClientWeb.");
     }
     List<string> retval=new List<string>();
     DataConnection dcon=null;
     string atozName;
     string atozThisDb=PrefC.GetString(PrefName.DocPath);
     for(int i=0;i<dbNames.Length;i++) {
         try {
             dcon=new DataConnection(dbNames[i]);
             string command="SELECT ValueString FROM preference WHERE PrefName='DocPath'";
             atozName=dcon.GetScalar(command);
             if(retval.Contains(atozName)) {
                 continue;
             }
             if(atozName==atozThisDb) {
                 continue;
             }
             retval.Add(atozName);
         }
         catch {
             //don't add it to the list
         }
     }
     return retval;
 }
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
File: DataCore.cs Progetto: mnisl/OD
		///<summary></summary>
		public static DataTable GetTable(string command) {
			DataConnection dcon=new DataConnection();
			DataTable table=dcon.GetTable(command);
			//DataSet retVal=new DataSet();
			//table.TableName="table";
			//retVal.Tables.Add(table);
			//retVal.Tables[0].TableName="";
			return table;//retVal;
		}
Esempio n. 8
0
		///<summary>If using remoting, then the calling program is responsible for filling the arrays on the client since the automated part only happens on the server.  So there are TWO sets of arrays in a server situation, but only one in a small office that connects directly to the database.</summary>
		public static DataTable RefreshCache(){
			//No need to check RemotingRole; Calls GetTableRemotelyIfNeeded().
			string command="SELECT * FROM definition ORDER BY Category,ItemOrder";
			DataConnection dcon=new DataConnection();
			DataTable table=Cache.GetTableRemotelyIfNeeded(MethodBase.GetCurrentMethod(),command);
			table.TableName="Def";
			FillCache(table);
			return table;
		}
Esempio n. 9
0
File: DataCore.cs Progetto: mnisl/OD
		///<summary>This query is run with full privileges.  This is for commands generated by the main program, and the user will not have access for injection attacks.  Result is usually number of rows changed, or can be insert id if requested.</summary>
		public static long NonQ(string command,bool getInsertID,params OdSqlParameter[] parameters) {
			DataConnection dcon=new DataConnection();
			long rowsChanged=dcon.NonQ(command,getInsertID,parameters);
			if(getInsertID){
				return (long)dcon.InsertID;
			}
			else{
				return rowsChanged;
			}
		}
Esempio n. 10
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. 11
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. 12
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. 13
0
 ///<summary>For a given date, gets a list of dateTimes of missed calls.  Gets directly from the Asterisk database, hard-coded.</summary>
 public static List<DateTime> GetMissedCalls(DateTime date)
 {
     DataConnection dcon=new DataConnection("192.168.0.197","asteriskcdrdb","opendental","secret",DatabaseType.MySql);
     string command="SELECT calldate FROM cdr WHERE "+DbHelper.DateColumn("calldate")+" = "+POut.Date(date)+" "
         +"AND (dcontext='ext-group' OR dcontext='ext-local') AND dst='vmu998'";
     List<DateTime> retVal=new List<DateTime>();
     DataTable table=dcon.GetTable(command);
     for(int i=0;i<table.Rows.Count;i++) {
         retVal.Add(PIn.DateT(table.Rows[i][0].ToString()));
     }
     return retVal;
 }
Esempio n. 14
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;
		}
Esempio n. 15
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. 16
0
File: MiscData.cs Progetto: mnisl/OD
		///<summary>Backs up the database to the same directory as the original just in case the user did not have sense enough to do a backup first.</summary>
		public static long MakeABackup() {
			//This function should always make the backup on the server itself, and since no directories are
			//referred to (all handled with MySQL), this function will always be referred to the server from
			//client machines.
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetLong(MethodBase.GetCurrentMethod());
			}
			//only used in two places: upgrading version, and upgrading mysql version.
			//Both places check first to make sure user is using mysql.
			//we have to be careful to throw an exception if the backup is failing.
			DataConnection dcon=new DataConnection();
			string command="SELECT database()";
			DataTable table=dcon.GetTable(command);
			string oldDb=PIn.String(table.Rows[0][0].ToString());
			string newDb=oldDb+"backup_"+DateTime.Today.ToString("MM_dd_yyyy");
			command="SHOW DATABASES";
			table=dcon.GetTable(command);
			string[] databases=new string[table.Rows.Count];
			for(int i=0;i<table.Rows.Count;i++) {
				databases[i]=table.Rows[i][0].ToString();
			}
			if(Contains(databases,newDb)) {//if the new database name already exists
				//find a unique one
				int uniqueID=1;
				string originalNewDb=newDb;
				do {
					newDb=originalNewDb+"_"+uniqueID.ToString();
					uniqueID++;
				}
				while(Contains(databases,newDb));
			}
			command="CREATE DATABASE "+newDb+" CHARACTER SET utf8";
			dcon.NonQ(command);
			command="SHOW FULL TABLES WHERE Table_type='BASE TABLE'";//Tables, not views.  Does not work in MySQL 4.1, however we test for MySQL version >= 5.0 in PrefL.
			table=dcon.GetTable(command);
			string[] tableName=new string[table.Rows.Count];
			for(int i=0;i<table.Rows.Count;i++) {
				tableName[i]=table.Rows[i][0].ToString();
			}
			//switch to using the new database
			DataConnection newDcon=new DataConnection(newDb);
			for(int i=0;i<tableName.Length;i++) {
				command="SHOW CREATE TABLE "+oldDb+"."+tableName[i];//also works with views.
				table=newDcon.GetTable(command);
				command=PIn.ByteArray(table.Rows[0][1]);
				newDcon.NonQ(command);//this has to be run using connection with new database
				command="INSERT INTO "+newDb+"."+tableName[i]
					+" SELECT * FROM "+oldDb+"."+tableName[i];
				newDcon.NonQ(command);
			}
			return 0;
		}
Esempio n. 17
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. 18
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;
			}
		}
        ///<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 computerName  = "";
            string database      = "";
            string user          = "";
            string password      = "";

            if (centralConnection.ServerName != "")           //Direct connection
            {
                computerName = centralConnection.ServerName;
                database     = centralConnection.DatabaseName;
                user         = centralConnection.MySqlUser;
                if (centralConnection.MySqlPassword != "")
                {
                    password = CentralConnections.Decrypt(centralConnection.MySqlPassword, EncryptionKey);
                }
                try {
                    DataConnection.DBtype = DatabaseType.MySql;
                    OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
                    dcon.SetDbT(computerName, database, user, password, "", "", DataConnection.DBtype);
                    RemotingClient.SetRemotingRoleT(RemotingRole.ClientDirect);
                    if (refreshCache)
                    {
                        Cache.Refresh(InvalidType.AllLocal);
                    }
                }
                catch {
                    return(false);
                }
            }
            else if (centralConnection.ServiceURI != "")           //Middle tier connection
            {
                RemotingClient.SetServerURIT(centralConnection.ServiceURI);
                RemotingClient.SetRemotingRoleT(RemotingRole.ClientWeb);
            }
            else
            {
                MessageBox.Show("Either a database or a Middle Tier URI must be specified in the connection.");
                return(false);
            }
            return(true);
        }
Esempio n. 20
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);
            }
        }
 ///<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. 22
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);
     }
 }
 ///<summary></summary>
 private string[] GetDatabases()
 {
     if (comboComputerName.Text == "")
     {
         return(new string[0]);
     }
     if (listType.SelectedIndex != 0)
     {
         return(new string[0]);               //because SHOW DATABASES won't work
     }
     try{
         OpenDentBusiness.DataConnection dcon;
         //use the one table that we know exists
         if (textUser.Text == "")
         {
             dcon = new OpenDentBusiness.DataConnection(comboComputerName.Text, "mysql", "root", textPassword.Text,
                                                        DatabaseType.MySql);
         }
         else
         {
             dcon = new OpenDentBusiness.DataConnection(comboComputerName.Text, "mysql", textUser.Text, textPassword.Text,
                                                        DatabaseType.MySql);
         }
         string command = "SHOW DATABASES";
         //if this next step fails, table will simply have 0 rows
         DataTable table   = dcon.GetTable(command);
         string[]  dbNames = new string[table.Rows.Count];
         for (int i = 0; i < table.Rows.Count; i++)
         {
             dbNames[i] = table.Rows[i][0].ToString();
         }
         return(dbNames);
     }
     catch {
         return(new string[0]);
     }
 }
Esempio n. 24
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. 25
0
        ///<summary>Inserts a new document into db, creates a filename based on Cur.DocNum, and then updates the db with this filename.  Also attaches the document to the current patient.</summary>
        public static int Insert(Document doc, string patLF, int patNum)
        {
            if (PrefB.RandomKeys)
            {
                doc.DocNum = MiscDataB.GetKey("document", "DocNum");
            }
            string command = "INSERT INTO document (";

            if (PrefB.RandomKeys)
            {
                command += "DocNum,";
            }
            command += "Description,DateCreated,DocCategory,PatNum,FileName,ImgType,"
                       + "IsFlipped,DegreesRotated,ToothNumbers,Note,SigIsTopaz,Signature,CropX,CropY,CropW,CropH,"
                       + "WindowingMin,WindowingMax,MountItemNum) VALUES(";
            if (PrefB.RandomKeys)
            {
                command += "'" + POut.PInt(doc.DocNum) + "', ";
            }
            command +=
                "'" + POut.PString(doc.Description) + "', "
                + POut.PDate(doc.DateCreated) + ", "
                + "'" + POut.PInt(doc.DocCategory) + "', "
                + "'" + POut.PInt(doc.PatNum) + "', "
                + "'" + POut.PString(doc.FileName) + "', "           //this may simply be the extension at this point, or it may be the full filename.
                + "'" + POut.PInt((int)doc.ImgType) + "', "
                + "'" + POut.PBool(doc.IsFlipped) + "', "
                + "'" + POut.PInt(doc.DegreesRotated) + "', "
                + "'" + POut.PString(doc.ToothNumbers) + "', "
                + "'" + POut.PString(doc.Note) + "', "
                + "'" + POut.PBool(doc.SigIsTopaz) + "', "
                + "'" + POut.PString(doc.Signature) + "',"
                + "'" + POut.PInt(doc.CropX) + "',"
                + "'" + POut.PInt(doc.CropY) + "',"
                + "'" + POut.PInt(doc.CropW) + "',"
                + "'" + POut.PInt(doc.CropH) + "',"
                + "'" + POut.PInt(doc.WindowingMin) + "',"
                + "'" + POut.PInt(doc.WindowingMax) + "',"
                + "'" + POut.PInt(doc.MountItemNum) + "')";

            /*+"'"+POut.PDate  (LastAltered)+"', "//will later be used in backups
             +"'"+POut.PBool  (IsDeleted)+"')";//ditto*/
            //MessageBox.Show(cmd.CommandText);
            DataConnection dcon = new DataConnection();

            if (PrefB.RandomKeys)
            {
                dcon.NonQ(command);
            }
            else
            {
                dcon.NonQ(command, true);
                doc.DocNum = dcon.InsertID;
            }
            //If the current filename is just an extension, then assign it a unique name.
            if (doc.FileName == Path.GetExtension(doc.FileName))
            {
                string extension = doc.FileName;
                doc.FileName = "";
                string s = patLF;              //pat.LName+pat.FName;
                for (int i = 0; i < s.Length; i++)
                {
                    if (Char.IsLetter(s, i))
                    {
                        doc.FileName += s.Substring(i, 1);
                    }
                }
                doc.FileName += doc.DocNum.ToString() + extension;            //ensures unique name
                //there is still a slight chance that someone manually added a file with this name, so quick fix:
                command = "SELECT FileName FROM document WHERE PatNum=" + POut.PInt(doc.PatNum);
                DataTable table     = dcon.GetTable(command);
                string[]  usedNames = new string[table.Rows.Count];
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    usedNames[i] = PIn.PString(table.Rows[i][0].ToString());
                }
                while (IsFileNameInList(doc.FileName, usedNames))
                {
                    doc.FileName = "x" + doc.FileName;
                }

                /*Document[] docList=GetAllWithPat(doc.PatNum);
                 * while(IsFileNameInList(doc.FileName,docList)) {
                 *      doc.FileName="x"+doc.FileName;
                 * }*/
                Update(doc);
            }
            DocAttach docAttach = new DocAttach();

            docAttach.DocNum = doc.DocNum;
            docAttach.PatNum = patNum;
            DocAttachB.Insert(docAttach);
            return(doc.DocNum);
        }
Esempio n. 26
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 saveOnSuccess = 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;
            }
            if (saveOnSuccess)
            {
                TrySaveConnectionSettings(centralConnection, dbType, connectionString, noShowOnStartup, listAdminCompNames);
            }
        }
Esempio n. 27
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. 28
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. 29
0
		public static void SetRingGroups(int extension,AsteriskRingGroups ringGroups) {
			DataConnection dcon=new DataConnection(ipAddressAsterisk,"asterisk","opendental","secret",DatabaseType.MySql);
			string command="SELECT grpnum,grplist FROM ringgroups WHERE grpnum = '601' OR grpnum = '609'";
			DataTable table=null;
			try {
				table=dcon.GetTable(command);
			}
			catch {//if remotely connecting from home
				return;
			}
			string rawExtensions601="";
			string rawExtensions609="";
			string[] arrayExtensions601=new string[0];
			string[] arrayExtensions609=new string[0];		
			for(int i=0;i<table.Rows.Count;i++) {
				if(table.Rows[i]["grpnum"].ToString()=="601") {//there should always be exactly one
					rawExtensions601=table.Rows[i]["grplist"].ToString();
					arrayExtensions601=rawExtensions601.Split(new char[] { '-' },StringSplitOptions.RemoveEmptyEntries);
				}
				if(table.Rows[i]["grpnum"].ToString()=="609") {//there should always be exactly one
					rawExtensions609=table.Rows[i]["grplist"].ToString();
					arrayExtensions609=rawExtensions609.Split(new char[] { '-' },StringSplitOptions.RemoveEmptyEntries);
				}
			}
			List<string> listExtension601=new List<string>();
			bool isIn601=false;
			for(int i=0;i<arrayExtensions601.Length;i++){
				//we won't test to make sure each item is a pure number.
				listExtension601.Add(arrayExtensions601[i]);
				if(arrayExtensions601[i]==extension.ToString()) {
					isIn601=true;
				}
			}
			List<string> listExtension609=new List<string>();
			bool isIn609=false;
			for(int i=0;i<arrayExtensions609.Length;i++) {
				//we won't test to make sure each item is a pure number.
				listExtension609.Add(arrayExtensions609[i]);
				if(arrayExtensions609[i]==extension.ToString()) {
					isIn609=true;
				}
			}
			if(ringGroups==AsteriskRingGroups.All) {
				if(!isIn601) {
					AddToRingGroup("601",extension.ToString(),rawExtensions601);
				}
				if(!isIn609) {
					AddToRingGroup("609",extension.ToString(),rawExtensions609);
				}
			}
			if(ringGroups==AsteriskRingGroups.None) {
				if(isIn601) {
					RemoveFromRingGroup("601",extension.ToString(),listExtension601,rawExtensions601);
				}
				if(isIn609) {
					RemoveFromRingGroup("609",extension.ToString(),listExtension609,rawExtensions609);
				}
			}
			if(ringGroups==AsteriskRingGroups.Backup) {
				if(isIn601) {
					RemoveFromRingGroup("601",extension.ToString(),listExtension601,rawExtensions601);
				}
				if(!isIn609) {
					AddToRingGroup("609",extension.ToString(),rawExtensions609);
				}
			}
			Signalods.SetInvalid(InvalidType.PhoneAsteriskReload);
		}
Esempio n. 30
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. 31
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. 32
0
		public static DataTable GetTreeListTableForPatient(string patNum){
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetTable(MethodBase.GetCurrentMethod(),patNum);
			}
			DataConnection dcon=new DataConnection();
			DataTable table=new DataTable("DocumentList");
			DataRow row;
			DataTable raw;
			string command;
			//Rows are first added to the resultSet list so they can be sorted at the end as a larger group, then
			//they are placed in the datatable to be returned.
			List<Object> resultSet=new List<Object>();
			//columns that start with lowercase are altered for display rather than being raw data.
			table.Columns.Add("DocNum");
			table.Columns.Add("MountNum");
			table.Columns.Add("DocCategory");
			table.Columns.Add("DateCreated");
			table.Columns.Add("docFolder");//The folder order to which the Document category corresponds.
			table.Columns.Add("description");
			table.Columns.Add("ImgType");
			//Move all documents which are invisible to the first document category.
			command="SELECT DocNum FROM document WHERE PatNum='"+patNum+"' AND "
				+"DocCategory<0";
			raw=dcon.GetTable(command);
			if(raw.Rows.Count>0){//Are there any invisible documents?
				command="UPDATE document SET DocCategory='"+DefC.GetList(DefCat.ImageCats)[0].DefNum
					+"' WHERE PatNum='"+patNum+"' AND (";
				for(int i=0;i<raw.Rows.Count;i++){
					command+="DocNum='"+PIn.Long(raw.Rows[i]["DocNum"].ToString())+"' ";
					if(i<raw.Rows.Count-1){
						command+="OR ";
					}
				}
				command+=")";
				dcon.NonQ(command);
			}
			//Load all documents into the result table.
			command="SELECT DocNum,DocCategory,DateCreated,Description,ImgType,MountItemNum FROM document WHERE PatNum='"+patNum+"'";
			raw=dcon.GetTable(command);
			for(int i=0;i<raw.Rows.Count;i++){
				//Make sure hidden documents are never added (there is a small possibility that one is added after all are made visible).
				if(DefC.GetOrder(DefCat.ImageCats,PIn.Long(raw.Rows[i]["DocCategory"].ToString()))<0){ 
					continue;
				}
				//Do not add individual documents which are part of a mount object.
				if(PIn.Long(raw.Rows[i]["MountItemNum"].ToString())!=0) {
					continue;
				}
				row=table.NewRow();
				row["DocNum"]=PIn.Long(raw.Rows[i]["DocNum"].ToString());
				row["MountNum"]=0;
				row["DocCategory"]=PIn.Long(raw.Rows[i]["DocCategory"].ToString());
				row["DateCreated"]=PIn.Date(raw.Rows[i]["DateCreated"].ToString());
				row["docFolder"]=DefC.GetOrder(DefCat.ImageCats,PIn.Long(raw.Rows[i]["DocCategory"].ToString()));
				row["description"]=PIn.Date(raw.Rows[i]["DateCreated"].ToString()).ToString("d")+": "
					+PIn.String(raw.Rows[i]["Description"].ToString());
				row["ImgType"]=PIn.Long(raw.Rows[i]["ImgType"].ToString());
				resultSet.Add(row);
			}
			//Move all mounts which are invisible to the first document category.
			command="SELECT MountNum FROM mount WHERE PatNum='"+patNum+"' AND "
				+"DocCategory<0";
			raw=dcon.GetTable(command);
			if(raw.Rows.Count>0) {//Are there any invisible mounts?
				command="UPDATE mount SET DocCategory='"+DefC.GetList(DefCat.ImageCats)[0].DefNum
					+"' WHERE PatNum='"+patNum+"' AND (";
				for(int i=0;i<raw.Rows.Count;i++) {
					command+="MountNum='"+PIn.Long(raw.Rows[i]["MountNum"].ToString())+"' ";
					if(i<raw.Rows.Count-1) {
						command+="OR ";
					}
				}
				command+=")";
				dcon.NonQ(command);
			}
			//Load all mounts into the result table.
			command="SELECT MountNum,DocCategory,DateCreated,Description,ImgType FROM mount WHERE PatNum='"+patNum+"'";
			raw=dcon.GetTable(command);
			for(int i=0;i<raw.Rows.Count;i++){
				//Make sure hidden mounts are never added (there is a small possibility that one is added after all are made visible).
				if(DefC.GetOrder(DefCat.ImageCats,PIn.Long(raw.Rows[i]["DocCategory"].ToString()))<0) {
					continue;
				}
				row=table.NewRow();
				row["DocNum"]=0;
				row["MountNum"]=PIn.Long(raw.Rows[i]["MountNum"].ToString());
				row["DocCategory"]=PIn.Long(raw.Rows[i]["DocCategory"].ToString());
				row["DateCreated"]=PIn.Date(raw.Rows[i]["DateCreated"].ToString());
				row["docFolder"]=DefC.GetOrder(DefCat.ImageCats,PIn.Long(raw.Rows[i]["DocCategory"].ToString()));
				row["description"]=PIn.Date(raw.Rows[i]["DateCreated"].ToString()).ToString("d")+": "
					+PIn.String(raw.Rows[i]["Description"].ToString());
				row["ImgType"]=PIn.Long(raw.Rows[i]["ImgType"].ToString());
				resultSet.Add(row);
			}
			//We must sort the results after they are returned from the database, because the database software (i.e. MySQL)
			//cannot return sorted results from two or more result sets like we have here.
			resultSet.Sort(delegate(Object o1,Object o2) {
				DataRow r1=(DataRow)o1;
				DataRow r2=(DataRow)o2;
				int docFolder1=Convert.ToInt32(r1["docFolder"].ToString());
				int docFolder2=Convert.ToInt32(r2["docFolder"].ToString());
				if(docFolder1<docFolder2){
					return -1;
				}else if(docFolder1>docFolder2){
					return 1;
				}
				return PIn.Date(r1["DateCreated"].ToString()).CompareTo(PIn.Date(r2["DateCreated"].ToString()));
			});
			//Finally, move the results from the list into a data table.
			for(int i=0;i<resultSet.Count;i++){
				table.Rows.Add((DataRow)resultSet[i]);
			}
			return table;
		}
Esempio n. 33
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. 34
0
		public static DataTable GetPlannedApt(long patNum) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetTable(MethodBase.GetCurrentMethod(),patNum);
			}
			DataConnection dcon=new DataConnection();
			DataTable table=new DataTable("Planned");
			DataRow row;
			//columns that start with lowercase are altered for display rather than being raw data.
			table.Columns.Add("AptNum");
			table.Columns.Add("colorBackG");
			table.Columns.Add("colorText");
			table.Columns.Add("dateSched");
			table.Columns.Add("ItemOrder");
			table.Columns.Add("minutes");
			table.Columns.Add("Note");
			table.Columns.Add("ProcDescript");
			table.Columns.Add("PlannedApptNum");
			//but we won't actually fill this table with rows until the very end.  It's more useful to use a List<> for now.
			List<DataRow> rows=new List<DataRow>();
			//The query below was causing a max join error for big offices.  It's fixed now, 
			//but a better option for next time would be to put SET SQL_BIG_SELECTS=1; before the query.
			string command="SELECT plannedappt.AptNum,ItemOrder,PlannedApptNum,appointment.AptDateTime,"
				+"appointment.Pattern,appointment.AptStatus,"//COUNT(procedurelog.ProcNum) someAreComplete "//The count won't be accurate, but it will tell us if not zero.
				+"(SELECT COUNT(*) FROM procedurelog WHERE procedurelog.PlannedAptNum=plannedappt.AptNum AND procedurelog.ProcStatus=2) someAreComplete "
				+"FROM plannedappt "
				+"LEFT JOIN appointment ON appointment.NextAptNum=plannedappt.AptNum "
				//+"LEFT JOIN procedurelog ON procedurelog.PlannedAptNum=plannedappt.AptNum "//grab all attached completed procs
				//+"AND procedurelog.ProcStatus=2 "
				+"WHERE plannedappt.PatNum="+POut.Long(patNum)+" "
				+"GROUP BY plannedappt.AptNum,ItemOrder,PlannedApptNum,appointment.AptDateTime,"
				+"appointment.Pattern,appointment.AptStatus "
				+"ORDER BY ItemOrder";
			//plannedappt.AptNum does refer to the planned appt, but the other fields in the result are for the linked scheduled appt.
			DataTable rawPlannedAppts=dcon.GetTable(command);
			DataRow aptRow;
			int itemOrder=1;
			DateTime dateSched;
			ApptStatus aptStatus;
			for(int i=0;i<rawPlannedAppts.Rows.Count;i++) {
				aptRow=null;
				for(int a=0;a<rawApt.Rows.Count;a++) {
					if(rawApt.Rows[a]["AptNum"].ToString()==rawPlannedAppts.Rows[i]["AptNum"].ToString()) {
						aptRow=rawApt.Rows[a];
						break;
					}
				}
				if(aptRow==null) {
					continue;//this will have to be fixed in dbmaint.
				}
				//repair any item orders here rather than in dbmaint. It's really fast.
				if(itemOrder.ToString()!=rawPlannedAppts.Rows[i]["ItemOrder"].ToString()) {
					command="UPDATE plannedappt SET ItemOrder="+POut.Long(itemOrder)
						+" WHERE PlannedApptNum="+rawPlannedAppts.Rows[i]["PlannedApptNum"].ToString();
					dcon.NonQ(command);
				}
				//end of repair
				row=table.NewRow();
				row["AptNum"]=aptRow["AptNum"].ToString();
				dateSched=PIn.Date(rawPlannedAppts.Rows[i]["AptDateTime"].ToString());
				//Colors----------------------------------------------------------------------------
				aptStatus=(ApptStatus)PIn.Long(rawPlannedAppts.Rows[i]["AptStatus"].ToString());
				//change color if completed, broken, or unscheduled no matter the date
				if(aptStatus==ApptStatus.Broken || aptStatus==ApptStatus.UnschedList) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][15].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][14].ItemColor.ToArgb().ToString();
				}
				else if(aptStatus==ApptStatus.Complete) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][11].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][10].ItemColor.ToArgb().ToString();
				}
				else if(aptStatus==ApptStatus.Scheduled && dateSched.Date!=DateTime.Today.Date) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][13].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][12].ItemColor.ToArgb().ToString();
				}
				else if(dateSched.Date<DateTime.Today && dateSched!=DateTime.MinValue) {//Past
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][11].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][10].ItemColor.ToArgb().ToString();
				}
				else if(dateSched.Date == DateTime.Today.Date) { //Today
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][9].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][8].ItemColor.ToArgb().ToString();
				}
				else if(dateSched.Date > DateTime.Today) { //Future
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][13].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][12].ItemColor.ToArgb().ToString();
				}
				else {
					row["colorBackG"]=Color.White.ToArgb().ToString();
					row["colorText"]=Color.Black.ToArgb().ToString();
				}
				//end of colors------------------------------------------------------------------------------
				if(dateSched.Year<1880) {
					row["dateSched"]="";
				}
				else {
					row["dateSched"]=dateSched.ToShortDateString();
				}
				row["ItemOrder"]=itemOrder.ToString();
				row["minutes"]=(aptRow["Pattern"].ToString().Length*5).ToString();
				row["Note"]=aptRow["Note"].ToString();
				row["PlannedApptNum"]=rawPlannedAppts.Rows[i]["PlannedApptNum"].ToString();
				row["ProcDescript"]=aptRow["ProcDescript"].ToString();
				if(aptStatus==ApptStatus.Complete) {
					row["ProcDescript"]=Lans.g("ContrChart","(Completed) ")+ row["ProcDescript"];
				}
				else if(dateSched == DateTime.Today.Date) {
					row["ProcDescript"]=Lans.g("ContrChart","(Today's) ")+ row["ProcDescript"];
				}
				else if(rawPlannedAppts.Rows[i]["someAreComplete"].ToString()!="0"){
					row["ProcDescript"]=Lans.g("ContrChart","(Some procs complete) ")+ row["ProcDescript"];
				}
				rows.Add(row);
				itemOrder++;
			}
			for(int i=0;i<rows.Count;i++) {
				table.Rows.Add(rows[i]);
			}
			return table;
		}
 ///<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. 36
0
 ///<summary></summary>
 private string[] GetDatabases()
 {
     if(comboComputerName.Text==""){
         return new string[0];
     }
     if(listType.SelectedIndex!=0){
         return new string[0];//because SHOW DATABASES won't work
     }
     try{
         OpenDentBusiness.DataConnection dcon;
         //use the one table that we know exists
         if(textUser.Text==""){
             dcon=new OpenDentBusiness.DataConnection(comboComputerName.Text,"mysql","root",textPassword.Text,
                 DatabaseType.MySql);
         }
         else{
             dcon=new OpenDentBusiness.DataConnection(comboComputerName.Text,"mysql",textUser.Text,textPassword.Text,
                 DatabaseType.MySql);
         }
         string command="SHOW DATABASES";
         //if this next step fails, table will simply have 0 rows
         DataTable table=dcon.GetTable(command);
         string[] dbNames=new string[table.Rows.Count];
         for(int i=0;i<table.Rows.Count;i++){
             dbNames[i]=table.Rows[i][0].ToString();
         }
         return dbNames;
     }
     catch{
         return new string[0];
     }
 }
Esempio n. 37
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. 38
0
File: DataCore.cs Progetto: mnisl/OD
		/*
		///<summary>This is for multiple queries all concatenated together with ;</summary>
		public static DataSet GetDataSet(string commands){
			DataConnection dcon=new DataConnection();
			//DataTable table=dcon.GetTable(command);
			DataSet retVal=dcon.GetDs(commands);
			//retVal.Tables.Add(table);
			return retVal;
		}*/

		///<summary>Get one single value.</summary>
		public static string GetScalar(string command) {
			DataConnection dcon=new DataConnection();
			return dcon.GetScalar(command);
		}
Esempio n. 39
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. 40
0
		private static void RemoveFromRingGroup(string ringGroup,string extension,List<string> listExtensions,string rawExtensions) {
			string newExtensions="";
			for(int i=0;i<listExtensions.Count;i++) {
				if(listExtensions[i]==extension) {//skip this extension
					continue;
				}
				if(newExtensions!="") {
					newExtensions=newExtensions+"-";
				}
				newExtensions=newExtensions+listExtensions[i];
			}
			string command="UPDATE ringgroups SET grplist='"+POut.String(newExtensions)+"' "
				+"WHERE grpnum='"+ringGroup+"' "
				+"AND grplist = '"+POut.String(rawExtensions)+"'";
			DataConnection dcon=new DataConnection(ipAddressAsterisk,"asterisk","opendental","secret",DatabaseType.MySql);
			dcon.NonQ(command);
		}
Esempio n. 41
0
        ///<summary>Backs up the database to the same directory as the original just in case the user did not have sense enough to do a backup first.
        ///Does not work for Oracle, due to some MySQL specific commands inside.</summary>
        public static long MakeABackup()
        {
            //This function should always make the backup on the server itself, and since no directories are
            //referred to (all handled with MySQL), this function will always be referred to the server from
            //client machines.
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetLong(MethodBase.GetCurrentMethod()));
            }
            //UpdateStreamLinePassword is purposefully named poorly and used in an odd fashion to sort of obfuscate it from our users.
            //GetStringNoCache() will return blank if pref does not exist.
            if (PrefC.GetStringNoCache(PrefName.UpdateStreamLinePassword) == "abracadabra")
            {
                return(0);
            }
            //only used in two places: upgrading version, and upgrading mysql version.
            //Both places check first to make sure user is using mysql.
            //we have to be careful to throw an exception if the backup is failing.
            DataConnection dcon    = new DataConnection();
            string         command = "SELECT database()";
            DataTable      table   = dcon.GetTable(command);
            string         oldDb   = PIn.String(table.Rows[0][0].ToString());
            string         newDb   = oldDb + "backup_" + DateTime.Today.ToString("MM_dd_yyyy");

            command = "SHOW DATABASES";
            table   = dcon.GetTable(command);
            string[] databases = new string[table.Rows.Count];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                databases[i] = table.Rows[i][0].ToString();
            }
            if (Contains(databases, newDb))            //if the new database name already exists
            //find a unique one
            {
                int    uniqueID      = 1;
                string originalNewDb = newDb;
                do
                {
                    newDb = originalNewDb + "_" + uniqueID.ToString();
                    uniqueID++;
                }while(Contains(databases, newDb));
            }
            command = "CREATE DATABASE `" + newDb + "` CHARACTER SET utf8";
            dcon.NonQ(command);
            command = "SHOW FULL TABLES WHERE Table_type='BASE TABLE'";          //Tables, not views.  Does not work in MySQL 4.1, however we test for MySQL version >= 5.0 in PrefL.
            table   = dcon.GetTable(command);
            string[] tableName = new string[table.Rows.Count];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                tableName[i] = table.Rows[i][0].ToString();
            }
            //switch to using the new database
            DataConnection newDcon = new DataConnection(newDb);

            for (int i = 0; i < tableName.Length; i++)
            {
                //Alert anyone that cares that we are backing up this table.
                ODEvent.Fire(new ODEventArgs("BackupProgress", Lans.g("MiscData", "Backing up table") + ": " + tableName[i]));
                command = "SHOW CREATE TABLE `" + oldDb + "`.`" + tableName[i] + "`";      //also works with views. Added backticks around table name for unusual characters.
                table   = newDcon.GetTable(command);
                command = PIn.ByteArray(table.Rows[0][1]);
                newDcon.NonQ(command);                                              //this has to be run using connection with new database
                command = "INSERT INTO `" + newDb + "`.`" + tableName[i] + "` "
                          + "SELECT * FROM `" + oldDb + "`.`" + tableName[i] + "`"; //Added backticks around table name for unusual characters.
                newDcon.NonQ(command);
            }
            return(0);
        }
Esempio n. 42
0
		private static void AddToRingGroup(string ringGroup,string extension,string rawExtensions) {
			string newExtensions=rawExtensions+"-"+extension;
			string command="UPDATE ringgroups SET grplist='"+POut.String(newExtensions)+"' "
				+"WHERE grpnum='"+ringGroup+"' "
				+"AND grplist = '"+POut.String(rawExtensions)+"'";//this ensures it hasn't changed since we checked it.  If it has, then this silently fails.
				//A transaction would be better, but no time.
			DataConnection dcon=new DataConnection(ipAddressAsterisk,"asterisk","opendental","secret",DatabaseType.MySql);
			dcon.NonQ(command);
		}
Esempio n. 43
0
		public static string GetCurrentConnectionString() {
			DataConnection dcon=new DataConnection();
			return dcon.con.ConnectionString;
		}
Esempio n. 44
0
File: MiscData.cs Progetto: mnisl/OD
		public static void UnlockWorkstationsForDbs(string[] dbNames) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				throw new ApplicationException("MiscData.UnlockWorkstationsForDbs failed.  Updates not allowed from ClientWeb.");
			}
			DataConnection dcon=null;
			for(int i=0;i<dbNames.Length;i++) {
				try {
					dcon=new DataConnection(dbNames[i]);
					string command="UPDATE preference SET ValueString =''"
						+" WHERE PrefName='UpdateInProgressOnComputerName'";
					dcon.NonQ(command);
				}
				catch { }
			}
		}
Esempio n. 45
0
 ///<summary>Returns serialized DbInfo object as JSON string of database info from both the preference table and non preferernce table info.
 ///Every unique bit of information is individually try / caught so that we return as much information as possible.</summary>
 private string GetDbInfoJSON(long patNum, string moduleName)
 {
     _info = new BugSubmission.SubmissionInfo();
     ODException.SwallowAnyException(() => {
         //This list is not in a separate method because we want to ensure that future development related to bug submissions don't try to make assumptions
         //on which preferences are in an object at any given time.
         //Ex.  Let's say in version 17.4, the list doesn't contain the payplan version preference, but 17.5 does.
         //If we called the method that retrieves the used preferences from WebServiceMainHQ which in this example is on version 17.5,
         // it would think all bugsubmission rows contain the payplan version preference when that is not the case.
         List <PrefName> listPrefs = new List <PrefName>()
         {
             PrefName.AtoZfolderUsed,
             PrefName.ClaimSnapshotEnabled,
             PrefName.ClaimSnapshotRunTime,
             PrefName.ClaimSnapshotTriggerType,
             PrefName.CorruptedDatabase,
             PrefName.DataBaseVersion,
             PrefName.EasyNoClinics,
             PrefName.LanguageAndRegion,
             PrefName.MySqlVersion,
             PrefName.PayPlansVersion,
             PrefName.ProcessSigsIntervalInSecs,
             PrefName.ProgramVersionLastUpdated,
             PrefName.ProgramVersion,
             PrefName.RandomPrimaryKeys,
             PrefName.RegistrationKey,
             PrefName.RegistrationKeyIsDisabled,
             PrefName.ReplicationFailureAtServer_id,
             PrefName.ReportingServerCompName,
             PrefName.ReportingServerDbName,
             PrefName.ReportingServerMySqlUser,
             PrefName.ReportingServerMySqlPassHash,
             PrefName.ReportingServerURI,
             PrefName.SecurityLogOffAfterMinutes,
             PrefName.WebServiceServerName
         };
         foreach (PrefName pref in listPrefs)
         {
             _info.DictPrefValues[pref] = Prefs.GetOne(pref).ValueString;
         }
     });
     ODException.SwallowAnyException(() => { _info.CountClinics = Clinics.GetCount(); });
     ODException.SwallowAnyException(() => { _info.EnabledPlugins = Programs.GetWhere(x => x.Enabled && !string.IsNullOrWhiteSpace(x.PluginDllName)).Select(x => x.ProgName).ToList(); });
     ODException.SwallowAnyException(() => { _info.ClinicNumCur = Clinics.ClinicNum; });
     ODException.SwallowAnyException(() => { _info.UserNumCur = Security.CurUser.UserNum; });
     ODException.SwallowAnyException(() => { _info.PatientNumCur = patNum; });
     ODException.SwallowAnyException(() => { _info.IsOfficeOnReplication = (ReplicationServers.GetCount() > 0 ? true : false); });
     ODException.SwallowAnyException(() => { _info.IsOfficeUsingMiddleTier = (RemotingClient.RemotingRole == RemotingRole.ClientWeb ? true : false); });
     ODException.SwallowAnyException(() => { _info.WindowsVersion = MiscData.GetOSVersionInfo(); });
     ODException.SwallowAnyException(() => { _info.CompName = Security.CurComputerName; });
     ODException.SwallowAnyException(() => {
         List <UpdateHistory> listHist = UpdateHistories.GetPreviousUpdateHistories(2);                        //Ordered by newer versions first.
         _info.PreviousUpdateVersion   = listHist.Count == 2 ? listHist[1].ProgramVersion : "";                //Show the previous version they updated from
         _info.PreviousUpdateTime      = listHist.Count > 0 ? listHist[0].DateTimeUpdated : DateTime.MinValue; //Show when they updated to the current version.
     });
     ODException.SwallowAnyException(() => { _info.ModuleNameCur = moduleName; });
     ODException.SwallowAnyException(() => { _info.DatabaseName = DataConnection.GetDatabaseName(); });
     ODException.SwallowAnyException(() => { _info.OpenDentBusinessVersion = MiscData.GetAssemblyVersion(); });
     ODException.SwallowAnyException(() => { _info.OpenDentBusinessMiddleTierVersion = MiscData.GetAssemblyVersionForMiddleTier(); });
     return(JsonConvert.SerializeObject(_info, new JsonSerializerSettings {
         NullValueHandling = NullValueHandling.Ignore
     }));
 }
 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. 47
0
        ///<summary>Updates only the changed columns.</summary>
        public static int Update(Procedure proc, Procedure oldProc)
        {
            bool   comma = false;
            string c     = "UPDATE procedurelog SET ";

            if (proc.PatNum != oldProc.PatNum)
            {
                c    += "PatNum = '" + POut.PInt(proc.PatNum) + "'";
                comma = true;
            }
            if (proc.AptNum != oldProc.AptNum)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "AptNum = '" + POut.PInt(proc.AptNum) + "'";
                comma = true;
            }
            if (proc.ADACode != oldProc.ADACode)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ADACode = '" + POut.PString(proc.ADACode) + "'";
                comma = true;
            }
            if (proc.ProcDate != oldProc.ProcDate)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ProcDate = " + POut.PDate(proc.ProcDate);
                comma = true;
            }
            if (proc.ProcFee != oldProc.ProcFee)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ProcFee = '" + POut.PDouble(proc.ProcFee) + "'";
                comma = true;
            }
            if (proc.Surf != oldProc.Surf)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "Surf = '" + POut.PString(proc.Surf) + "'";
                comma = true;
            }
            if (proc.ToothNum != oldProc.ToothNum)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ToothNum = '" + POut.PString(proc.ToothNum) + "'";
                comma = true;
            }
            if (proc.ToothRange != oldProc.ToothRange)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ToothRange = '" + POut.PString(proc.ToothRange) + "'";
                comma = true;
            }
            if (proc.Priority != oldProc.Priority)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "Priority = '" + POut.PInt(proc.Priority) + "'";
                comma = true;
            }
            if (proc.ProcStatus != oldProc.ProcStatus)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ProcStatus = '" + POut.PInt((int)proc.ProcStatus) + "'";
                comma = true;
            }
            if (proc.ProvNum != oldProc.ProvNum)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ProvNum = '" + POut.PInt(proc.ProvNum) + "'";
                comma = true;
            }
            if (proc.Dx != oldProc.Dx)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "Dx = '" + POut.PInt(proc.Dx) + "'";
                comma = true;
            }
            if (proc.PlannedAptNum != oldProc.PlannedAptNum)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "PlannedAptNum = '" + POut.PInt(proc.PlannedAptNum) + "'";
                comma = true;
            }
            if (proc.PlaceService != oldProc.PlaceService)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "PlaceService = '" + POut.PInt((int)proc.PlaceService) + "'";
                comma = true;
            }
            if (proc.Prosthesis != oldProc.Prosthesis)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "Prosthesis = '" + POut.PString(proc.Prosthesis) + "'";
                comma = true;
            }
            if (proc.DateOriginalProsth != oldProc.DateOriginalProsth)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "DateOriginalProsth = " + POut.PDate(proc.DateOriginalProsth);
                comma = true;
            }
            if (proc.ClaimNote != oldProc.ClaimNote)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ClaimNote = '" + POut.PString(proc.ClaimNote) + "'";
                comma = true;
            }
            if (proc.DateEntryC != oldProc.DateEntryC)
            {
                if (comma)
                {
                    c += ",";
                }
                c += "DateEntryC = ";
                if (DataConnection.DBtype == DatabaseType.Oracle)
                {
                    c += POut.PDateT(MiscDataB.GetNowDateTime());
                }
                else                  //Assume MySQL
                {
                    c += "NOW()";
                }
                comma = true;
            }
            if (proc.ClinicNum != oldProc.ClinicNum)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ClinicNum = '" + POut.PInt(proc.ClinicNum) + "'";
                comma = true;
            }
            if (proc.MedicalCode != oldProc.MedicalCode)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "MedicalCode = '" + POut.PString(proc.MedicalCode) + "'";
                comma = true;
            }
            if (proc.DiagnosticCode != oldProc.DiagnosticCode)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "DiagnosticCode = '" + POut.PString(proc.DiagnosticCode) + "'";
                comma = true;
            }
            if (proc.IsPrincDiag != oldProc.IsPrincDiag)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "IsPrincDiag = '" + POut.PBool(proc.IsPrincDiag) + "'";
                comma = true;
            }
            if (proc.ProcNumLab != oldProc.ProcNumLab)
            {
                if (comma)
                {
                    c += ",";
                }
                c    += "ProcNumLab = '" + POut.PInt(proc.ProcNumLab) + "'";
                comma = true;
            }
            int rowsChanged = 0;

            if (comma)
            {
                c += " WHERE ProcNum = '" + POut.PInt(proc.ProcNum) + "'";
                DataConnection dcon = new DataConnection();
                rowsChanged = dcon.NonQ(c);
            }
            else
            {
                //rowsChanged=0;//this means no change is actually required.
            }
            if (proc.Note != oldProc.Note ||
                proc.UserNum != oldProc.UserNum ||
                proc.SigIsTopaz != oldProc.SigIsTopaz ||
                proc.Signature != oldProc.Signature)
            {
                ProcNote note = new ProcNote();
                note.PatNum     = proc.PatNum;
                note.ProcNum    = proc.ProcNum;
                note.UserNum    = proc.UserNum;
                note.Note       = proc.Note;
                note.SigIsTopaz = proc.SigIsTopaz;
                note.Signature  = proc.Signature;
                ProcNoteB.Insert(note);
            }
            return(rowsChanged);
        }
Esempio n. 48
0
        private static DataTable GetProgNotes(int patNum, bool isAuditMode)
        {
            DataConnection dcon  = new DataConnection();
            DataTable      table = new DataTable("ProgNotes");
            DataRow        row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("ADACode");
            table.Columns.Add("aptDateTime", typeof(DateTime));
            table.Columns.Add("colorBackG");
            table.Columns.Add("colorText");
            table.Columns.Add("CommlogNum");
            table.Columns.Add("description");
            table.Columns.Add("dx");
            table.Columns.Add("Dx");
            table.Columns.Add("note");
            table.Columns.Add("Priority");
            table.Columns.Add("procDate");
            table.Columns.Add("ProcDate", typeof(DateTime));
            table.Columns.Add("procFee");
            table.Columns.Add("ProcNum");
            table.Columns.Add("ProcNumLab");
            table.Columns.Add("procStatus");
            table.Columns.Add("ProcStatus");
            table.Columns.Add("prov");
            table.Columns.Add("RxNum");
            table.Columns.Add("signature");
            table.Columns.Add("Surf");
            table.Columns.Add("toothNum");
            table.Columns.Add("ToothNum");
            table.Columns.Add("ToothRange");
            table.Columns.Add("user");
            //table.Columns.Add("");
            //but we won't actually fill this table with rows until the very end.  It's more useful to use a List<> for now.
            List <DataRow> rows = new List <DataRow>();
            //Procedures-----------------------------------------------------------------------------------------------------
            string command = "SELECT ProcDate,ProcStatus,ToothNum,Surf,Dx,procedurelog.ADACode,ProcNum,procedurecode.Descript,"
                             + "provider.Abbr,ProcFee,ProcNumLab,appointment.AptDateTime,Priority,ToothRange "
                             + "FROM procedurelog "
                             + "LEFT JOIN procedurecode ON procedurecode.ADACode=procedurelog.ADACode "
                             + "LEFT JOIN provider ON provider.ProvNum=procedurelog.ProvNum "
                             + "LEFT JOIN appointment ON appointment.AptNum=procedurelog.AptNum "
                             + "AND (appointment.AptStatus=" + POut.PInt((int)ApptStatus.Scheduled)
                             + " OR appointment.AptStatus=" + POut.PInt((int)ApptStatus.ASAP)
                             + " OR appointment.AptStatus=" + POut.PInt((int)ApptStatus.Broken)
                             + " OR appointment.AptStatus=" + POut.PInt((int)ApptStatus.Complete)
                             + ") WHERE procedurelog.PatNum=" + POut.PInt(patNum);

            if (!isAuditMode)
            {
                command += " AND ProcStatus !=6";     //don't include deleted
            }
            command += " ORDER BY ProcDate";          //we'll just have to reorder it anyway
            DataTable rawProcs = dcon.GetTable(command);

            command = "SELECT ProcNum,EntryDateTime,UserNum,Note,"
                      + "CASE WHEN Signature!='' THEN 1 ELSE 0 END AS SigPresent "
                      + "FROM procnote WHERE PatNum=" + POut.PInt(patNum)
                      + " ORDER BY EntryDateTime";         // but this helps when looping for notes
            DataTable      rawNotes = dcon.GetTable(command);
            DateTime       dateT;
            List <DataRow> labRows = new List <DataRow>();        //Canadian lab procs, which must be added in a loop at the very end.

            for (int i = 0; i < rawProcs.Rows.Count; i++)
            {
                row                = table.NewRow();
                row["ADACode"]     = rawProcs.Rows[i]["ADACode"].ToString();
                row["aptDateTime"] = PIn.PDateT(rawProcs.Rows[i]["AptDateTime"].ToString());
                row["colorBackG"]  = Color.White.ToArgb();
                if (((DateTime)row["aptDateTime"]).Date == DateTime.Today)
                {
                    row["colorBackG"] = DefB.Long[(int)DefCat.MiscColors][6].ItemColor.ToArgb().ToString();
                }
                switch ((ProcStat)PIn.PInt(rawProcs.Rows[i]["ProcStatus"].ToString()))
                {
                case ProcStat.TP:
                    row["colorText"] = DefB.Long[(int)DefCat.ProgNoteColors][0].ItemColor.ToArgb().ToString();
                    break;

                case ProcStat.C:
                    row["colorText"] = DefB.Long[(int)DefCat.ProgNoteColors][1].ItemColor.ToArgb().ToString();
                    break;

                case ProcStat.EC:
                    row["colorText"] = DefB.Long[(int)DefCat.ProgNoteColors][2].ItemColor.ToArgb().ToString();
                    break;

                case ProcStat.EO:
                    row["colorText"] = DefB.Long[(int)DefCat.ProgNoteColors][3].ItemColor.ToArgb().ToString();
                    break;

                case ProcStat.R:
                    row["colorText"] = DefB.Long[(int)DefCat.ProgNoteColors][4].ItemColor.ToArgb().ToString();
                    break;

                case ProcStat.D:
                    row["colorText"] = Color.Black.ToArgb().ToString();
                    break;
                }
                row["CommlogNum"]  = 0;
                row["description"] = rawProcs.Rows[i]["Descript"].ToString();
                row["dx"]          = DefB.GetValue(DefCat.Diagnosis, PIn.PInt(rawProcs.Rows[i]["Dx"].ToString()));
                row["Dx"]          = rawProcs.Rows[i]["Dx"].ToString();
                //note-----------------------------------------------------------------------------------------------------------
                if (isAuditMode)                                  //we will include all notes for each proc.  We will concat and make readable.
                {
                    for (int n = 0; n < rawNotes.Rows.Count; n++) //loop through each note
                    {
                        if (rawProcs.Rows[i]["ProcNum"].ToString() != rawNotes.Rows[n]["ProcNum"].ToString())
                        {
                            continue;
                        }
                        if (row["Note"].ToString() != "")                                                    //if there is an existing note
                        {
                            row["note"] += "\r\n------------------------------------------------------\r\n"; //start a new line
                        }
                        row["note"] += PIn.PDateT(rawNotes.Rows[n]["EntryDateTime"].ToString()).ToString();
                        row["note"] += "  " + UserodB.GetName(PIn.PInt(rawNotes.Rows[n]["UserNum"].ToString()));
                        if (rawNotes.Rows[n]["SigPresent"].ToString() == "1")
                        {
                            row["note"] += "  " + Lan.g("ChartModule", "(signed)");
                        }
                        row["note"] += "\r\n" + rawNotes.Rows[n]["Note"].ToString();
                    }
                }
                else                                                   //we just want the most recent note
                {
                    for (int n = rawNotes.Rows.Count - 1; n >= 0; n--) //loop through each note, backwards.
                    {
                        if (rawProcs.Rows[i]["ProcNum"].ToString() != rawNotes.Rows[n]["ProcNum"].ToString())
                        {
                            continue;
                        }
                        row["user"] = UserodB.GetName(PIn.PInt(rawNotes.Rows[n]["UserNum"].ToString()));
                        row["note"] = rawNotes.Rows[n]["Note"].ToString();
                        if (rawNotes.Rows[n]["SigPresent"].ToString() == "1")
                        {
                            row["signature"] = Lan.g("ChartModule", "Signed");
                        }
                        else
                        {
                            row["signature"] = "";
                        }
                        break;                        //out of note loop.
                    }
                }
                row["Priority"] = rawProcs.Rows[i]["Priority"].ToString();
                dateT           = PIn.PDateT(rawProcs.Rows[i]["ProcDate"].ToString());
                if (dateT.Year < 1880)
                {
                    row["procDate"] = "";
                }
                else
                {
                    row["procDate"] = dateT.ToShortDateString();
                }
                row["ProcDate"]   = dateT;
                row["procFee"]    = PIn.PDouble(rawProcs.Rows[i]["ProcFee"].ToString()).ToString("F");
                row["ProcNum"]    = rawProcs.Rows[i]["ProcNum"].ToString();
                row["ProcNumLab"] = rawProcs.Rows[i]["ProcNumLab"].ToString();
                row["procStatus"] = Lan.g("enumProcStat", ((ProcStat)PIn.PInt(rawProcs.Rows[i]["ProcStatus"].ToString())).ToString());
                row["ProcStatus"] = rawProcs.Rows[i]["ProcStatus"].ToString();
                row["prov"]       = rawProcs.Rows[i]["Abbr"].ToString();
                row["RxNum"]      = 0;
                row["Surf"]       = rawProcs.Rows[i]["Surf"].ToString();
                row["toothNum"]   = Tooth.ToInternat(rawProcs.Rows[i]["ToothNum"].ToString());
                row["ToothNum"]   = rawProcs.Rows[i]["ToothNum"].ToString();
                row["ToothRange"] = rawProcs.Rows[i]["ToothRange"].ToString();
                if (rawProcs.Rows[i]["ProcNumLab"].ToString() == "0")              //normal proc
                {
                    rows.Add(row);
                }
                else
                {
                    row["description"] = "-----" + row["description"].ToString();
                    labRows.Add(row);                    //these will be added in the loop at the end
                }
            }
            //Commlog-----------------------------------------------------------------------------------------------------------
            command = "SELECT CommlogNum,CommDateTime,CommType,Note FROM commlog WHERE PatNum=" + POut.PInt(patNum)
                      + " ORDER BY CommDateTime";
            DataTable rawComm = dcon.GetTable(command);

            for (int i = 0; i < rawComm.Rows.Count; i++)
            {
                row = table.NewRow();
                row["colorBackG"]  = Color.White.ToArgb();
                row["colorText"]   = DefB.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();
                row["CommlogNum"]  = rawComm.Rows[i]["CommlogNum"].ToString();
                row["description"] = Lan.g("ChartModule", "Comm - ")
                                     + Lan.g("enumCommItemType", ((CommItemType)PIn.PInt(rawComm.Rows[i]["CommType"].ToString())).ToString());
                row["note"] = rawComm.Rows[i]["Note"].ToString();
                dateT       = PIn.PDateT(rawComm.Rows[i]["CommDateTime"].ToString());
                if (dateT.Year < 1880)
                {
                    row["procDate"] = "";
                }
                else
                {
                    row["procDate"] = dateT.ToShortDateString();
                }
                row["ProcDate"] = dateT;
                row["ProcNum"]  = 0;
                row["RxNum"]    = 0;
                rows.Add(row);
            }
            //Rx------------------------------------------------------------------------------------------------------------------
            command = "SELECT RxNum,RxDate,Drug,Disp,ProvNum,Notes FROM rxpat WHERE PatNum=" + POut.PInt(patNum)
                      + " ORDER BY RxDate";
            DataTable rawRx = dcon.GetTable(command);

            for (int i = 0; i < rawRx.Rows.Count; i++)
            {
                row = table.NewRow();
                row["colorBackG"]  = Color.White.ToArgb();
                row["colorText"]   = DefB.Long[(int)DefCat.ProgNoteColors][5].ItemColor.ToArgb().ToString();
                row["CommlogNum"]  = 0;
                row["description"] = Lan.g("ChartModule", "Rx - ") + rawRx.Rows[i]["Drug"].ToString() + " - #" + rawRx.Rows[i]["Disp"].ToString();
                row["note"]        = rawRx.Rows[i]["Notes"].ToString();
                dateT = PIn.PDate(rawRx.Rows[i]["RxDate"].ToString());
                if (dateT.Year < 1880)
                {
                    row["procDate"] = "";
                }
                else
                {
                    row["procDate"] = dateT.ToShortDateString();
                }
                row["ProcDate"] = dateT;
                row["ProcNum"]  = 0;
                row["RxNum"]    = rawRx.Rows[i]["RxNum"].ToString();
                rows.Add(row);
            }
            //Sorting
            rows.Sort(CompareChartRows);
            //Canadian lab procedures need to come immediately after their corresponding proc---------------------------------
            for (int i = 0; i < labRows.Count; i++)
            {
                for (int r = 0; r < rows.Count; r++)
                {
                    if (rows[r]["ProcNum"].ToString() == labRows[i]["ProcNumLab"].ToString())
                    {
                        rows.Insert(r + 1, labRows[i]);
                        break;
                    }
                }
            }
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            return(table);
        }
Esempio n. 49
0
		public static DataTable GetProgNotes(long patNum,	bool isAuditMode,ChartModuleComponentsToLoad componentsToLoad) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetTable(MethodBase.GetCurrentMethod(),componentsToLoad);
			}
			DataConnection dcon=new DataConnection();
			DataTable table=new DataTable("ProgNotes");
			DataRow row;
			//columns that start with lowercase are altered for display rather than being raw data.
			table.Columns.Add("aptDateTime",typeof(DateTime));
			table.Columns.Add("AbbrDesc");
			table.Columns.Add("AptNum");
			table.Columns.Add("clinic");
			table.Columns.Add("CodeNum");
			table.Columns.Add("colorBackG");
			table.Columns.Add("colorText");
			table.Columns.Add("CommlogNum");
			table.Columns.Add("dateEntryC");
			table.Columns.Add("dateTP");
			table.Columns.Add("description");
			table.Columns.Add("dx");
			table.Columns.Add("Dx");
			table.Columns.Add("EmailMessageNum");
			table.Columns.Add("FormPatNum");
			table.Columns.Add("HideGraphics");
			table.Columns.Add("isLocked");
			table.Columns.Add("length");
			table.Columns.Add("LabCaseNum");
			table.Columns.Add("note");
			table.Columns.Add("orionDateScheduleBy");
			table.Columns.Add("orionDateStopClock");
			table.Columns.Add("orionDPC");
			table.Columns.Add("orionDPCpost");
			table.Columns.Add("orionIsEffectiveComm");
			table.Columns.Add("orionIsOnCall");
			table.Columns.Add("orionStatus2");
			table.Columns.Add("PatNum");//only used for Commlog and Task
			table.Columns.Add("Priority");//for sorting
			table.Columns.Add("priority");
			table.Columns.Add("ProcCode");
			table.Columns.Add("procDate");
			table.Columns.Add("ProcDate",typeof(DateTime));
			table.Columns.Add("procFee");
			table.Columns.Add("ProcNum");
			table.Columns.Add("ProcNumLab");
			table.Columns.Add("procStatus");
			table.Columns.Add("ProcStatus");
			table.Columns.Add("procTime");
			table.Columns.Add("procTimeEnd");
			table.Columns.Add("prognosis");
			table.Columns.Add("prov");
			table.Columns.Add("quadrant");
			table.Columns.Add("RxNum");
			table.Columns.Add("SheetNum");
			table.Columns.Add("signature");
			table.Columns.Add("Surf");
			table.Columns.Add("surf");
			table.Columns.Add("TaskNum");
			table.Columns.Add("toothNum");
			table.Columns.Add("ToothNum");
			table.Columns.Add("ToothRange");
			table.Columns.Add("user");
			//table.Columns.Add("");
			//but we won't actually fill this table with rows until the very end.  It's more useful to use a List<> for now.
			List<DataRow> rows=new List<DataRow>();
			string command;
			DateTime dateT;
			string txt;
			List<DataRow> labRows=new List<DataRow>();//Canadian lab procs, which must be added in a loop at the very end.
			if(componentsToLoad.ShowTreatPlan
				|| componentsToLoad.ShowCompleted
				|| componentsToLoad.ShowExisting
				|| componentsToLoad.ShowReferred
				|| componentsToLoad.ShowConditions){
				#region Procedures
				command="SELECT provider.Abbr,procedurecode.AbbrDesc,appointment.AptDateTime,procedurelog.BaseUnits,procedurelog.ClinicNum,"
				+"procedurelog.CodeNum,procedurelog.DateEntryC,orionproc.DateScheduleBy,orionproc.DateStopClock,procedurelog.DateTP,"
				+"procedurecode.Descript,orionproc.DPC,orionproc.DPCpost,Dx,HideGraphics,orionproc.IsEffectiveComm,IsLocked,orionproc.IsOnCall,"
				+"LaymanTerm,Priority,procedurecode.ProcCode,ProcDate,ProcFee,procedurelog.ProcNum,ProcNumLab,procedurelog.ProcTime,"
				+"procedurelog.ProcTimeEnd,procedurelog.Prognosis,ProcStatus,orionproc.Status2,Surf,ToothNum,ToothRange,UnitQty "
				+"FROM procedurelog "
				+"LEFT JOIN procedurecode ON procedurecode.CodeNum=procedurelog.CodeNum "
				+"LEFT JOIN provider ON provider.ProvNum=procedurelog.ProvNum "
				+"LEFT JOIN orionproc ON procedurelog.ProcNum=orionproc.ProcNum "
				+"LEFT JOIN appointment ON appointment.AptNum=procedurelog.AptNum "
				+"AND (appointment.AptStatus="+POut.Long((int)ApptStatus.Scheduled)
				+" OR appointment.AptStatus="+POut.Long((int)ApptStatus.ASAP)
				+" OR appointment.AptStatus="+POut.Long((int)ApptStatus.Broken)
				+" OR appointment.AptStatus="+POut.Long((int)ApptStatus.Complete)
				+") WHERE procedurelog.PatNum="+POut.Long(patNum);
				if(!isAuditMode) {//regular mode
					command+=" AND (ProcStatus !=6"//not deleted
						+" OR IsLocked=1)";//Any locked proc should show.  This forces invalidated (deleted locked) procs to show.
				}
				command+=" ORDER BY ProcDate";//we'll just have to reorder it anyway
				DataTable rawProcs=dcon.GetTable(command);
				command="SELECT ProcNum,EntryDateTime,UserNum,Note,"
				+"CASE WHEN Signature!='' THEN 1 ELSE 0 END AS SigPresent "
				+"FROM procnote WHERE PatNum="+POut.Long(patNum)
				+" ORDER BY EntryDateTime";// but this helps when looping for notes
				DataTable rawNotes=dcon.GetTable(command);
				for(int i=0;i<rawProcs.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]=rawProcs.Rows[i]["AbbrDesc"].ToString();
					row["aptDateTime"]=PIn.DateT(rawProcs.Rows[i]["AptDateTime"].ToString());
					row["AptNum"]=0;
					row["clinic"]=Clinics.GetDesc(PIn.Long(rawProcs.Rows[i]["ClinicNum"].ToString()));
					row["CodeNum"]=rawProcs.Rows[i]["CodeNum"].ToString();
					row["colorBackG"]=Color.White.ToArgb();
					if(((DateTime)row["aptDateTime"]).Date==DateTime.Today) {
						row["colorBackG"]=DefC.Long[(int)DefCat.MiscColors][6].ItemColor.ToArgb().ToString();
					}
					switch((ProcStat)PIn.Long(rawProcs.Rows[i]["ProcStatus"].ToString())) {
						case ProcStat.TP:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][0].ItemColor.ToArgb().ToString();
							break;
						case ProcStat.C:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][1].ItemColor.ToArgb().ToString();
							break;
						case ProcStat.EC:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][2].ItemColor.ToArgb().ToString();
							break;
						case ProcStat.EO:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][3].ItemColor.ToArgb().ToString();
							break;
						case ProcStat.R:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][4].ItemColor.ToArgb().ToString();
							break;
						case ProcStat.D:
							row["colorText"]=Color.Black.ToArgb().ToString();
							break;
						case ProcStat.Cn:
							row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][22].ItemColor.ToArgb().ToString();
							break;
					}
					row["CommlogNum"]=0;
					dateT=PIn.DateT(rawProcs.Rows[i]["DateEntryC"].ToString());
					if(dateT.Year<1880) {
						row["dateEntryC"]="";
					}
					else {
						row["dateEntryC"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					dateT=PIn.DateT(rawProcs.Rows[i]["DateTP"].ToString());
					if(dateT.Year<1880) {
						row["dateTP"]="";
					}
					else {
						row["dateTP"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					if(rawProcs.Rows[i]["LaymanTerm"].ToString()=="") {
						row["description"]=rawProcs.Rows[i]["Descript"].ToString();
					}
					else {
						row["description"]=rawProcs.Rows[i]["LaymanTerm"].ToString();
					}
					if(rawProcs.Rows[i]["ToothRange"].ToString()!="") {
						row["description"]+=" #"+Tooth.FormatRangeForDisplay(rawProcs.Rows[i]["ToothRange"].ToString());
					}
					row["dx"]=DefC.GetValue(DefCat.Diagnosis,PIn.Long(rawProcs.Rows[i]["Dx"].ToString()));
					row["Dx"]=rawProcs.Rows[i]["Dx"].ToString();
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]=rawProcs.Rows[i]["HideGraphics"].ToString();
					row["isLocked"]=PIn.Bool(rawProcs.Rows[i]["isLocked"].ToString())?"X":"";
					row["LabCaseNum"]=0;
					row["length"]="";
					row["signature"]="";
					row["user"]="";
					if(componentsToLoad.ShowProcNotes) {
						#region note-----------------------------------------------------------------------------------------------------------
						row["note"]="";
						dateT=PIn.DateT(rawProcs.Rows[i]["DateScheduleBy"].ToString());
						if(dateT.Year<1880) {
							row["orionDateScheduleBy"]="";
						}
						else {
							row["orionDateScheduleBy"]=dateT.ToString(Lans.GetShortDateTimeFormat());
						}
						dateT=PIn.DateT(rawProcs.Rows[i]["DateStopClock"].ToString());
						if(dateT.Year<1880) {
							row["orionDateStopClock"]="";
						}
						else {
							row["orionDateStopClock"]=dateT.ToString(Lans.GetShortDateTimeFormat());
						}
						if(((OrionDPC)PIn.Int(rawProcs.Rows[i]["DPC"].ToString())).ToString()=="NotSpecified") {
							row["orionDPC"]="";
						}
						else {
							row["orionDPC"]=((OrionDPC)PIn.Int(rawProcs.Rows[i]["DPC"].ToString())).ToString();
						}
						if(((OrionDPC)PIn.Int(rawProcs.Rows[i]["DPCpost"].ToString())).ToString()=="NotSpecified") {
							row["orionDPCpost"]="";
						}
						else {
							row["orionDPCpost"]=((OrionDPC)PIn.Int(rawProcs.Rows[i]["DPCpost"].ToString())).ToString();
						}
						row["orionIsEffectiveComm"]="";
						if(rawProcs.Rows[i]["IsEffectiveComm"].ToString()=="1") {
							row["orionIsEffectiveComm"]="Y";
						}
						else if(rawProcs.Rows[i]["IsEffectiveComm"].ToString()=="0") {
							row["orionIsEffectiveComm"]="";
						}
						row["orionIsOnCall"]="";
						if(rawProcs.Rows[i]["IsOnCall"].ToString()=="1") {
							row["orionIsOnCall"]="Y";
						}
						else if(rawProcs.Rows[i]["IsOnCall"].ToString()=="0") {
							row["orionIsOnCall"]="";
						}
						row["orionStatus2"]=((OrionStatus)PIn.Int(rawProcs.Rows[i]["Status2"].ToString())).ToString();
						if(isAuditMode) {//we will include all notes for each proc.  We will concat and make readable.
							for(int n=0;n<rawNotes.Rows.Count;n++) {//loop through each note
								if(rawProcs.Rows[i]["ProcNum"].ToString() != rawNotes.Rows[n]["ProcNum"].ToString()) {
									continue;
								}
								if(row["note"].ToString()!="") {//if there is an existing note
									row["note"]+="\r\n------------------------------------------------------\r\n";//start a new line
								}
								row["note"]+=PIn.DateT(rawNotes.Rows[n]["EntryDateTime"].ToString()).ToString();
								row["note"]+="  "+Userods.GetName(PIn.Long(rawNotes.Rows[n]["UserNum"].ToString()));
								if(rawNotes.Rows[n]["SigPresent"].ToString()=="1") {
									row["note"]+="  "+Lans.g("ChartModule","(signed)");
								}
								row["note"]+="\r\n"+rawNotes.Rows[n]["Note"].ToString();
							}
						}
						else {//Not audit mode.  We just want the most recent note
							for(int n=rawNotes.Rows.Count-1;n>=0;n--) {//loop through each note, backwards.
								if(rawProcs.Rows[i]["ProcNum"].ToString() != rawNotes.Rows[n]["ProcNum"].ToString()) {
									continue;
								}
								row["note"]=rawNotes.Rows[n]["Note"].ToString();
								break;//out of note loop.
							}
						}
						#endregion Note
					}
					//This section is closely related to notes, but must be filled for all procedures regardless of whether showing the actual note.
					if(!isAuditMode) {//Audit mode is handled above by putting this info into the note section itself.
						for(int n=rawNotes.Rows.Count-1;n>=0;n--) {//Loop through each note; backwards to get most recent note.
							if(rawProcs.Rows[i]["ProcNum"].ToString() != rawNotes.Rows[n]["ProcNum"].ToString()) {
								continue;
							}
							row["user"]=Userods.GetName(PIn.Long(rawNotes.Rows[n]["UserNum"].ToString()));
							if(rawNotes.Rows[n]["SigPresent"].ToString()=="1") {
								row["signature"]=Lans.g("ChartModule","Signed");
							}
							else {
								row["signature"]="";
							}
							break;
						}
					}
					row["PatNum"]="";
					row["Priority"]=rawProcs.Rows[i]["Priority"].ToString();
					row["priority"]=DefC.GetName(DefCat.TxPriorities,PIn.Long(rawProcs.Rows[i]["Priority"].ToString()));
					row["ProcCode"]=rawProcs.Rows[i]["ProcCode"].ToString();
					dateT=PIn.DateT(rawProcs.Rows[i]["ProcDate"].ToString());
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["ProcDate"]=dateT;
					double amt = PIn.Double(rawProcs.Rows[i]["ProcFee"].ToString());
					int qty = PIn.Int(rawProcs.Rows[i]["UnitQty"].ToString()) + PIn.Int(rawProcs.Rows[i]["BaseUnits"].ToString());
					if(qty>0) {
						amt *= qty;
					}
					row["procFee"]=amt.ToString("F");
					row["ProcNum"]=rawProcs.Rows[i]["ProcNum"].ToString();
					row["ProcNumLab"]=rawProcs.Rows[i]["ProcNumLab"].ToString();
					row["procStatus"]=Lans.g("enumProcStat",((ProcStat)PIn.Long(rawProcs.Rows[i]["ProcStatus"].ToString())).ToString());
					if(row["procStatus"].ToString()=="D") {
						if(row["isLocked"].ToString()=="X") {
							row["procStatus"]="I";
							row["description"]=Lans.g("ChartModule","-invalid-")+" "+row["description"].ToString();
						}
					}
					row["ProcStatus"]=rawProcs.Rows[i]["ProcStatus"].ToString();
					row["procTime"]="";
					dateT=PIn.DateT(rawProcs.Rows[i]["ProcTime"].ToString());
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["procTimeEnd"]="";
					dateT=PIn.DateT(rawProcs.Rows[i]["ProcTimeEnd"].ToString());
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTimeEnd"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["prognosis"]=DefC.GetName(DefCat.Prognosis,PIn.Long(rawProcs.Rows[i]["Prognosis"].ToString()));
					row["prov"]=rawProcs.Rows[i]["Abbr"].ToString();
					row["quadrant"]="";
					if(ProcedureCodes.GetProcCode(PIn.Long(row["CodeNum"].ToString())).TreatArea==TreatmentArea.Tooth) {
						row["quadrant"]=Tooth.GetQuadrant(rawProcs.Rows[i]["ToothNum"].ToString());
					}
					else if(ProcedureCodes.GetProcCode(PIn.Long(row["CodeNum"].ToString())).TreatArea==TreatmentArea.Surf) {
						row["quadrant"]=Tooth.GetQuadrant(rawProcs.Rows[i]["ToothNum"].ToString());
					}
					else if(ProcedureCodes.GetProcCode(PIn.Long(row["CodeNum"].ToString())).TreatArea==TreatmentArea.Quad) {
						row["quadrant"]=rawProcs.Rows[i]["Surf"].ToString();
					}
					else if(ProcedureCodes.GetProcCode(PIn.Long(row["CodeNum"].ToString())).TreatArea==TreatmentArea.ToothRange) {
						string[] toothNum=rawProcs.Rows[i]["ToothRange"].ToString().Split(',');
						bool sameQuad=false;//Don't want true if length==0.
						for(int n=0;n<toothNum.Length;n++) {//But want true if length==1 (check index 0 against itself).
							if(Tooth.GetQuadrant(toothNum[n])==Tooth.GetQuadrant(toothNum[0])) {
								sameQuad=true;
							}
							else {
								sameQuad=false;
								break;
							}
						}
						if(sameQuad) {
							row["quadrant"]=Tooth.GetQuadrant(toothNum[0]);
						}
					}
					row["RxNum"]=0;
					row["SheetNum"]=0;
					row["Surf"]=rawProcs.Rows[i]["Surf"].ToString();
					if(ProcedureCodes.GetProcCode(PIn.Long(row["CodeNum"].ToString())).TreatArea==TreatmentArea.Surf) {
						row["surf"]=Tooth.SurfTidyFromDbToDisplay(rawProcs.Rows[i]["Surf"].ToString(),rawProcs.Rows[i]["ToothNum"].ToString());
					}
					else {
						row["surf"]=rawProcs.Rows[i]["Surf"].ToString();
					}
					row["TaskNum"]=0;
					row["toothNum"]=Tooth.GetToothLabel(rawProcs.Rows[i]["ToothNum"].ToString());
					row["ToothNum"]=rawProcs.Rows[i]["ToothNum"].ToString();
					row["ToothRange"]=rawProcs.Rows[i]["ToothRange"].ToString();
					if(rawProcs.Rows[i]["ProcNumLab"].ToString()=="0") {//normal proc
						rows.Add(row);
					}
					else {
						row["description"]="^ ^ "+row["description"].ToString();
						labRows.Add(row);//these will be added in the loop at the end
					}
				}
				#endregion Procedures
			}
			if(componentsToLoad.ShowCommLog) {//TODO: refine to use show Family
				#region Commlog
				command="SELECT CommlogNum,CommDateTime,commlog.DateTimeEnd,CommType,Note,commlog.PatNum,UserNum,p1.FName,"
				+"CASE WHEN Signature!='' THEN 1 ELSE 0 END SigPresent "
				+"FROM patient p1,patient p2,commlog "
				+"WHERE commlog.PatNum=p1.PatNum "
				+"AND p1.Guarantor=p2.Guarantor "
				+"AND p2.PatNum="+POut.Long(patNum)
				+" ORDER BY CommDateTime";
				DataTable rawComm=dcon.GetTable(command);
				for(int i=0;i<rawComm.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					row["colorBackG"]=Color.White.ToArgb();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();
					row["CommlogNum"]=rawComm.Rows[i]["CommlogNum"].ToString();
					row["dateEntryC"]="";
					row["dateTP"]="";
					if(rawComm.Rows[i]["PatNum"].ToString()==patNum.ToString()) {
						txt="";
					}
					else {
						txt="("+rawComm.Rows[i]["FName"].ToString()+") ";
					}
					row["description"]=txt+Lans.g("ChartModule","Comm - ")
					+DefC.GetName(DefCat.CommLogTypes,PIn.Long(rawComm.Rows[i]["CommType"].ToString()));
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=0;
					row["length"]="";
					if(PIn.DateT(rawComm.Rows[i]["DateTimeEnd"].ToString()).Year>1880) {
						DateTime startTime=PIn.DateT(rawComm.Rows[i]["CommDateTime"].ToString());
						DateTime endTime=PIn.DateT(rawComm.Rows[i]["DateTimeEnd"].ToString());
						row["length"]=(endTime-startTime).ToStringHmm();
					}
					row["note"]=rawComm.Rows[i]["Note"].ToString();
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]=rawComm.Rows[i]["PatNum"].ToString();
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					dateT=PIn.DateT(rawComm.Rows[i]["CommDateTime"].ToString());
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["ProcDate"]=dateT;
					row["procTime"]="";
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["procTimeEnd"]="";
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["prov"]="";
					row["quadrant"]="";
					row["RxNum"]=0;
					row["SheetNum"]=0;
					row["signature"]="";
					if(rawComm.Rows[i]["SigPresent"].ToString()=="1") {
						row["signature"]=Lans.g("ChartModule","Signed");
					}
					row["Surf"]="";
					row["TaskNum"]=0;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]=Userods.GetName(PIn.Long(rawComm.Rows[i]["UserNum"].ToString()));
					rows.Add(row);
				}
				#endregion Commlog
			}
			if(componentsToLoad.ShowFormPat) {
				#region formpat
				command = "SELECT FormDateTime,FormPatNum "
				+ "FROM formpat WHERE PatNum ='" + POut.Long(patNum) + "' ORDER BY FormDateTime";
				DataTable rawForm = dcon.GetTable(command);
				for(int i = 0;i < rawForm.Rows.Count;i++) {
					row = table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"] = DateTime.MinValue;
					row["AptNum"] = 0;
					row["clinic"]="";
					row["CodeNum"] = "";
					row["colorBackG"] = Color.White.ToArgb();
					row["colorText"] = DefC.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();
					row["CommlogNum"] =0;
					row["dateEntryC"]="";
					row["dateTP"]="";
					row["description"] = Lans.g("ChartModule","Questionnaire");
					row["dx"] = "";
					row["Dx"] = "";
					row["EmailMessageNum"] = 0;
					row["FormPatNum"] = rawForm.Rows[i]["FormPatNum"].ToString();
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"] = 0;
					row["length"]="";
					row["note"] = "";
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"] = "";
					row["Priority"] = "";
					row["priority"]="";
					row["ProcCode"] = "";
					dateT = PIn.DateT(rawForm.Rows[i]["FormDateTime"].ToString());
					row["ProcDate"] = dateT.ToShortDateString();
					if(dateT.TimeOfDay != TimeSpan.Zero) {
						row["procTime"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
					}
					if(dateT.Year < 1880) {
						row["procDate"] = "";
					}
					else {
						row["procDate"] = dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					if(dateT.TimeOfDay != TimeSpan.Zero) {
						row["procTime"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
					}
					row["procTimeEnd"]="";
					row["procFee"] = "";
					row["ProcNum"] = 0;
					row["ProcNumLab"] = "";
					row["procStatus"] = "";
					row["ProcStatus"] = "";
					row["prov"] = "";
					row["quadrant"]="";
					row["RxNum"] = 0;
					row["SheetNum"] = 0;
					row["signature"] = "";
					row["Surf"] = "";
					row["TaskNum"] = 0;
					row["toothNum"] = "";
					row["ToothNum"] = "";
					row["ToothRange"] = "";
					row["user"] = "";
					/*commlog code
					dateT = PIn.PDateT(rawForm.Rows[i]["FormDateTime"].ToString());
					row["CommDateTime"] = dateT;
					row["commDate"] = dateT.ToShortDateString();
					if (dateT.TimeOfDay != TimeSpan.Zero)
					{
							row["commTime"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
					}
					row["CommlogNum"] = "0";
					row["commType"] = Lans.g("AccountModule", "Questionnaire");
					row["EmailMessageNum"] = "0";
					row["FormPatNum"] = rawForm.Rows[i]["FormPatNum"].ToString();
					row["mode"] = "";
					row["Note"] = "";
					row["patName"] = "";
					row["SheetNum"] = "0";
					//row["sentOrReceived"]="";
					*/
					rows.Add(row);
				}
				#endregion formpat
			}
			if(componentsToLoad.ShowRX) {
				#region Rx
				command="SELECT RxNum,RxDate,Drug,Disp,ProvNum,Notes,PharmacyNum FROM rxpat WHERE PatNum="+POut.Long(patNum)
				+" ORDER BY RxDate";
				DataTable rawRx=dcon.GetTable(command);
				for(int i=0;i<rawRx.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					row["colorBackG"]=Color.White.ToArgb();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][5].ItemColor.ToArgb().ToString();
					row["CommlogNum"]=0;
					row["dateEntryC"]="";
					row["dateTP"]="";
					row["description"]=Lans.g("ChartModule","Rx - ")+rawRx.Rows[i]["Drug"].ToString()+" - #"+rawRx.Rows[i]["Disp"].ToString();
					if(rawRx.Rows[i]["PharmacyNum"].ToString()!="0") {
						row["description"]+="\r\n"+Pharmacies.GetDescription(PIn.Long(rawRx.Rows[i]["PharmacyNum"].ToString()));
					}
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=0;
					row["length"]="";
					row["note"]=rawRx.Rows[i]["Notes"].ToString();
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]="";
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					dateT=PIn.Date(rawRx.Rows[i]["RxDate"].ToString());
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["ProcDate"]=dateT;
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["procTime"]="";
					row["procTimeEnd"]="";
					row["prov"]=Providers.GetAbbr(PIn.Long(rawRx.Rows[i]["ProvNum"].ToString()));
					row["quadrant"]="";
					row["RxNum"]=rawRx.Rows[i]["RxNum"].ToString();
					row["SheetNum"]=0;
					row["signature"]="";
					row["Surf"]="";
					row["TaskNum"]=0;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]="";
					rows.Add(row);
				}
				#endregion Rx
			}
			if(componentsToLoad.ShowLabCases) {
				#region LabCase
				command="SELECT labcase.*,Description,Phone FROM labcase,laboratory "
				+"WHERE labcase.LaboratoryNum=laboratory.LaboratoryNum "
				+"AND PatNum="+POut.Long(patNum)
				+" ORDER BY DateTimeCreated";
				DataTable rawLab=dcon.GetTable(command);
				DateTime duedate;
				for(int i=0;i<rawLab.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					row["colorBackG"]=Color.White.ToArgb();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][7].ItemColor.ToArgb().ToString();
					row["CommlogNum"]=0;
					row["dateEntryC"]="";
					row["dateTP"]="";
					row["description"]=Lans.g("ChartModule","LabCase - ")+rawLab.Rows[i]["Description"].ToString()+" "
					+rawLab.Rows[i]["Phone"].ToString();
					if(PIn.Date(rawLab.Rows[i]["DateTimeDue"].ToString()).Year>1880) {
						duedate=PIn.DateT(rawLab.Rows[i]["DateTimeDue"].ToString());
						row["description"]+="\r\n"+Lans.g("ChartModule","Due")+" "+duedate.ToString("ddd")+" "
						+duedate.ToShortDateString()+" "+duedate.ToShortTimeString();
					}
					if(PIn.Date(rawLab.Rows[i]["DateTimeChecked"].ToString()).Year>1880) {
						row["description"]+="\r\n"+Lans.g("ChartModule","Quality Checked");
					}
					else if(PIn.Date(rawLab.Rows[i]["DateTimeRecd"].ToString()).Year>1880) {
						row["description"]+="\r\n"+Lans.g("ChartModule","Received");
					}
					else if(PIn.Date(rawLab.Rows[i]["DateTimeSent"].ToString()).Year>1880) {
						row["description"]+="\r\n"+Lans.g("ChartModule","Sent");
					}
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=rawLab.Rows[i]["LabCaseNum"].ToString();
					row["length"]="";
					row["note"]=rawLab.Rows[i]["Instructions"].ToString();
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]="";
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					dateT=PIn.DateT(rawLab.Rows[i]["DateTimeCreated"].ToString());
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["procTime"]="";
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["ProcDate"]=dateT;
					row["procTimeEnd"]="";
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["prov"]="";
					row["quadrant"]="";
					row["RxNum"]=0;
					row["SheetNum"]=0;
					row["signature"]="";
					row["Surf"]="";
					row["TaskNum"]=0;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]="";
					rows.Add(row);
				}
				#endregion LabCase
			}
			if(componentsToLoad.ShowTasks) {
				#region Task
				command="SELECT task.*,tasklist.Descript ListDisc,p1.FName "
				+"FROM patient p1,patient p2, task,tasklist "
				+"WHERE task.KeyNum=p1.PatNum "
				+"AND task.TaskListNum=tasklist.TaskListNum "
				+"AND p1.Guarantor=p2.Guarantor "
				+"AND p2.PatNum="+POut.Long(patNum)
				+" AND task.ObjectType=1 "
				+"ORDER BY DateTimeEntry";
				DataTable rawTask=dcon.GetTable(command);
				List<long> taskNums=new List<long>();
				for(int i=0;i<rawTask.Rows.Count;i++) {
					taskNums.Add(PIn.Long(rawTask.Rows[i]["TaskNum"].ToString()));
				}
				List<TaskNote> TaskNoteList=TaskNotes.RefreshForTasks(taskNums);
				for(int i=0;i<rawTask.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					//colors the same as notes
					row["colorText"] = DefC.Long[(int)DefCat.ProgNoteColors][18].ItemColor.ToArgb().ToString();
					row["colorBackG"] = DefC.Long[(int)DefCat.ProgNoteColors][19].ItemColor.ToArgb().ToString();
					//row["colorText"] = DefC.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();//same as commlog
					row["CommlogNum"]=0;
					row["dateEntryC"]="";
					row["dateTP"]="";
					if(rawTask.Rows[i]["KeyNum"].ToString()==patNum.ToString()) {
						txt="";
					}
					else {
						txt="("+rawTask.Rows[i]["FName"].ToString()+") ";
					}
					if(rawTask.Rows[i]["TaskStatus"].ToString()=="2") {//completed
						txt += Lans.g("ChartModule","Completed ");
						row["colorBackG"] = Color.White.ToArgb();
						//use same as note colors for completed tasks
						row["colorText"] = DefC.Long[(int)DefCat.ProgNoteColors][20].ItemColor.ToArgb().ToString();
						row["colorBackG"] = DefC.Long[(int)DefCat.ProgNoteColors][21].ItemColor.ToArgb().ToString();
					}
					row["description"]=txt+Lans.g("ChartModule","Task - In List: ")+rawTask.Rows[i]["ListDisc"].ToString();
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=0;
					row["length"]="";
					txt="";
					if(!rawTask.Rows[i]["Descript"].ToString().StartsWith("==") && rawTask.Rows[i]["UserNum"].ToString()!="") {
						txt+=Userods.GetName(PIn.Long(rawTask.Rows[i]["UserNum"].ToString()))+" - ";
					}
					txt+=rawTask.Rows[i]["Descript"].ToString();
					long taskNum=PIn.Long(rawTask.Rows[i]["TaskNum"].ToString());
					for(int n=0;n<TaskNoteList.Count;n++) {
						if(TaskNoteList[n].TaskNum!=taskNum) {
							continue;
						}
						txt+="\r\n"//even on the first loop
						+"=="+Userods.GetName(TaskNoteList[n].UserNum)+" - "
						+TaskNoteList[n].DateTimeNote.ToShortDateString()+" "
						+TaskNoteList[n].DateTimeNote.ToShortTimeString()
						+" - "+TaskNoteList[n].Note;
					}
					row["note"]=txt;
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]=rawTask.Rows[i]["KeyNum"].ToString();
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					dateT = PIn.DateT(rawTask.Rows[i]["DateTask"].ToString());
					row["procTime"]="";
					if(dateT.Year < 1880) {//check if due date set for task or note
						dateT = PIn.DateT(rawTask.Rows[i]["DateTimeEntry"].ToString());
						if(dateT.Year < 1880) {//since dateT was just redefined, check it now
							row["procDate"] = "";
						}
						else {
							row["procDate"] = dateT.ToShortDateString();
						}
						if(dateT.TimeOfDay != TimeSpan.Zero) {
							row["procTime"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
						}
						row["ProcDate"] = dateT;
					}
					else {
						row["procDate"] =dateT.ToString(Lans.GetShortDateTimeFormat());
						if(dateT.TimeOfDay != TimeSpan.Zero) {
							row["procTime"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
						}
						row["ProcDate"] = dateT;
						//row["Surf"] = "DUE";
					}
					row["procTimeEnd"]="";
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["prov"]="";
					row["quadrant"]="";
					row["RxNum"]=0;
					row["SheetNum"]=0;
					row["signature"]="";
					row["Surf"]="";
					row["TaskNum"]=taskNum;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]="";
					rows.Add(row);
				}
				#endregion Task
			}
			#region Appointments
			command="SELECT * FROM appointment WHERE PatNum="+POut.Long(patNum);
			if(componentsToLoad.ShowAppointments) {//we will need this table later for planned appts, so always need to get.
				//get all appts
			}
			else{
				//only include planned appts.  We will need those later, but not in this grid.
				command+=" AND AptStatus = "+POut.Int((int)ApptStatus.Planned);
			}
			command+=" ORDER BY AptDateTime";
			rawApt=dcon.GetTable(command);
			long apptStatus;
			for(int i=0;i<rawApt.Rows.Count;i++) {
				row=table.NewRow();
				row["AbbrDesc"]="";
				row["aptDateTime"]=DateTime.MinValue;
				row["AptNum"]=rawApt.Rows[i]["AptNum"].ToString();
				row["clinic"]="";
				row["colorBackG"]=Color.White.ToArgb();
				dateT=PIn.DateT(rawApt.Rows[i]["AptDateTime"].ToString());
				apptStatus=PIn.Long(rawApt.Rows[i]["AptStatus"].ToString());
				row["colorBackG"]="";
				row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][8].ItemColor.ToArgb().ToString();
				row["CommlogNum"]=0;
				row["dateEntryC"]="";
				row["dateTP"]="";
				row["description"]=Lans.g("ChartModule","Appointment - ")+dateT.ToShortTimeString()+"\r\n"
				+rawApt.Rows[i]["ProcDescript"].ToString();
				if(dateT.Date.Date==DateTime.Today.Date) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][9].ItemColor.ToArgb().ToString(); //deliniates nicely between old appts
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][8].ItemColor.ToArgb().ToString();
				}
				else if(dateT.Date<DateTime.Today) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][11].ItemColor.ToArgb().ToString();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][10].ItemColor.ToArgb().ToString();
				}
				else if(dateT.Date>DateTime.Today) {
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][13].ItemColor.ToArgb().ToString(); //at a glace, you see green...the pt is good to go as they have a future appt scheduled
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][12].ItemColor.ToArgb().ToString();
				}
				if(apptStatus==(int)ApptStatus.Broken) {
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][14].ItemColor.ToArgb().ToString();
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][15].ItemColor.ToArgb().ToString();
					row["description"]=Lans.g("ChartModule","BROKEN Appointment - ")+dateT.ToShortTimeString()+"\r\n"
					+rawApt.Rows[i]["ProcDescript"].ToString();
				}
				else if(apptStatus==(int)ApptStatus.UnschedList) {
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][14].ItemColor.ToArgb().ToString();
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][15].ItemColor.ToArgb().ToString();
					row["description"]=Lans.g("ChartModule","UNSCHEDULED Appointment - ")+dateT.ToShortTimeString()+"\r\n"
					+rawApt.Rows[i]["ProcDescript"].ToString();
				}
				else if(apptStatus==(int)ApptStatus.Planned) {
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][16].ItemColor.ToArgb().ToString();
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][17].ItemColor.ToArgb().ToString();
					row["description"]=Lans.g("ChartModule","PLANNED Appointment")+"\r\n"
					+rawApt.Rows[i]["ProcDescript"].ToString();
				}
				else if(apptStatus==(int)ApptStatus.PtNote) {
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][18].ItemColor.ToArgb().ToString();
					row["colorBackG"]=DefC.Long[(int)DefCat.ProgNoteColors][19].ItemColor.ToArgb().ToString();
					row["description"] = Lans.g("ChartModule","*** Patient NOTE  *** - ") + dateT.ToShortTimeString();
				}
				else if(apptStatus ==(int)ApptStatus.PtNoteCompleted) {
					row["colorText"] = DefC.Long[(int)DefCat.ProgNoteColors][20].ItemColor.ToArgb().ToString();
					row["colorBackG"] = DefC.Long[(int)DefCat.ProgNoteColors][21].ItemColor.ToArgb().ToString();
					row["description"] = Lans.g("ChartModule","** Complete Patient NOTE ** - ") + dateT.ToShortTimeString();
				}
				row["dx"]="";
				row["Dx"]="";
				row["EmailMessageNum"]=0;
				row["FormPatNum"]=0;
				row["HideGraphics"]="";
				row["isLocked"]="";
				row["LabCaseNum"]=0;
				row["length"]="";
				if(rawApt.Rows[i]["Pattern"].ToString()!="") {
					row["length"]=new TimeSpan(0,rawApt.Rows[i]["Pattern"].ToString().Length*5,0).ToStringHmm();
				}
				row["note"]=rawApt.Rows[i]["Note"].ToString();
				row["orionDateScheduleBy"]="";
				row["orionDateStopClock"]="";
				row["orionDPC"]="";
				row["orionDPCpost"]="";
				row["orionIsEffectiveComm"]="";
				row["orionIsOnCall"]="";
				row["orionStatus2"]="";
				row["PatNum"]="";
				row["Priority"]="";
				row["priority"]="";
				row["ProcCode"]="";
				if(dateT.Year<1880) {
					row["procDate"]="";
				}
				else {
					row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
				}
				row["procTime"]="";
				if(dateT.TimeOfDay!=TimeSpan.Zero) {
					row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
				}
				row["ProcDate"]=dateT;
				row["procTimeEnd"]="";
				row["procFee"]="";
				row["ProcNum"]=0;
				row["ProcNumLab"]="";
				row["procStatus"]="";
				row["ProcStatus"]="";
				row["prov"]="";
				row["quadrant"]="";
				row["RxNum"]=0;
				row["SheetNum"]=0;
				row["signature"]="";
				row["Surf"]="";
				row["TaskNum"]=0;
				row["toothNum"]="";
				row["ToothNum"]="";
				row["ToothRange"]="";
				row["user"]="";
				rows.Add(row);
			}
			#endregion Appointments
			if(componentsToLoad.ShowEmail) {
				#region email
				command="SELECT EmailMessageNum,MsgDateTime,Subject,BodyText,PatNum,SentOrReceived "
				+"FROM emailmessage "
				+"WHERE PatNum="+POut.Long(patNum)+" AND SentOrReceived NOT IN (12,13) "//Do not show Direct message acknowledgements in Chart progress notes
				+"ORDER BY MsgDateTime";
				DataTable rawEmail=dcon.GetTable(command);
				for(int i=0;i<rawEmail.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					row["colorBackG"]=Color.White.ToArgb();
					row["colorText"]=DefC.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();//needs to change
					row["CommlogNum"]=0;
					row["dateEntryC"]="";
					row["dateTP"]="";
					txt="";
					if(rawEmail.Rows[i]["SentOrReceived"].ToString()=="0") {
						txt=Lans.g("ChartModule","(unsent) ");
					}
					row["description"]=Lans.g("ChartModule","Email - ")+txt+rawEmail.Rows[i]["Subject"].ToString();
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=rawEmail.Rows[i]["EmailMessageNum"].ToString();
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=0;
					row["length"]="";
					row["note"]=rawEmail.Rows[i]["BodyText"].ToString();
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]="";
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					//row["PatNum"]=rawEmail.Rows[i]["PatNum"].ToString();
					dateT=PIn.DateT(rawEmail.Rows[i]["msgDateTime"].ToString());
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["ProcDate"]=dateT;
					row["procTime"]="";
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["procTimeEnd"]="";
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["prov"]="";
					row["quadrant"]="";
					row["RxNum"]=0;
					row["SheetNum"]=0;
					row["signature"]="";
					row["Surf"]="";
					row["TaskNum"]=0;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]="";
					rows.Add(row);
				}
				#endregion email
			}
			if(componentsToLoad.ShowSheets) {
				#region sheet
				command="SELECT Description,SheetNum,DateTimeSheet,SheetType "
				+"FROM sheet "
				+"WHERE PatNum="+POut.Long(patNum)
				+" AND SheetType!="+POut.Long((int)SheetTypeEnum.Rx)//rx are only accesssible from within Rx edit window.
				+" AND SheetType!="+POut.Long((int)SheetTypeEnum.LabSlip)//labslips are only accesssible from within the labslip edit window.
				+" ORDER BY DateTimeSheet";
				DataTable rawSheet=dcon.GetTable(command);
				//SheetTypeEnum sheetType;
				for(int i=0;i<rawSheet.Rows.Count;i++) {
					row=table.NewRow();
					row["AbbrDesc"]="";
					row["aptDateTime"]=DateTime.MinValue;
					row["AptNum"]=0;
					row["clinic"]="";
					row["CodeNum"]="";
					row["colorBackG"]=Color.White.ToArgb();
					row["colorText"]=Color.Black.ToArgb();//DefC.Long[(int)DefCat.ProgNoteColors][6].ItemColor.ToArgb().ToString();//needs to change
					row["CommlogNum"]=0;
					dateT=PIn.DateT(rawSheet.Rows[i]["DateTimeSheet"].ToString());
					if(dateT.Year<1880) {
						row["dateEntryC"]="";
						row["dateTP"]="";
					}
					else {
						row["dateEntryC"]=dateT.ToString(Lans.GetShortDateTimeFormat());
						row["dateTP"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					//sheetType=(SheetTypeEnum)PIn.PLong(rawSheet.Rows[i]["SheetType"].ToString());
					row["description"]=rawSheet.Rows[i]["Description"].ToString();
					row["dx"]="";
					row["Dx"]="";
					row["EmailMessageNum"]=0;
					row["FormPatNum"]=0;
					row["HideGraphics"]="";
					row["isLocked"]="";
					row["LabCaseNum"]=0;
					row["length"]="";
					row["note"]="";
					row["orionDateScheduleBy"]="";
					row["orionDateStopClock"]="";
					row["orionDPC"]="";
					row["orionDPCpost"]="";
					row["orionIsEffectiveComm"]="";
					row["orionIsOnCall"]="";
					row["orionStatus2"]="";
					row["PatNum"]="";
					row["Priority"]="";
					row["priority"]="";
					row["ProcCode"]="";
					if(dateT.Year<1880) {
						row["procDate"]="";
					}
					else {
						row["procDate"]=dateT.ToString(Lans.GetShortDateTimeFormat());
					}
					row["ProcDate"]=dateT;
					row["procTime"]="";
					if(dateT.TimeOfDay!=TimeSpan.Zero) {
						row["procTime"]=dateT.ToString("h:mm")+dateT.ToString("%t").ToLower();
					}
					row["procTimeEnd"]="";
					row["procFee"]="";
					row["ProcNum"]=0;
					row["ProcNumLab"]="";
					row["procStatus"]="";
					row["ProcStatus"]="";
					row["prov"]="";
					row["quadrant"]="";
					row["RxNum"]=0;
					row["SheetNum"]=rawSheet.Rows[i]["SheetNum"].ToString();
					row["signature"]="";
					row["Surf"]="";
					row["TaskNum"]=0;
					row["toothNum"]="";
					row["ToothNum"]="";
					row["ToothRange"]="";
					row["user"]="";
					rows.Add(row);
				}
				#endregion sheet
			}
			#region Sorting
			rows.Sort(CompareChartRows);
			//Canadian lab procedures need to come immediately after their corresponding proc---------------------------------
			for(int i=0;i<labRows.Count;i++) {
				for(int r=0;r<rows.Count;r++) {
					if(rows[r]["ProcNum"].ToString()==labRows[i]["ProcNumLab"].ToString()) {
						rows.Insert(r+1,labRows[i]);
						break;
					}
				}
			}
			#endregion Sorting
			for(int i=0;i<rows.Count;i++) {
				table.Rows.Add(rows[i]);
			}
			return table;
		}
Esempio n. 50
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. 51
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. 52
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. 53
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. 54
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. 55
0
        public static int Insert(Procedure proc)
        {
            if (PrefB.RandomKeys)
            {
                proc.ProcNum = MiscDataB.GetKey("procedurelog", "ProcNum");
            }
            string command = "INSERT INTO procedurelog (";

            if (PrefB.RandomKeys)
            {
                command += "ProcNum,";
            }
            command += "PatNum, AptNum, ADACode, ProcDate,ProcFee,Surf,"
                       + "ToothNum,ToothRange,Priority,ProcStatus,ProvNum,"
                       + "Dx,PlannedAptNum,PlaceService,Prosthesis,DateOriginalProsth,ClaimNote,"
                       + "DateEntryC,ClinicNum,MedicalCode,DiagnosticCode,IsPrincDiag,ProcNumLab) VALUES(";
            if (PrefB.RandomKeys)
            {
                command += "'" + POut.PInt(proc.ProcNum) + "', ";
            }
            command +=
                "'" + POut.PInt(proc.PatNum) + "', "
                + "'" + POut.PInt(proc.AptNum) + "', "
                + "'" + POut.PString(proc.ADACode) + "', "
                + POut.PDate(proc.ProcDate) + ", "
                + "'" + POut.PDouble(proc.ProcFee) + "', "
                + "'" + POut.PString(proc.Surf) + "', "
                + "'" + POut.PString(proc.ToothNum) + "', "
                + "'" + POut.PString(proc.ToothRange) + "', "
                + "'" + POut.PInt(proc.Priority) + "', "
                + "'" + POut.PInt((int)proc.ProcStatus) + "', "
                + "'" + POut.PInt(proc.ProvNum) + "', "
                + "'" + POut.PInt(proc.Dx) + "', "
                + "'" + POut.PInt(proc.PlannedAptNum) + "', "
                + "'" + POut.PInt((int)proc.PlaceService) + "', "
                + "'" + POut.PString(proc.Prosthesis) + "', "
                + POut.PDate(proc.DateOriginalProsth) + ", "
                + "'" + POut.PString(proc.ClaimNote) + "', ";
            if (DataConnection.DBtype == DatabaseType.Oracle)
            {
                command += POut.PDateT(MiscDataB.GetNowDateTime());
            }
            else              //Assume MySQL
            {
                command += "NOW()";
            }
            command += ", "          //DateEntryC
                       + "'" + POut.PInt(proc.ClinicNum) + "', "
                       + "'" + POut.PString(proc.MedicalCode) + "', "
                       + "'" + POut.PString(proc.DiagnosticCode) + "', "
                       + "'" + POut.PBool(proc.IsPrincDiag) + "', "
                       + "'" + POut.PInt(proc.ProcNumLab) + "')";
            //MessageBox.Show(cmd.CommandText);
            DataConnection dcon = new DataConnection();

            if (PrefB.RandomKeys)
            {
                dcon.NonQ(command);
            }
            else
            {
                dcon.NonQ(command, true);
                proc.ProcNum = dcon.InsertID;
            }
            if (proc.Note != "")
            {
                ProcNote note = new ProcNote();
                note.PatNum  = proc.PatNum;
                note.ProcNum = proc.ProcNum;
                note.UserNum = proc.UserNum;
                note.Note    = proc.Note;
                ProcNoteB.Insert(note);
            }
            return(proc.ProcNum);
        }