/// <summary>Will only convert to MyISAM if default storage engine set to MyISAM.</summary>
		private void butToMyIsam_Click(object sender,EventArgs e) {
			if(!MsgBox.Show(this,MsgBoxButtons.OKCancel,"This will convert all tables in the database to the MyISAM storage engine.  This may take several minutes.\r\nContinue?")) {
				return;
			}
			if(InnoDb.GetDefaultEngine()=="InnoDB") {
				MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(
					Lan.g("FormInnoDB","You will first need to change your default storage engine to MyISAM.  Make sure that the following line is in your my.ini file: \r\n"
					+"default-storage-engine=MyISAM.\r\n"
					+"Then, restart the MySQL service and return here."));
				msgbox.ShowDialog();
				return;
			}
			try {
				MiscData.MakeABackup();
			}
			catch(Exception ex) {
				if(ex.Message!="") {
					MessageBox.Show(ex.Message);
				}
				MsgBox.Show("FormInnoDb","Backup failed. Your database has not been altered.");
				return;
			}
			Cursor=Cursors.WaitCursor;
			textBox1.Text+=Lans.g("FormInnoDb","Default Storage Engine: "+InnoDb.GetDefaultEngine().ToString()+"\r\n");
			Application.DoEvents();
			int numchanged=InnoDb.ConvertTables("InnoDB","MyISAM");
			textBox1.Text+=Lan.g("FormInnoDb","Number of tables converted to MyIsam: ")+numchanged.ToString()+"\r\n";
			Application.DoEvents();
			textBox1.Text+=InnoDb.GetEngineCount();
			Application.DoEvents();
			Cursor=Cursors.Default;
		}
        private void butPushBoth_Click(object sender, EventArgs e)
        {
            if (textDate.errorProvider1.GetError(textDate) != "")
            {
                MsgBox.Show(this, "Please fix error first.");
                return;
            }
            //Enter info into local DB before pushing out to others so we save it.
            int      days = PIn.Int(textDays.Text);
            DateTime date = PIn.Date(textDate.Text);

            Prefs.UpdateString(PrefName.SecurityLockDate, POut.Date(date, false));
            Prefs.UpdateInt(PrefName.SecurityLockDays, days);
            Prefs.UpdateBool(PrefName.SecurityLockIncludesAdmin, checkAdmin.Checked);
            Prefs.UpdateBool(PrefName.CentralManagerSecurityLock, checkEnable.Checked);
            FormCentralConnections FormCC = new FormCentralConnections();

            FormCC.IsSelectionMode = true;
            FormCC.ShowDialog();
            if (FormCC.DialogResult != DialogResult.OK)
            {
                return;
            }
            CodeBase.MsgBoxCopyPaste MsgBoxCopyPaste = new CodeBase.MsgBoxCopyPaste(CentralSyncHelper.PushBoth(FormCC.ListConnsSelected));
            MsgBoxCopyPaste.ShowDialog();
        }
Exemple #3
0
        ///<summary>Log a message to the log text file and add a description of the sender (for debugging purposes). If sender is null then a description of the sender is not printed. Always returns false so that a calling boolean function can return at the same time that it logs an error message.</summary>
        public bool Log(Object sender, string sendingFunctionName, string message, bool msgBox)
        {
            if (curSev < level)          //Only log messages with a severity matches the current level. This will even skip message boxes.
            {
                return(false);
            }
            try{
                if (sender != null)
                {
                    if (sendingFunctionName != null && sendingFunctionName.Length > 0)
                    {
                        message = sender.ToString() + "." + sendingFunctionName + ": " + message;
                    }
                    else
                    {
                        message = sender.ToString() + ": " + message;
                    }
                }
                else if (sendingFunctionName != null && sendingFunctionName.Length > 0)
                {
                    message = sendingFunctionName + ": " + message;
                }
                int procId = System.Diagnostics.Process.GetCurrentProcess().Id;
                message = SeverityToString(curSev).PadRight(MaxSeverityStringLength() + 1, ' ') +
                          DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " " + procId.ToString().PadLeft(6, '0') + " " + message;
                if (msgBox)
                {
                    MsgBoxCopyPaste mbox = new MsgBoxCopyPaste(message);
                    mbox.ShowDialog();
                }
            }catch (Exception e) {
                MessageBox.Show(e.ToString());
            }
            //File access is always exclusive, so if we cannot access the file, we can try again for a little while
            //and hope that the other process will release the file.
            bool tryagain = true;
            int  numtries = 0;

            while (tryagain && numtries < 5)
            {
                tryagain = false;
                numtries++;
                try{
                    if (logFile != null)
                    {
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(logFile, true);                     //Open the file exclusively.
                        if (sw != null)
                        {
                            sw.WriteLine(message);
                            sw.Flush();
                            sw.Dispose();                            //Close the file to allow exclusive access by other instances of OpenDental.
                        }
                    }
                }catch (Exception) {
                    tryagain = true;
                }
            }
            return(false);
        }
        private void butPushLocks_Click(object sender, EventArgs e)
        {
            FormCentralConnections FormCC = new FormCentralConnections();

            FormCC.IsSelectionMode = true;
            FormCC.ShowDialog();
            if (FormCC.DialogResult != DialogResult.OK)
            {
                return;
            }
            CodeBase.MsgBoxCopyPaste MsgBoxCopyPaste = new CodeBase.MsgBoxCopyPaste(CentralSyncHelper.PushLocks(FormCC.ListConnsSelected));
            MsgBoxCopyPaste.ShowDialog();
        }
Exemple #5
0
 private void butBuild_Click(object sender,EventArgs e)
 {
     Cursor=Cursors.WaitCursor;
     MissingTables=new List<string>();
     //dcon=new DataConnection();
     command="SHOW TABLES";
     DataTable table=dcon.GetTable(command);
     string outputFile=ODFileUtils.CombinePaths(new string[] {"..","..","OpenDentalDocumentation.xml"});
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Indent = true;
     settings.IndentChars = ("    ");
     //input:
     string inputFile=ODFileUtils.CombinePaths(new string[] {"..","..","..","OpenDentBusiness","bin","Release","OpenDentBusiness.xml"});
     XmlDocument document=new XmlDocument();
     document.Load(inputFile);
     Navigator=document.CreateNavigator();
     using(XmlWriter writer=XmlWriter.Create(outputFile, settings)){
         //<?xml-stylesheet type="text/xsl" href="OpenDentalDocumentation.xsl"?>
         writer.WriteProcessingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"OpenDentalDocumentation.xsl\"");
             //("<?xml-stylesheet type=\"text/xsl\" href=\"OpenDentalDocumentation.xsl\"?>");
         writer.WriteStartElement("database");
         writer.WriteAttributeString("version",textVersion.Text);
         for(int i=0;i<table.Rows.Count;i++){
             WriteTable(writer,table.Rows[i][0].ToString());
         }
         writer.WriteEndElement();
         writer.Flush();
     }
     if(MissingTables.Count>0){
         string s="";
         for(int i=0;i<MissingTables.Count;i++){
             if(i>0){
                 s+="\r\n";
             }
             s+=MissingTables[i];
         }
         MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(s);
         msgbox.ShowDialog();
         Application.Exit();
         return;
     }
     //ProcessStartInfo startInfo=new ProcessStartInfo();
     //Process.Start("Notepad.exe",outputFile);
     //Process.Start("iexplore.exe",outputFile);
     Process.Start(outputFile);
     Application.Exit();
 }
Exemple #6
0
        private void RunTransfer()
        {
            //Get data from the source connection. This will have all the patients selected from the sourceconnection
            string   stringFailedConns = "";
            ODThread odThread          = new ODThread(GetDataFromSourceConnection, new object[] { _sourceConnection });

            odThread.GroupName = "FetchSheets";
            odThread.Start();
            ODThread.JoinThreadsByGroupName(Timeout.Infinite, "FetchSheets");
            if (_listSheetsForSelectedPats.IsNullOrEmpty())
            {
                string connString = CentralConnections.GetConnectionString(_sourceConnection);
                stringFailedConns += connString + "\r\n";
            }
            //Insert the sheets to each of the databases. The sheets will have a patnum=0;
            List <Action> listActions = new List <Action>();
            object        locker      = new object();

            foreach (CentralConnection conn in _listConnectionsToTransferTo)
            {
                List <Sheet> listSheets = _listSheetsForSelectedPats.Select(x => x.Copy()).ToList();
                listActions.Add(() => {
                    if (!InsertSheetsToConnection(conn, listSheets))
                    {
                        string connString = CentralConnections.GetConnectionString(conn);
                        lock (locker) {
                            stringFailedConns += connString + "\r\n";
                        }
                    }
                });
            }
            ODThread.RunParallel(listActions);
            if (stringFailedConns != "")
            {
                stringFailedConns = Lans.g(this, "There were some transfers that failed due to connection issues.  Fix connections and try again.\r\n"
                                           + "Failed Connections:") + "\r\n" + stringFailedConns;
                CodeBase.MsgBoxCopyPaste msgBoxCP = new CodeBase.MsgBoxCopyPaste(stringFailedConns);
                msgBoxCP.ShowDialog();
            }
            else
            {
                MsgBox.Show(this, "Transfers Completed Successfully\r\nGo to each database you transferred patients to and retrieve Webforms to finish the "
                            + "transfer process.");
            }
        }
Exemple #7
0
 /// <summary>destinationPath includes filename (Setup.exe).  destinationPath2 will create a second copy at the specified path/filename, or it will be skipped if null or empty.</summary>
 public static void DownloadInstallPatchFromURI(string downloadUri,string destinationPath,bool runSetupAfterDownload,bool showShutdownWindow,string destinationPath2)
 {
     string[] dblist=PrefC.GetString(PrefName.UpdateMultipleDatabases).Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries);
     if(showShutdownWindow) {
         //Even if updating multiple databases, extra shutdown signals are not needed.
         FormShutdown FormSD=new FormShutdown();
         FormSD.IsUpdate=true;
         FormSD.ShowDialog();
         if(FormSD.DialogResult==DialogResult.OK) {
             //turn off signal reception for 5 seconds so this workstation will not shut down.
             FormOpenDental.signalLastRefreshed=MiscData.GetNowDateTime().AddSeconds(5);
             Signalod sig=new Signalod();
             sig.ITypes=((int)InvalidType.ShutDownNow).ToString();
             sig.SigType=SignalType.Invalid;
             Signalods.Insert(sig);
             Computers.ClearAllHeartBeats(Environment.MachineName);//always assume success
             //SecurityLogs.MakeLogEntry(Permissions.Setup,0,"Shutdown all workstations.");//can't do this because sometimes no user.
         }
         //continue on even if user clicked cancel
         //no other workstation will be able to start up until this value is reset.
         Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,Environment.MachineName);
     }
     MiscData.LockWorkstationsForDbs(dblist);//lock workstations for other db's.
     File.Delete(destinationPath);
     WebRequest wr=WebRequest.Create(downloadUri);
     WebResponse webResp=null;
     try{
         webResp=wr.GetResponse();
     }
     catch(Exception ex){
         CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message+"\r\nUri: "+downloadUri);
         msgbox.ShowDialog();
         MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done.
         return;
     }
     int fileSize=(int)webResp.ContentLength/1024;
     FormProgress FormP=new FormProgress();
     //start the thread that will perform the download
     System.Threading.ThreadStart downloadDelegate= delegate { DownloadInstallPatchWorker(downloadUri,destinationPath,ref FormP); };
     Thread workerThread=new System.Threading.Thread(downloadDelegate);
     workerThread.Start();
     //display the progress dialog to the user:
     FormP.MaxVal=(double)fileSize/1024;
     FormP.NumberMultiplication=100;
     FormP.DisplayText="?currentVal MB of ?maxVal MB copied";
     FormP.NumberFormat="F";
     FormP.ShowDialog();
     if(FormP.DialogResult==DialogResult.Cancel) {
         workerThread.Abort();
         MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done.
         return;
     }
     //copy to second destination directory
     if(destinationPath2!=null && destinationPath2!=""){
         if(File.Exists(destinationPath2)){
             File.Delete(destinationPath2);
         }
         File.Copy(destinationPath,destinationPath2);
     }
     //copy the Setup.exe to the AtoZ folders for the other db's.
     List<string> atozNameList=MiscData.GetAtoZforDb(dblist);
     for(int i=0;i<atozNameList.Count;i++) {
         if(destinationPath==Path.Combine(atozNameList[i],"Setup.exe")) {//if they are sharing an AtoZ folder.
             continue;
         }
         if(Directory.Exists(atozNameList[i])) {
             File.Copy(destinationPath,//copy the Setup.exe that was just downloaded to this AtoZ folder
                 Path.Combine(atozNameList[i],"Setup.exe"),//to the other atozFolder
                 true);//overwrite
         }
     }
     if(!runSetupAfterDownload) {
         return;
     }
     string msg=Lan.g("FormUpdate","Download succeeded.  Setup program will now begin.  When done, restart the program on this computer, then on the other computers.");
     if(dblist.Length > 0){
         msg="Download succeeded.  Setup file probably copied to other AtoZ folders as well.  Setup program will now begin.  When done, restart the program for each database on this computer, then on the other computers.";
     }
     if(MessageBox.Show(msg,"",MessageBoxButtons.OKCancel) !=DialogResult.OK){
         //Clicking cancel gives the user a chance to avoid running the setup program,
         Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done.
         return;
     }
     try{
         Process.Start(destinationPath);
         Application.Exit();
     }
     catch{
         Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done.
         MsgBox.Show(FormP,"Could not launch setup");
     }
 }
		//private void menuItemGoToAccount_Click(object sender,EventArgs e) {
			
			//Patient pat=Patients.GetPat(FormCS.GotoPatNum);
			//OnPatientSelected(FormCS.GotoPatNum,pat.GetNameLF(),pat.Email!="",pat.ChartNumber);
			//GotoModule.GotoClaim(FormCS.GotoClaimNum);
		//}

		private void ShowSecondaryClaims() {
			DataTable secCPs=Claims.GetSecondaryClaims(ClaimsAttached);
			if(secCPs.Rows.Count==0) {
				return;
			}
			string message="Some of the payments have secondary claims: \r\n"
				+"Date | PatNum | Patient Name";
			for(int i=0;i<secCPs.Rows.Count;i++) {
				//claimProc=secondaryClaims[i];
				message+="\r\n"+PIn.Date(secCPs.Rows[i]["ProcDate"].ToString()).ToShortDateString()
					+" | "+secCPs.Rows[i]["PatNum"].ToString()
					+" | "+Patients.GetPat(PIn.Long(secCPs.Rows[i]["PatNum"].ToString())).GetNameLF();
			}
			message+="\r\n\r\nPrint this list, then use it to review and send secondary claims.";
			MsgBoxCopyPaste msgBox=new MsgBoxCopyPaste(message);
			msgBox.ShowDialog();
		}
Exemple #9
0
		private void gridSupplementalInfo_CellDoubleClick(object sender,ODGridClickEventArgs e) {
			Hx835_Info info=(Hx835_Info)gridSupplementalInfo.Rows[e.Row].Tag;
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(info.FieldName+"\r\n"+info.FieldValue);
			msgbox.Show(this);
		}
		private void butImport_Click(object sender,EventArgs e) {
			MsgBoxCopyPaste MBCP = new MsgBoxCopyPaste("Paste HL7 Lab Message Text Here.");
			MBCP.textMain.SelectAll();
			MBCP.ShowDialog();
			if(MBCP.DialogResult!=DialogResult.OK) {
				return;
			}
			List<EhrLab> listEhrLabs;
			try {
				listEhrLabs=EhrLabs.ProcessHl7Message(MBCP.textMain.Text);//Not a typical use of the msg box copy paste
				if(listEhrLabs[0].PatNum==PatCur.PatNum) {//only need to check the first lab.
					//nothing to do here. Imported lab matches the current patient.
				}
				else{//does not match current patient, redirect to import form which displays patient information and is build for importing.
					FormEhrLabOrderImport FormLOI=new FormEhrLabOrderImport();
					FormLOI.PatCur=PatCur;
					FormLOI.Hl7LabMessage=MBCP.textMain.Text;
					FormLOI.ShowDialog();
					FillGrid();
					return;
				}
				//else if(listEhrLabs[0].PatNum==0) {
				//	if(MessageBox.Show("Lab patient does not match current patient. Lab patient name is "
				//		+MBCP.textMain.Text.Split(new string[] { "\r\n" },StringSplitOptions.RemoveEmptyEntries)[1].Split('|')[5].Split('~')[0].Split('^')[1]+" "//first name
				//		+MBCP.textMain.Text.Split(new string[] { "\r\n" },StringSplitOptions.RemoveEmptyEntries)[1].Split('|')[5].Split('~')[0].Split('^')[1]+" "//last name
				//		+"\r\nWould you like to import lab for the current patient?","",MessageBoxButtons.OKCancel)!=DialogResult.OK) 
				//	{
				//		return;
				//	}
				//	//User agreed to import current lab(s) for current patient.
				//	for(int i=0;i<listEhrLabs.Count;i++) {
				//		listEhrLabs[i].PatNum=PatCur.PatNum;
				//		//TODO: Import external OIDs and PatIDs so that we can identify this patient next time.
				//	}
				//}
				//else {//Patnum is already associated with another patient.
				//	MessageBox.Show("This lab contains patient information for a different patient. Lab patient name is "
				//		+MBCP.textMain.Text.Split(new string[] { "\r\n" },StringSplitOptions.RemoveEmptyEntries)[1].Split('|')[5].Split('~')[0].Split('^')[1]+" "//first name
				//		+MBCP.textMain.Text.Split(new string[] { "\r\n" },StringSplitOptions.RemoveEmptyEntries)[1].Split('|')[5].Split('~')[0].Split('^')[1]);
				//	return;
				//}
			}
			catch (Exception Ex){
				MessageBox.Show(this,"Unable to import lab.\r\n"+Ex.Message);
				return;
			}
			for(int i=0;i<listEhrLabs.Count;i++) {
				EhrLab tempLab=null;//lab from DB if it exists.
				tempLab=EhrLabs.GetByGUID(listEhrLabs[i].PlacerOrderUniversalID,listEhrLabs[i].PlacerOrderNum);
				if(tempLab==null){
					tempLab=EhrLabs.GetByGUID(listEhrLabs[i].FillerOrderUniversalID,listEhrLabs[i].FillerOrderNum);
				}
				if(tempLab!=null) {
					//Date validation.
					//if(tempLab.ResultDateTime.CompareTo(listEhrLabs[i].ResultDateTime)<=0) {//string compare dates will return 1+ if tempLab Date is greater.
					//	MsgBox.Show(this,"This lab already exists in the database and has a more recent timestamp.");
					//	continue;
					//}
					//TODO: The code above works, but ignores more recent lab results. Although the lab order my be unchanged there may be updated lab results.
					//It would be better to check for updated results, unfortunately results have no unique identifiers.
				}
				if(Security.CurUser.ProvNum!=0 && Providers.GetProv(Security.CurUser.ProvNum).EhrKey!="") {//The user who is currently logged in is a provider and has a valid EHR key.
					ListEhrLabs[i].IsCpoe=true;
				}
				listEhrLabs[i]=EhrLabs.SaveToDB(listEhrLabs[i]);//SAVE
				for(int j=0;j<listEhrLabs[i].ListEhrLabResults.Count;j++) {//EHR TRIGGER
					if(CDSPermissions.GetForUser(Security.CurUser.UserNum).ShowCDS && CDSPermissions.GetForUser(Security.CurUser.UserNum).LabTestCDS) {
						FormCDSIntervention FormCDSI=new FormCDSIntervention();
						FormCDSI.ListCDSI=EhrTriggers.TriggerMatch(listEhrLabs[i].ListEhrLabResults[j],PatCur);
						FormCDSI.ShowIfRequired(false);
					}
				}
			}
			FillGrid();
		}
Exemple #11
0
		private void butDirectMessage_Click(object sender,EventArgs e) {
			//this will not be available if already sent.
			if(emailPreview.FromAddress=="" || emailPreview.ToAddress=="") {
				MessageBox.Show("Addresses not allowed to be blank.");
				return;
			}
			EmailAddress emailAddressFrom=emailPreview.GetEmailAddress();
			if(emailPreview.FromAddress!=emailAddressFrom.EmailUsername) {
				//Without this block, encryption would fail with an obscure error message, because the from address would not match the digital signature of the sender.
				MessageBox.Show(Lan.g(this,"From address must match email address username in email setup.")+"\r\n"+Lan.g(this,"From address must be exactly")+" "+emailAddressFrom.EmailUsername);
				return;
			}
			if(emailAddressFrom.SMTPserver=="") {
				MsgBox.Show(this,"The email address in email setup must have an SMTP server.");
				return;
			}
			if(emailPreview.ToAddress.Contains(",")) {
				MsgBox.Show(this,"Multiple recipient addresses not allowed for direct messaging.");
				return;
			}
			Cursor=Cursors.WaitCursor;
			if(!EmailMessages.IsAddressTrusted(emailPreview.ToAddress)) {//Not trusted yet.
				EmailMessages.TryAddTrustDirect(emailPreview.ToAddress);
				if(!EmailMessages.IsAddressTrusted(emailPreview.ToAddress)) {
					Cursor=Cursors.Default;
					MsgBox.Show(this,"Failed to trust recipient because a valid certificate could not be located.");
					return;
				}
			}
			SaveMsg();
			try {
				string strErrors=EmailMessages.SendEmailDirect(_emailMessage,emailAddressFrom);
				if(strErrors!="") {
					Cursor=Cursors.Default;
					MessageBox.Show(strErrors);
					return;
				}
				else {
					_emailMessage.SentOrReceived=EmailSentOrReceived.SentDirect;
					EmailMessages.Update(_emailMessage);
					MsgBox.Show(this,"Sent");
				}
			}
			catch(Exception ex) {
				Cursor=Cursors.Default;
				MsgBoxCopyPaste msgBox=new MsgBoxCopyPaste(ex.Message);
				msgBox.ShowDialog();
				return;
			}
			Cursor=Cursors.Default;
			DialogResult=DialogResult.OK;
		}
		private void butShow_Click(object sender,EventArgs e) {
			if(comboProv.SelectedIndex==-1) {
				MessageBox.Show("Please select a provider first.");
				return;
			}
			try {
				DateTime.Parse(textDateStart.Text);
				DateTime.Parse(textDateEnd.Text);
			}
			catch {
				MessageBox.Show("Invalid dates.");
				return;
			}
			if(listQ==null) {
				MessageBox.Show("Click Refresh first.");
				return;
			}
			MsgBoxCopyPaste MsgBoxCP = new MsgBoxCopyPaste(GeneratePQRS_xml());
			MsgBoxCP.ShowDialog();
		}
Exemple #13
0
		private void butSend_Click(object sender, System.EventArgs e) {
			if(gridBill.SelectedIndices.Length==0){
				MessageBox.Show(Lan.g(this,"Please select items first."));
				return;
			}
			labelPrinted.Text=Lan.g(this,"Printed=")+"0";
			labelEmailed.Text=Lan.g(this,"E-mailed=")+"0";
			labelSentElect.Text=Lan.g(this,"SentElect=")+"0";
			if(!MsgBox.Show(this,true,"Please be prepared to wait up to ten minutes while all the bills get processed.\r\nOnce complete, the pdf print preview will be launched in Adobe Reader.  You will print from that program.  Continue?")){
				return;
			}
			Cursor=Cursors.WaitCursor;
			isPrinting=true;
			FormRpStatement FormST=new FormRpStatement();
			Statement stmt;
			Random rnd;
			string fileName;
			string filePathAndName;
			string attachPath;
			EmailMessage message;
			EmailAttach attach;
			EmailAddress emailAddress;
			Family fam;
			Patient pat;
			Clinic clinic;
			string patFolder;
			int skipped=0;
			int skippedElect=0;
			int emailed=0;
			int printed=0;
			int sentelect=0;
			//FormEmailMessageEdit FormEME=new FormEmailMessageEdit();
			//if(ImageStore.UpdatePatient == null){
			//	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
			//}
			//OpenDental.Imaging.ImageStoreBase imageStore;
			//Concat all the pdf's together to create one print job.
			//Also, if a statement is to be emailed, it does that here and does not attach it to the print job.
			//If something fails badly, it's no big deal, because we can click the radio button to see "sent" bills, and unsend them from there.
			PdfDocument outputDocument=new PdfDocument();
			PdfDocument inputDocument;
			PdfPage page;
			string savedPdfPath;
			PrintDocument pd=null;
			XmlWriterSettings xmlSettings=new XmlWriterSettings();
			xmlSettings.OmitXmlDeclaration=true;
			xmlSettings.Encoding=Encoding.UTF8;
			xmlSettings.Indent=true;
			xmlSettings.IndentChars="   ";
			StringBuilder strBuildElect=new StringBuilder();
			XmlWriter writerElect=XmlWriter.Create(strBuildElect,xmlSettings);
			if(PrefC.GetString(PrefName.BillingUseElectronic)=="1") {
				OpenDental.Bridges.EHG_statements.GeneratePracticeInfo(writerElect);
			} 
			else if(PrefC.GetString(PrefName.BillingUseElectronic)=="2") {
				OpenDental.Bridges.POS_statements.GeneratePracticeInfo(writerElect);
			} 
			else if(PrefC.GetString(PrefName.BillingUseElectronic)=="3") {
				OpenDental.Bridges.ClaimX_Statements.GeneratePracticeInfo(writerElect);
			}
			DataSet dataSet;
			List<long> stateNumsElect=new List<long>();
			//TODO: Query the database to get an updated list of unsent bills and compare them to the local list to make sure that we do not resend statements that have already been sent by another user.
			for(int i=0;i<gridBill.SelectedIndices.Length;i++){
				stmt=Statements.CreateObject(PIn.Long(table.Rows[gridBill.SelectedIndices[i]]["StatementNum"].ToString()));
				fam=Patients.GetFamily(stmt.PatNum);
				pat=fam.GetPatient(stmt.PatNum);
				patFolder=ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath());
				dataSet=AccountModules.GetStatementDataSet(stmt);
				emailAddress=EmailAddresses.GetByClinic(pat.ClinicNum);
				if(stmt.Mode_==StatementMode.Email){
					if(emailAddress.SMTPserver==""){
						MsgBox.Show(this,"You need to enter an SMTP server name in e-mail setup before you can send e-mail.");
						Cursor=Cursors.Default;
						isPrinting=false;
						//FillGrid();//automatic
						return;
					}
					if(pat.Email==""){
						skipped++;
						continue;
					}
				}
				stmt.IsSent=true;
				stmt.DateSent=DateTimeOD.Today;
				if(PrefC.GetBool(PrefName.StatementsUseSheets)){
					FormST.CreateStatementPdfSheets(stmt,pat,fam,dataSet);
				}
				else{
					FormST.CreateStatementPdfClassic(stmt,pat,fam,dataSet);
				}
				if(stmt.DocNum==0){
					MsgBox.Show(this,"Failed to save PDF.  In Setup, DataPaths, please make sure the top radio button is checked.");
					Cursor=Cursors.Default;
					isPrinting=false;
					return;
				}
				//imageStore = OpenDental.Imaging.ImageStore.GetImageStore(pat);
				savedPdfPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),patFolder);
				if(stmt.Mode_==StatementMode.InPerson || stmt.Mode_==StatementMode.Mail){
					if(pd==null){
						pd=new PrintDocument();
					}
					inputDocument=PdfReader.Open(savedPdfPath,PdfDocumentOpenMode.Import);
					for(int idx=0;idx<inputDocument.PageCount;idx++){
						page=inputDocument.Pages[idx];
						outputDocument.AddPage(page);
					}
					printed++;
					labelPrinted.Text=Lan.g(this,"Printed=")+printed.ToString();
					Application.DoEvents();
					Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
				}
				if(stmt.Mode_==StatementMode.Email){
					attachPath=EmailAttaches.GetAttachPath();
					rnd=new Random();
					fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
					filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
					File.Copy(savedPdfPath,filePathAndName);
					//Process.Start(filePathAndName);
					message=Statements.GetEmailMessageForStatement(stmt,pat);
					attach=new EmailAttach();
					attach.DisplayedFileName="Statement.pdf";
					attach.ActualFileName=fileName;
					message.Attachments.Add(attach);
					try{
						EmailMessages.SendEmailUnsecure(message,emailAddress);
						message.SentOrReceived=EmailSentOrReceived.Sent;
						message.MsgDateTime=DateTime.Now;
						EmailMessages.Insert(message);
						emailed++;
						labelEmailed.Text=Lan.g(this,"E-mailed=")+emailed.ToString();
						Application.DoEvents();
					}
					catch{
						//Cursor=Cursors.Default;
						//MessageBox.Show(ex.Message);
						//return;
						skipped++;
						continue;
					}
					Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
				}
				if(stmt.Mode_==StatementMode.Electronic) {
					Patient guar=fam.ListPats[0];
					if(guar.Address.Trim()=="" || guar.City.Trim()=="" || guar.State.Trim()=="" || guar.Zip.Trim()=="") {
						skippedElect++;
						continue;
					}
					bool statementWritten=true;
					if(PrefC.GetString(PrefName.BillingUseElectronic)=="1") {
						try {
							OpenDental.Bridges.EHG_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
						}
						catch(Exception ex){
							MessageBox.Show(Lan.g(this,"Error sending statement")+": "+Environment.NewLine+ex.ToString());
							statementWritten=false;
						}
					}
					else if(PrefC.GetString(PrefName.BillingUseElectronic)=="2") {
						OpenDental.Bridges.POS_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
					}
					else if(PrefC.GetString(PrefName.BillingUseElectronic)=="3") {
						OpenDental.Bridges.ClaimX_Statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
					}
					if(statementWritten) {
						stateNumsElect.Add(stmt.StatementNum);
						sentelect++;
						labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
						Application.DoEvents();
						//do this later:
						//Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
					}
				}
			}
			//now print-------------------------------------------------------------------------------------
			if(pd!=null){
				string tempFileOutputDocument=PrefL.GetRandomTempFile(".pdf");
				outputDocument.Save(tempFileOutputDocument);
				try{
					Process.Start(tempFileOutputDocument);
				}
				catch(Exception ex){
					MessageBox.Show(Lan.g(this,"Error: Please make sure Adobe Reader is installed.")+ex.Message);
				}
				//}
			}
			//finish up elect and send if needed------------------------------------------------------------
			if(sentelect>0) {
				if(PrefC.GetString(PrefName.BillingUseElectronic)=="1") {
					OpenDental.Bridges.EHG_statements.GenerateWrapUp(writerElect);
					writerElect.Close();
					try {
						//OpenDental.Bridges.Tesia_statements.Send(strBuildElect.ToString());
						OpenDental.Bridges.EHG_statements.Send(strBuildElect.ToString());
						//CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(strBuildElect.ToString());
						//msgbox.ShowDialog();
						//loop through all statements and mark sent
						for(int i=0;i<stateNumsElect.Count;i++) {
							Statements.MarkSent(stateNumsElect[i],DateTimeOD.Today);
						}
					} 
					catch(Exception ex) {
						string errorMsg=ex.Message;
						if(ex.Message.Contains("(404) Not Found")) {
							//The full error is "The remote server returned an error: (404) Not Found."  We convert the message into a more user friendly message.
							errorMsg=Lan.g(this,"The connection to the server could not be established or was lost, or the upload timed out.  "
								+"Ensure your internet connection is working and that your firewall is not blocking this application.  "
								+"If the upload timed out after 10 minutes, try sending 25 statements or less in each batch to reduce upload time.");
						}
						MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(errorMsg);
						msgbox.ShowDialog();
						sentelect=0;
						labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
					}
				}
				if(PrefC.GetString(PrefName.BillingUseElectronic)=="2") {
					OpenDental.Bridges.POS_statements.GenerateWrapUp(writerElect);
					writerElect.Close();
					SaveFileDialog dlg=new SaveFileDialog();
					dlg.FileName="Statements.xml";
					if(dlg.ShowDialog()!=DialogResult.OK) {
						sentelect=0;
						labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
					}
					File.WriteAllText(dlg.FileName,strBuildElect.ToString());
					for(int i=0;i<stateNumsElect.Count;i++) {
						Statements.MarkSent(stateNumsElect[i],DateTimeOD.Today);
					}
				}
				if(PrefC.GetString(PrefName.BillingUseElectronic)=="3") {
					OpenDental.Bridges.ClaimX_Statements.GenerateWrapUp(writerElect);
					writerElect.Close();
					SaveFileDialog dlg=new SaveFileDialog();
					dlg.InitialDirectory=@"C:\StatementX\";//Clint from ExtraDent requested this default path.
					if(!Directory.Exists(dlg.InitialDirectory)) {
						try {
							Directory.CreateDirectory(dlg.InitialDirectory);
						} 
						catch {}
					}
					dlg.FileName="Statements.xml";
					if(dlg.ShowDialog()!=DialogResult.OK) {
						sentelect=0;
						labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
					}
					File.WriteAllText(dlg.FileName,strBuildElect.ToString());
					for(int i=0;i<stateNumsElect.Count;i++) {
						Statements.MarkSent(stateNumsElect[i],DateTimeOD.Today);
					}
				}
			}
			else {
				writerElect.Close();
			}
			string msg="";
			if(skipped>0){
				msg+=Lan.g(this,"Skipped due to missing or bad email address: ")+skipped.ToString()+"\r\n";
			}
			if(skippedElect>0) {
				msg+=Lan.g(this,"Skipped due to missing or bad mailing address: ")+skippedElect.ToString()+"\r\n";
			}
			msg+=Lan.g(this,"Printed: ")+printed.ToString()+"\r\n"
				+Lan.g(this,"E-mailed: ")+emailed.ToString()+"\r\n"
				+Lan.g(this,"SentElect: ")+sentelect.ToString();
			MessageBox.Show(msg);
			Cursor=Cursors.Default;
			isPrinting=false;
			FillGrid();//not automatic
		}
Exemple #14
0
		/// <summary>destinationPath includes filename (Setup.exe).  destinationPath2 will create a second copy at the specified path/filename, or it will be skipped if null or empty.</summary>
		public static void DownloadInstallPatchFromURI(string downloadUri,string destinationPath,bool runSetupAfterDownload,bool showShutdownWindow,string destinationPath2){
			string[] dblist=PrefC.GetString(PrefName.UpdateMultipleDatabases).Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries);
			if(showShutdownWindow) {
				//Even if updating multiple databases, extra shutdown signals are not needed.
				FormShutdown FormSD=new FormShutdown();
				FormSD.IsUpdate=true;
				FormSD.ShowDialog();
				if(FormSD.DialogResult==DialogResult.OK) {
					//turn off signal reception for 5 seconds so this workstation will not shut down.
					FormOpenDental.signalLastRefreshed=MiscData.GetNowDateTime().AddSeconds(5);
					Signalod sig=new Signalod();
					sig.ITypes=((int)InvalidType.ShutDownNow).ToString();
					sig.SigType=SignalType.Invalid;
					Signalods.Insert(sig);
					Computers.ClearAllHeartBeats(Environment.MachineName);//always assume success
					//SecurityLogs.MakeLogEntry(Permissions.Setup,0,"Shutdown all workstations.");//can't do this because sometimes no user.
				}
				//continue on even if user clicked cancel
				//no other workstation will be able to start up until this value is reset.
				Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,Environment.MachineName);
			}
			MiscData.LockWorkstationsForDbs(dblist);//lock workstations for other db's.
			File.Delete(destinationPath);
			WebRequest wr=WebRequest.Create(downloadUri);
			WebResponse webResp=null;
			try{
				webResp=wr.GetResponse();
			}
			catch(Exception ex){
				CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message+"\r\nUri: "+downloadUri);
				msgbox.ShowDialog();
				MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done.
				return;
			}
			int fileSize=(int)webResp.ContentLength/1024;
			FormProgress FormP=new FormProgress();
			//start the thread that will perform the download
			System.Threading.ThreadStart downloadDelegate= delegate { DownloadInstallPatchWorker(downloadUri,destinationPath,ref FormP); };
			Thread workerThread=new System.Threading.Thread(downloadDelegate);
			workerThread.Start();
			//display the progress dialog to the user:
			FormP.MaxVal=(double)fileSize/1024;
			FormP.NumberMultiplication=100;
			FormP.DisplayText="?currentVal MB of ?maxVal MB copied";
			FormP.NumberFormat="F";
			FormP.ShowDialog();
			if(FormP.DialogResult==DialogResult.Cancel) {
				workerThread.Abort();
				MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done.
				return;
			}
			//copy to second destination directory
			if(destinationPath2!=null && destinationPath2!=""){
				if(File.Exists(destinationPath2)){
					File.Delete(destinationPath2);
				}
				File.Copy(destinationPath,destinationPath2);
			}
			//copy the Setup.exe to the AtoZ folders for the other db's.
			List<string> atozNameList=MiscData.GetAtoZforDb(dblist);
			for(int i=0;i<atozNameList.Count;i++) {
				if(destinationPath==Path.Combine(atozNameList[i],"Setup.exe")) {//if they are sharing an AtoZ folder.
					continue;
				}
				if(Directory.Exists(atozNameList[i])) {
					File.Copy(destinationPath,//copy the Setup.exe that was just downloaded to this AtoZ folder
						Path.Combine(atozNameList[i],"Setup.exe"),//to the other atozFolder
						true);//overwrite
				}
			}
			if(!runSetupAfterDownload) {
				return;
			}
			string msg=Lan.g("FormUpdate","Download succeeded.  Setup program will now begin.  When done, restart the program on this computer, then on the other computers.");
			if(dblist.Length > 0){
				msg="Download succeeded.  Setup file probably copied to other AtoZ folders as well.  Setup program will now begin.  When done, restart the program for each database on this computer, then on the other computers.";
			}
			if(MessageBox.Show(msg,"",MessageBoxButtons.OKCancel) !=DialogResult.OK){
				//Clicking cancel gives the user a chance to avoid running the setup program,
				Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done.
				return;
			}
			#region Stop OpenDent Services
			//If the update has been initiated from the designated update server then try and stop all "OpenDent..." services.
			//They will be automatically restarted once Open Dental has successfully upgraded.
			if(PrefC.GetString(PrefName.WebServiceServerName)!="" && ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName))) {
				List<ServiceController> listServices=ODEnvironment.GetAllOpenDentServices();
				StringBuilder strBuilder=new StringBuilder();
				if(listServices.Count>0) {
					FormAlertSimple FormAS=new FormAlertSimple(Lan.g("FormUpdate","Stopping services..."));
					FormAS.Show();
					Application.DoEvents();//Allows the form to show up on top of FormUpdate right away.
					//Loop through all Open Dental services and stop them if they have not stopped or are not pending a stop so that their binaries can be updated.
					for(int i=0;i<listServices.Count;i++) {
						if(listServices[i].Status==ServiceControllerStatus.Stopped || listServices[i].Status==ServiceControllerStatus.StopPending) {
							continue;//Already stopped.  Calling Stop again will guarantee an exception is thrown.  Do not try calling Stop on a stopped service.
						}
						try {
							listServices[i].Stop();
							listServices[i].WaitForStatus(ServiceControllerStatus.Stopped,new TimeSpan(0,0,7));
						}
						catch {
							//An InvalidOperationException will get thrown if the service could not stop.  E.g. the user is not running Open Dental as an administrator.
							strBuilder.AppendLine(listServices[i].DisplayName);
						}
					}
					FormAS.Close();
					//Notify the user to go manually stop the services that could not automatically stop.
					if(strBuilder.ToString()!="") {
						MsgBoxCopyPaste msgBCP=new MsgBoxCopyPaste(Lan.g("FormUpdate","The following services could not be stopped.  You need to manually stop them before continuing.")
						+"\r\n"+strBuilder.ToString());
						msgBCP.ShowDialog();
					}
				}
			}
			#endregion
			try {
				Process.Start(destinationPath);
				Application.Exit();
			}
			catch{
				Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done.
				MsgBox.Show(FormP,"Could not launch setup");
			}
		}
Exemple #15
0
		private void butExport_Click(object sender,EventArgs e) {
			string strCcdValidationErrors=EhrCCD.ValidateSettings();
			if(strCcdValidationErrors!="") {//Do not even try to export if global settings are invalid.
				MessageBox.Show(strCcdValidationErrors);//We do not want to use translations here, because the text is dynamic. The errors are generated in the business layer, and Lan.g() is not available there.
				return;
			}
			FolderBrowserDialog dlg=new FolderBrowserDialog();
			DialogResult result=dlg.ShowDialog();
			if(result!=DialogResult.OK) {
				return;
			}
			DateTime dateNow=DateTime.Now;
			string folderPath=ODFileUtils.CombinePaths(dlg.SelectedPath,(dateNow.Year+"_"+dateNow.Month+"_"+dateNow.Day));
			if(Directory.Exists(folderPath)) {
				int loopCount=1;
				while(Directory.Exists(folderPath+"_"+loopCount)) {
					loopCount++;
				}
				folderPath=folderPath+"_"+loopCount;
			}
			try {
				Directory.CreateDirectory(folderPath);
			}
			catch {
				MessageBox.Show("Error, Could not create folder");
				return;
			}
			this.Cursor=Cursors.WaitCursor;
			Patient patCur;
			string fileName;
			int numSkipped=0;  //Number of patients skipped. Set to -1 if only one patient was selected and had CcdValidationErrors.
			string patientsSkipped="";  //Names of the patients that were skipped, so we can tell the user which ones didn't export correctly.
			for(int i=0;i<gridMain.SelectedIndices.Length;i++) {
				patCur=Patients.GetPat((long)gridMain.Rows[gridMain.SelectedIndices[i]].Tag);//Cannot use GetLim because more information is needed in the CCD message generation below.
				strCcdValidationErrors=EhrCCD.ValidatePatient(patCur);
				if(strCcdValidationErrors!="") {
					if(gridMain.SelectedIndices.Length==1) {
						numSkipped=-1; //Set to -1 so we know below to not show the "exported" message.
						MessageBox.Show(Lan.g(this,"Patient not exported due to the following errors")+":\r\n"+strCcdValidationErrors);
						continue;
					}
					//If one patient is missing the required information for export, then simply skip the patient. We do not want to popup a message,
					//because it would be hard to get through the export if many patients were missing required information.
					numSkipped++;
					patientsSkipped+="\r\n"+patCur.LName+", "+patCur.FName;
					continue;
				}
				fileName="";
				string lName=patCur.LName;
				for(int j=0;j<lName.Length;j++) {  //Strip all non-letters from FName
					if(Char.IsLetter(lName,j)) {
						fileName+=lName.Substring(j,1);
					}
				}
				fileName+="_";
				string fName=patCur.FName;
				for(int k=0;k<fName.Length;k++) {  //Strip all non-letters from LName
					if(Char.IsLetter(fName,k)) {
						fileName+=fName.Substring(k,1);
					}
				}
				fileName+="_"+patCur.PatNum;  //LName_FName_PatNum
				string ccd=EhrCCD.GeneratePatientExport(patCur);
				try {
					File.WriteAllText(ODFileUtils.CombinePaths(folderPath,fileName+".xml"),ccd);
				}
				catch {
					MessageBox.Show("Error, Could not create xml file");
					this.Cursor=Cursors.Default;
					return;
				}
			}
			if(numSkipped==-1) {	//Will be -1 if only one patient was selected, and it did not export correctly.
				this.Cursor=Cursors.Default;
				return;//Don't display "Exported" to the user because the CCD was not exported.
			}
			try {
				File.WriteAllText(ODFileUtils.CombinePaths(folderPath,"CCD.xsl"),FormEHR.GetEhrResource("CCD"));
			}
			catch {
				MessageBox.Show("Error, Could not create stylesheet file");
			}
			string strMsg=Lan.g(this,"Exported");
			if(numSkipped>0) {
				strMsg+=". "+Lan.g(this,"Patients skipped due to missing information")+": "+numSkipped+patientsSkipped;
				MsgBoxCopyPaste msgCP=new MsgBoxCopyPaste(strMsg);
				msgCP.Show();
			}
			else {
				MessageBox.Show(strMsg);
			}
			this.Cursor=Cursors.Default;
		}
Exemple #16
0
 ///<summary>Called every time timerSignals_Tick fires.  Usually about every 5-10 seconds.</summary>
 public void ProcessSignals()
 {
     try {
         List<Signalod> sigList=Signalods.RefreshTimed(signalLastRefreshed);//this also attaches all elements to their sigs
         if(sigList.Count==0) {
             return;
         }
         if(Security.CurUser==null) {
             return;
         }
         //look for shutdown signal
         for(int i=0;i<sigList.Count;i++) {
             if(sigList[i].ITypes==((int)InvalidType.ShutDownNow).ToString()) {
                 timerSignals.Enabled=false;//quit receiving signals.
                 //close the webcam if present so that it can be updated too.
                 if(PrefC.GetBool(PrefName.DockPhonePanelShow)) {
                     Process[] processes=Process.GetProcessesByName("WebCamOD");
                     for(int p=0;p<processes.Length;p++) {
                         processes[p].Kill();
                     }
                 }
                 //start the thread that will kill the application
                 Thread killThread=new Thread(new ThreadStart(KillThread));
                 killThread.Start();
                 string msg="";
                 if(Process.GetCurrentProcess().ProcessName=="OpenDental") {
                     msg+="All copies of Open Dental ";
                 }
                 else {
                     msg+=Process.GetCurrentProcess().ProcessName+" ";
                 }
                 msg+=Lan.g(this,"will shut down in 15 seconds.  Quickly click OK on any open windows with unsaved data.");
                 MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(msg);
                 msgbox.Size=new Size(300,300);
                 msgbox.TopMost=true;
                 msgbox.ShowDialog();
                 return;
             }
         }
         if(sigList[sigList.Count-1].AckTime.Year>1880) {
             signalLastRefreshed=sigList[sigList.Count-1].AckTime;
         }
         else {
             signalLastRefreshed=sigList[sigList.Count-1].SigDateTime;
         }
         if(ContrAppt2.Visible && Signalods.ApptNeedsRefresh(sigList,AppointmentL.DateSelected.Date)) {
             ContrAppt2.RefreshPeriod();
         }
         bool areAnySignalsTasks=false;
         for(int i=0;i<sigList.Count;i++) {
             if(sigList[i].ITypes==((int)InvalidType.Task).ToString()
                 || sigList[i].ITypes==((int)InvalidType.TaskPopup).ToString()) {
                 areAnySignalsTasks=true;
             }
         }
         List<Task> tasksPopup=Signalods.GetNewTaskPopupsThisUser(sigList,Security.CurUser.UserNum);
         if(tasksPopup.Count>0) {
             for(int i=0;i<tasksPopup.Count;i++) {
                 //Even though this is triggered to popup, if this is my own task, then do not popup.
                 List<TaskNote> notesForThisTask=TaskNotes.GetForTask(tasksPopup[i].TaskNum);
                 if(notesForThisTask.Count==0) {//'sender' is the usernum on the task
                     if(tasksPopup[i].UserNum==Security.CurUser.UserNum) {
                         continue;
                     }
                 }
                 else {//'sender' is the user on the last added note
                     if(notesForThisTask[notesForThisTask.Count-1].UserNum==Security.CurUser.UserNum) {
                         continue;
                     }
                 }
                 if(tasksPopup[i].TaskListNum!=Security.CurUser.TaskListInBox//if not my inbox
                     && userControlTasks1.PopupsAreBlocked)//and popups blocked
                 {
                     continue;//no sound or popup
                     //in other words, popups will always show for my inbox even if popups blocked.
                 }
                 System.Media.SoundPlayer soundplay=new SoundPlayer(Properties.Resources.notify);
                 soundplay.Play();
                 this.BringToFront();//don't know if this is doing anything.
                 FormTaskEdit FormT=new FormTaskEdit(tasksPopup[i],tasksPopup[i].Copy());
                 FormT.IsPopup=true;
                 FormT.Closing+=new CancelEventHandler(TaskGoToEvent);
                 FormT.Show();//non-modal
             }
         }
         if(areAnySignalsTasks || tasksPopup.Count>0) {
             //if user has the Task dialog open, we can't easily tell it to refresh,
             //So that dialog is responsible for auto refreshing every minute on a timer.
             //Improve this.
             if(userControlTasks1.Visible) {
                 userControlTasks1.RefreshTasks();
             }
         }
         List<int> itypes=Signalods.GetInvalidTypes(sigList);
         InvalidType[] itypeArray=new InvalidType[itypes.Count];
         for(int i=0;i<itypeArray.Length;i++) {
             itypeArray[i]=(InvalidType)itypes[i];
         }
         //InvalidTypes invalidTypes=Signalods.GetInvalidTypes(sigList);
         if(itypes.Count>0) {//invalidTypes!=0){
             RefreshLocalData(itypeArray);
         }
         List<Signalod> sigListButs=Signalods.GetButtonSigs(sigList);
         ContrManage2.LogMsgs(sigListButs);
         FillSignalButtons(sigListButs);
         //Need to add a test to this: do not play messages that are over 2 minutes old.
         Thread newThread=new Thread(new ParameterizedThreadStart(PlaySounds));
         newThread.Start(sigListButs);
     }
     catch {
         signalLastRefreshed=DateTime.Now;
     }
 }
Exemple #17
0
		private void SyncAll(List<CentralConnection> listConns) {
			Cursor=Cursors.WaitCursor;
			//Get CEMT users, groups, and associated permissions
			List<CentralUserData> listCentralUserData=new List<CentralUserData>();
			for(int i=0;i<_listCEMTUsers.Count;i++) {
				bool hasUserGroup=false;
				UserGroup userGroupCEMT=UserGroups.GetGroup(_listCEMTUsers[i].UserGroupNum);//All users have a usergroup.
				for(int j=0;j<listCentralUserData.Count;j++) {
					if(listCentralUserData[j].UserGroup.Description==userGroupCEMT.Description) {
						listCentralUserData[j].ListUsers.Add(_listCEMTUsers[i]);
						hasUserGroup=true;
						break;
					}
				}
				if(!hasUserGroup) {//Add user group and permissions if they aren't already included.
					List<GroupPermission> listGroupPerms=GroupPermissions.GetPerms(userGroupCEMT.UserGroupNum);
					//New struct element with a one member list of the only person found so far in that usergroup, along with the permissions.
					listCentralUserData.Add(new CentralUserData(userGroupCEMT,new List<Userod>() { _listCEMTUsers[i] },listGroupPerms));
				}
			}
			string failedConns="";
			string nameConflicts="";
			for(int i=0;i<listConns.Count;i++) {
				if(!CentralConnectionHelper.UpdateCentralConnection(listConns[i])) {
					string serverName="";
					if(listConns[i].ServiceURI!="") {
						serverName=listConns[i].ServiceURI;
					}
					else {
						serverName=listConns[i].ServerName+", "+listConns[i].DatabaseName;
					}
					failedConns+=serverName+"\r\n";
					continue;
				}
				Prefs.RefreshCache();
				if(Prefs.UpdateString(PrefName.SecurityLockDate,POut.Date(PIn.Date(textDate.Text),false))
					| Prefs.UpdateInt(PrefName.SecurityLockDays,PIn.Int(textDays.Text))
					| Prefs.UpdateBool(PrefName.SecurityLockIncludesAdmin,checkAdmin.Checked)  
					| Prefs.UpdateBool(PrefName.CentralManagerSecurityLock,checkEnable.Checked)) 
				{
					Signalods.SetInvalid(InvalidType.Prefs);//Causes cache refresh on workstations
				}
				//We're connected, cache has been refreshed
				//Get remote users, usergroups, and associated permissions
				List<Userod> listRemoteUsers=UserodC.GetListt();
				List<UserGroup> listRemoteUserGroups=UserGroups.GetList();
				#region Detect Conflicts
				//User conflicts
				bool nameConflict=false;
				for(int j=0;j<_listCEMTUsers.Count;j++) {
					for(int k=0;k<listRemoteUsers.Count;k++) {
						if(listRemoteUsers[k].UserName==_listCEMTUsers[j].UserName && listRemoteUsers[k].UserNumCEMT==0) {//User doesn't belong to CEMT
							string serverName="";
							if(listConns[i].ServiceURI!="") {
								serverName=listConns[i].ServiceURI;
							}
							else {
								serverName=listConns[i].ServerName+", "+listConns[i].DatabaseName;
							}
							nameConflicts+=listRemoteUsers[j].UserName+" already exists in "+serverName+"\r\n";
							nameConflict=true;
							break;
						}
					}
				}
				if(nameConflict) {
					continue;//Skip on to the next connection.
				}
				#endregion
				List<UserGroup> listRemoteCEMTUserGroups=UserGroups.GetCEMTGroups();
				List<UserGroup> listCEMTUserGroups=new List<UserGroup>();
				for(int j=0;j<listCentralUserData.Count;j++) {
					listCEMTUserGroups.Add(listCentralUserData[j].UserGroup.Copy());
				}
				//SyncUserGroups returns the list of UserGroups for deletion so it can be used after syncing Users and GroupPermissions.
				List<UserGroup> listUserGroupsForDeletion=CentralUserGroups.Sync(listCEMTUserGroups,listRemoteCEMTUserGroups);
				UserGroups.RefreshCache();
				listRemoteCEMTUserGroups=UserGroups.GetCEMTGroups();
				for(int j=0;j<listCentralUserData.Count;j++) {
					List<GroupPermission> listGroupPerms=new List<GroupPermission>();
					for(int k=0;k<listRemoteCEMTUserGroups.Count;k++) {
						if(listCentralUserData[j].UserGroup.UserGroupNumCEMT==listRemoteCEMTUserGroups[k].UserGroupNumCEMT) {
							for(int l=0;l<listCentralUserData[j].ListUsers.Count;l++) {
								listCentralUserData[j].ListUsers[l].UserGroupNum=listRemoteCEMTUserGroups[k].UserGroupNum;
							}
							for(int l=0;l<listCentralUserData[j].ListGroupPermissions.Count;l++) {
								listCentralUserData[j].ListGroupPermissions[l].UserGroupNum=listRemoteCEMTUserGroups[k].UserGroupNum;
							}
							listGroupPerms=GroupPermissions.GetPerms(listRemoteCEMTUserGroups[k].UserGroupNum);
						}
					}
					CentralUserods.Sync(listCentralUserData[j].ListUsers,listRemoteUsers);
					CentralGroupPermissions.Sync(listCentralUserData[j].ListGroupPermissions,listGroupPerms);
				}
				for(int j=0;j<listUserGroupsForDeletion.Count;j++) {
					UserGroups.Delete(listUserGroupsForDeletion[j]);
				}
			}
			string errorText="";
			if(failedConns=="" && nameConflicts=="") {
				errorText+="Done";
			}
			if(failedConns!="") {
				errorText="Failed Connections:\r\n"+failedConns+"Please try these connections again.\r\n";
			}
			if(nameConflicts!="") {
				errorText+="Name Conflicts:\r\n"+nameConflicts+"Please rename users and try again.\r\n";
			}
			Cursor=Cursors.Default;
			MsgBoxCopyPaste MsgBoxCopyPaste=new MsgBoxCopyPaste(errorText);
			MsgBoxCopyPaste.ShowDialog();
		}
Exemple #18
0
 private void butSend_Click(object sender, System.EventArgs e)
 {
     if(gridBill.SelectedIndices.Length==0){
         MessageBox.Show(Lan.g(this,"Please select items first."));
         return;
     }
     labelPrinted.Text=Lan.g(this,"Printed=")+"0";
     labelEmailed.Text=Lan.g(this,"E-mailed=")+"0";
     labelSentElect.Text=Lan.g(this,"SentElect=")+"0";
     if(!MsgBox.Show(this,true,"Please be prepared to wait up to ten minutes while all the bills get processed.\r\nOnce complete, the pdf print preview will be launched in Adobe Reader.  You will print from that program.  Continue?")){
         return;
     }
     Cursor=Cursors.WaitCursor;
     isPrinting=true;
     FormRpStatement FormST=new FormRpStatement();
     Statement stmt;
     Random rnd;
     string fileName;
     string filePathAndName;
     string attachPath;
     EmailMessage message;
     EmailAttach attach;
     Family fam;
     Patient pat;
     string patFolder;
     int skipped=0;
     int emailed=0;
     int printed=0;
     int sentelect=0;
     //FormEmailMessageEdit FormEME=new FormEmailMessageEdit();
     //if(ImageStore.UpdatePatient == null){
     //	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
     //}
     //OpenDental.Imaging.ImageStoreBase imageStore;
     //Concat all the pdf's together to create one print job.
     //Also, if a statement is to be emailed, it does that here and does not attach it to the print job.
     //If something fails badly, it's no big deal, because we can click the radio button to see "sent" bills, and unsend them from there.
       PdfDocument outputDocument=new PdfDocument();
     PdfDocument inputDocument;
     PdfPage page;
     string savedPdfPath;
     PrintDocument pd=null;
     XmlWriterSettings xmlSettings=new XmlWriterSettings();
     xmlSettings.OmitXmlDeclaration=true;
     xmlSettings.Encoding=Encoding.UTF8;
     xmlSettings.Indent=true;
     xmlSettings.IndentChars="   ";
     StringBuilder strBuildElect=new StringBuilder();
     XmlWriter writerElect=XmlWriter.Create(strBuildElect,xmlSettings);
     //OpenDental.Bridges.Tesia_statements.GeneratePracticeInfo(writerElect);
     OpenDental.Bridges.EHG_statements.GeneratePracticeInfo(writerElect);
     DataSet dataSet;
     List<long> stateNumsElect=new List<long>();
     for(int i=0;i<gridBill.SelectedIndices.Length;i++){
         stmt=Statements.CreateObject(PIn.Long(table.Rows[gridBill.SelectedIndices[i]]["StatementNum"].ToString()));
         fam=Patients.GetFamily(stmt.PatNum);
         pat=fam.GetPatient(stmt.PatNum);
         patFolder=ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath());
         dataSet=AccountModules.GetStatementDataSet(stmt);
         if(stmt.Mode_==StatementMode.Email){
             if(PrefC.GetString(PrefName.EmailSMTPserver)==""){
                 MsgBox.Show(this,"You need to enter an SMTP server name in e-mail setup before you can send e-mail.");
                 Cursor=Cursors.Default;
                 isPrinting=false;
                 //FillGrid();//automatic
                 return;
             }
             if(pat.Email==""){
                 skipped++;
                 continue;
             }
         }
         stmt.IsSent=true;
         stmt.DateSent=DateTime.Today;
         FormST.CreateStatementPdf(stmt,pat,fam,dataSet);
         if(stmt.DocNum==0){
             MsgBox.Show(this,"Failed to save PDF.  In Setup, DataPaths, please make sure the top radio button is checked.");
             Cursor=Cursors.Default;
             isPrinting=false;
             return;
         }
         //imageStore = OpenDental.Imaging.ImageStore.GetImageStore(pat);
         savedPdfPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),patFolder);
         if(stmt.Mode_==StatementMode.InPerson || stmt.Mode_==StatementMode.Mail){
             if(pd==null){
                 pd=new PrintDocument();
             }
             inputDocument=PdfReader.Open(savedPdfPath,PdfDocumentOpenMode.Import);
             for(int idx=0;idx<inputDocument.PageCount;idx++){
                 page=inputDocument.Pages[idx];
                 outputDocument.AddPage(page);
             }
             printed++;
             labelPrinted.Text=Lan.g(this,"Printed=")+printed.ToString();
             Application.DoEvents();
             Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
         if(stmt.Mode_==StatementMode.Email){
             attachPath=FormEmailMessageEdit.GetAttachPath();
             rnd=new Random();
             fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
             filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
             File.Copy(savedPdfPath,filePathAndName);
             //Process.Start(filePathAndName);
             message=new EmailMessage();
             message.PatNum=pat.PatNum;
             message.ToAddress=pat.Email;
             message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
             string str;
             str=PrefC.GetString(PrefName.BillingEmailSubject);
             str=str.Replace("[nameF]",pat.GetNameFirst());
             str=str.Replace("[nameFL]",pat.GetNameFL());
             str=str.Replace("[namePref]",pat.Preferred);
             str=str.Replace("[PatNum]",pat.PatNum.ToString());
             message.Subject=str;
             str=PrefC.GetString(PrefName.BillingEmailBodyText);
             str=str.Replace("[nameF]",pat.GetNameFirst());
             str=str.Replace("[nameFL]",pat.GetNameFL());
             str=str.Replace("[namePref]",pat.Preferred);
             str=str.Replace("[PatNum]",pat.PatNum.ToString());
             message.BodyText=str;
             attach=new EmailAttach();
             attach.DisplayedFileName="Statement.pdf";
             attach.ActualFileName=fileName;
             message.Attachments.Add(attach);
             try{
                 FormEmailMessageEdit.SendEmail(message);
                 emailed++;
                 labelEmailed.Text=Lan.g(this,"E-mailed=")+emailed.ToString();
                 Application.DoEvents();
             }
             catch{
                 //Cursor=Cursors.Default;
                 //MessageBox.Show(ex.Message);
                 //return;
                 skipped++;
                 continue;
             }
             Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
         if(stmt.Mode_==StatementMode.Electronic) {
             stateNumsElect.Add(stmt.StatementNum);
             //OpenDental.Bridges.Tesia_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
             OpenDental.Bridges.EHG_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
             sentelect++;
             labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
             Application.DoEvents();
             //do this later:
             //Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
     }
     //now print-------------------------------------------------------------------------------------
     if(pd!=null){
         string tempFileOutputDocument=Path.GetTempFileName()+".pdf";
         outputDocument.Save(tempFileOutputDocument);
         try{
             Process.Start(tempFileOutputDocument);
         }
         catch(Exception ex){
             MessageBox.Show(Lan.g(this,"Error: Please make sure Adobe Reader is installed.")+ex.Message);
         }
         //}
     }
     //finish up elect and send if needed------------------------------------------------------------
     if(sentelect>0) {
         //OpenDental.Bridges.Tesia_statements.GenerateWrapUp(writerElect);
         OpenDental.Bridges.EHG_statements.GenerateWrapUp(writerElect);
         writerElect.Close();
         try {
             //OpenDental.Bridges.Tesia_statements.Send(strBuildElect.ToString());
             OpenDental.Bridges.EHG_statements.Send(strBuildElect.ToString());
             //CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(strBuildElect.ToString());
             //msgbox.ShowDialog();
             //loop through all statements and mark sent
             for(int i=0;i<stateNumsElect.Count;i++) {
                 Statements.MarkSent(stateNumsElect[i],DateTime.Today);
             }
         }
         catch(Exception ex) {
             MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message);
             msgbox.ShowDialog();
             //MessageBox.Show();
             sentelect=0;
             labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
         }
     }
     else {
         writerElect.Close();
     }
     string msg="";
     if(skipped>0){
         msg+=Lan.g(this,"Skipped due to missing or bad email address: ")+skipped.ToString()+"\r\n";
     }
     msg+=Lan.g(this,"Printed: ")+printed.ToString()+"\r\n"
         +Lan.g(this,"E-mailed: ")+emailed.ToString()+"\r\n"
         +Lan.g(this,"SentElect: ")+sentelect.ToString();
     MessageBox.Show(msg);
     Cursor=Cursors.Default;
     isPrinting=false;
     FillGrid();//not automatic
 }
		private void butShowXml_Click(object sender,EventArgs e) {
			string ccd="";
			try {
				FormEhrExportCCD FormEEC=new FormEhrExportCCD(PatCur);
				FormEEC.ShowDialog();
				if(FormEEC.DialogResult==DialogResult.OK) {
					ccd=FormEEC.CCD;
				}
				else {
					return;
				}
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return;
			}
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ccd);
			msgbox.ShowDialog();
		}
Exemple #20
0
		private void butRawMessage_Click(object sender,EventArgs e) {
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(_emailMessage.RawEmailIn);
			msgbox.ShowDialog();
		}		
		private void butGetElectronic_Click(object sender,EventArgs e) {
			//button not visible if SubCur is null
			if(PrefC.GetBool(PrefName.CustomizedForPracticeWeb)) {
				EligibilityCheckDentalXchange();
				return;
			}
			//Visible for everyone.
			Clearinghouse clearhouse=Clearinghouses.GetDefaultDental();
			if(clearhouse==null){
				MsgBox.Show(this,"No clearinghouse is set as default.");
				return;
			}
			if(clearhouse.CommBridge!=EclaimsCommBridge.ClaimConnect
				&& clearhouse.Eformat!=ElectronicClaimFormat.Canadian)
			{
				MsgBox.Show(this,"So far, eligibility checks only work with ClaimConnect and CDAnet.");
				return;
			}
			if(clearhouse.Eformat==ElectronicClaimFormat.Canadian) {
				EligibilityCheckCanada();
				return;
			}
			if(!FillPlanCurFromForm()) {
				return;
			}
			Cursor=Cursors.WaitCursor;
			try {
				Eclaims.x270Controller.RequestBenefits(clearhouse,PlanCur,PatPlanCur.PatNum,CarrierCur,benefitList,PatPlanCur.PatPlanNum,SubCur);
			}
			catch(Exception ex) {//although many errors will be caught and result in a response etrans.
				//this also catches validation errors such as missing info.
				Cursor=Cursors.Default;
				if(ex.Message.Contains("AAA*N**79*")){
					MsgBox.Show(this,"There is a problem with your benefits request. The clearing house you are using (typically Claim Connect) may not support Real Time Eligibility "
						+"for this carrier. Please ensure the carrier's electronic ID is correct and that your clearing house supports Real Time Eligibility for this carrier.");
				}
				else{
					CodeBase.MsgBoxCopyPaste msgbox=new CodeBase.MsgBoxCopyPaste(ex.Message);
					msgbox.ShowDialog();
				}
			}
			Cursor=Cursors.Default;
			DateTime dateLast270=Etranss.GetLastDate270(PlanCur.PlanNum);
			if(dateLast270.Year<1880) {
				textElectBenLastDate.Text="";
			}
			else {
				textElectBenLastDate.Text=dateLast270.ToShortDateString();
			}
			FillBenefits();
		}
Exemple #22
0
		///<summary></summary>
		private void butSend_Click(object sender, System.EventArgs e) {
			//this will not be available if already sent.
			if(emailPreview.FromAddress=="" || emailPreview.ToAddress=="") {
				MsgBox.Show(this,"Addresses not allowed to be blank.");
				return;
			}
			if(EhrCCD.HasCcdEmailAttachment(_emailMessage)) {
				MsgBox.Show(this,"The email has a summary of care attachment which may contain sensitive patient data.  Use the Direct Message button instead.");
				return;
			}
			EmailAddress emailAddress=emailPreview.GetEmailAddress();
			if(emailAddress.SMTPserver==""){
				MsgBox.Show(this,"The email address in email setup must have an SMTP server.");
				return;
			}
			Cursor=Cursors.WaitCursor;
			SaveMsg();
			try{
				if(emailPreview.IsSigned) {
					EmailMessages.SendEmailUnsecureWithSig(_emailMessage,emailAddress,emailPreview.Signature);
				}
				else {
					EmailMessages.SendEmailUnsecure(_emailMessage,emailAddress);
				}
				_emailMessage.SentOrReceived=EmailSentOrReceived.Sent;
				EmailMessages.Update(_emailMessage);
				MsgBox.Show(this,"Sent");
			}
			catch(Exception ex){
				Cursor=Cursors.Default;
				MsgBoxCopyPaste msgBox=new MsgBoxCopyPaste(ex.Message);
				msgBox.ShowDialog();
				return;
			}
			Cursor=Cursors.Default;
			//MessageCur.MsgDateTime=DateTime.Now;
			DialogResult=DialogResult.OK;
		}
		private void butShowXml_Click(object sender,EventArgs e) {
			string strCcd=File.ReadAllText(StrXmlFilePath);
			//Reformat to add newlines after each element to make more readable.
			strCcd=strCcd.Replace("\r\n","").Replace("\n","").Replace("\r","");//Remove existsing newlines.
			strCcd=strCcd.Replace(">",">\r\n");
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(strCcd);
			msgbox.ShowDialog();
		}
Exemple #24
0
		private void gridClaimAdjustments_CellDoubleClick(object sender,ODGridClickEventArgs e) {
			Hx835_Adj adj=(Hx835_Adj)gridClaimAdjustments.Rows[e.Row].Tag;
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(adj.AdjCode+" "+adj.AdjustDescript+"\r\r"+adj.ReasonDescript+"\r\n"+adj.AdjAmt.ToString("f2"));
			msgbox.Show(this);
		}
		private void ShowColor(object sender) {
			Color color=((Button)sender).BackColor;
			int colorint=color.ToArgb();
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(colorint.ToString());
			msgbox.ShowDialog();
		}
Exemple #26
0
		private void butShow_Click(object sender,EventArgs e) {
			if(gridMain.SelectedIndices.Length==0) {
				MessageBox.Show("Please select lab panels first.");
				return;
			}
			List<LabPanel> panels=new List<LabPanel>();
			for(int i=0;i<gridMain.SelectedIndices.Length;i++) {
				panels.Add(listLP[gridMain.SelectedIndices[i]]);
			}
			OpenDentBusiness.HL7.EhrORU oru=new OpenDentBusiness.HL7.EhrORU();
			Cursor=Cursors.WaitCursor;
			try {
				oru.Initialize(panels);
			}
			catch(ApplicationException ex) {
				Cursor=Cursors.Default;
				MessageBox.Show(ex.Message);
				return;
			}
			string outputStr=oru.GenerateMessage();
			Cursor=Cursors.Default;
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(outputStr);
			msgbox.ShowDialog();
		}
		private void butManEdit_Click(object sender,EventArgs e) {
			//PumpGridIntoTable();
			Markup=GenerateMarkup();
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(Markup);
			msgbox.ShowDialog();
			if(msgbox.DialogResult!=DialogResult.OK) {
				return;
			}
			Markup=msgbox.textMain.Text;
			ParseMarkup();
			FillGrid();
		}
		private void butRawMessage_Click(object sender,EventArgs e) {
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(MessageText);
			msgbox.ShowDialog();
		}
		private void ManuallyEdit() {
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(Markup);
			msgbox.ShowDialog();
			if(msgbox.DialogResult==DialogResult.OK) {
				Markup=msgbox.textMain.Text;
				ParseMarkup();//try again
			}
			else {
				DialogResult=DialogResult.Cancel;
			}
		}
		private void butShowXml_Click(object sender,EventArgs e) {
			string ccd="";
			try {
				ccd=EhrCCD.GenerateElectronicCopy(PatCur);
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return;
			}
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ccd);
			msgbox.ShowDialog();
		}
Exemple #31
0
        ///<summary>Log a message to the log text file and add a description of the sender (for debugging purposes). If sender is null then a description of the sender is not printed. Always returns false so that a calling boolean function can return at the same time that it logs an error message.</summary>
        public bool Log(Object sender, string sendingFunctionName, string message, bool msgBox, Severity severity)
        {
            if (severity > level)          //Only log messages with a severity matches the current level. This will even skip message boxes.
            {
                return(false);
            }
            try{
                if (sender != null)
                {
                    if (sendingFunctionName != null && sendingFunctionName.Length > 0)
                    {
                        message = sender.ToString() + "." + sendingFunctionName + ": " + message;
                    }
                    else
                    {
                        message = sender.ToString() + ": " + message;
                    }
                }
                else if (sendingFunctionName != null && sendingFunctionName.Length > 0)
                {
                    message = sendingFunctionName + ": " + message;
                }
                int procId = System.Diagnostics.Process.GetCurrentProcess().Id;
                message = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " " + procId.ToString().PadLeft(6, '0') + " " +
                          SeverityToString(severity) + " " + message;
                if (msgBox)
                {
                    MsgBoxCopyPaste mbox = new MsgBoxCopyPaste(message);
                    mbox.ShowDialog();
                }
            }catch (Exception e) {
                MessageBox.Show(e.ToString());
            }
            //File access is always exclusive, so if we cannot access the file, we can try again for a little while
            //and hope that the other process will release the file.
            bool tryagain = true;
            int  numtries = 0;

            while (tryagain && numtries < 5)
            {
                tryagain = false;
                numtries++;
                try{
                    if (logFile != null)
                    {
                        //Ensure that the log file always exists before trying to read it.
                        if (!File.Exists(logFile))
                        {
                            try{
                                FileStream fs = File.Create(logFile);
                                fs.Dispose();
                            }catch {
                            }
                        }
                        else
                        {
                            //Make the log file roll into the old log file when it reaches the roll byte size.
                            System.IO.StreamReader sr = new System.IO.StreamReader(logFile);
                            if (sr != null)
                            {
                                Stream st         = sr.BaseStream;
                                long   fileLength = st.Length;
                                if (fileLength >= logRollByteCount)
                                {
                                    try {
                                        File.Copy(logFile, logFile + ".old.txt");
                                    }catch {
                                    }
                                    try{
                                        File.Delete(logFile);
                                    }catch {
                                    }
                                    fileLength = 0;
                                }
                                st.Dispose();
                                sr.Dispose();
                                if (fileLength < 1)
                                {
                                    try{
                                        FileStream fs = File.Create(logFile);
                                        fs.Dispose();
                                    }catch {
                                    }
                                }
                            }
                        }
                        //Re-open the log file
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(logFile, true);                     //Open the file exclusively.
                        if (sw != null)
                        {
                            sw.WriteLine(message);
                            sw.Flush();
                            sw.Dispose();                            //Close the file to allow exclusive access by other instances of OpenDental.
                        }
                    }
                }catch {
                    tryagain = true;
                }
            }
            return(false);
        }
		///<summary>Used to show EULA or other pre-download actions.  Displays message boxes. Returns false if pre-download checks not satisfied.</summary>
		private bool PreDownloadHelper(string codeSystemName) {
			string programVersion=PrefC.GetString(PrefName.ProgramVersion);
			switch(codeSystemName) {
				//Code system specific pre-download actions.
				case "SNOMEDCT":
					#region SNOMEDCT EULA
					string EULA=@"Open Dental "+programVersion+@" includes SNOMED Clinical Terms® (SNOMED CT®) which is used by permission of the International Health Terminology Standards Development Organization (IHTSDO). All rights reserved. SNOMED CT® was originally created by the College of American Pathologists. “SNOMED”, “SNOMED CT” and “SNOMED Clinical Terms” are registered trademarks of the IHTSDO (www.ihtsdo.org).
Use of SNOMED CT in Open Dental "+programVersion+@" is governed by the conditions of the following SNOMED CT Sub-license issued by Open Dental Software Inc.
1. The meaning of the terms “Affiliate”, or “Data Analysis System”, “Data Creation System”, “Derivative”, “End User”, “Extension”, “Member”, “Non-Member Territory”, “SNOMED CT” and “SNOMED CT Content” are as defined in the IHTSDO Affiliate License Agreement (see www.ihtsdo.org/license.pdf).
2. Information about Affiliate Licensing is available at www.ihtsdo.org/license. Individuals or organizations wishing to register as IHTSDO Affiliates can register at www.ihtsdo.org/salsa, subject to acceptance of the Affiliate License Agreement (see www.ihtsdo.org/license.pdf).
3. The current list of IHTSDO Member Territories can be viewed at www.ihtsdo.org/members. Countries not included in that list are “Non-Member Territories”.
4. End Users, that do not hold an IHTSDO Affiliate License, may access SNOMED CT® using Open Dental subject to acceptance of and adherence to the following sub-license limitations:
  a) The sub-licensee is only permitted to access SNOMED CT® using this software (or service) for the purpose of exploring and evaluating the terminology.
  b) The sub-licensee is not permitted the use of this software as part of a system that constitutes a SNOMED CT “Data Creation System” or “Data Analysis System”, as defined in the IHTSDO Affiliate License. This means that the sub-licensee must not use Open Dental "+programVersion+@" to add or copy SNOMED CT identifiers into any type of record system, database or document.
  c) The sub-licensee is not permitted to translate or modify SNOMED CT Content or Derivatives.
  d) The sub-licensee is not permitted to distribute or share SNOMED CT Content or Derivatives.
5. IHTSDO Affiliates may use Open Dental "+programVersion+@" as part of a “Data Creation System” or “Data Analysis System” subject to the following conditions:
  a) The IHTSDO Affiliate, using Open Dental "+programVersion+@" must accept full responsibility for any reporting and fees due for use or deployment of such a system in a Non-Member Territory.
  b) The IHTSDO Affiliate must not use Open Dental "+programVersion+@" to access or interact with SNOMED CT in any way that is not permitted by the Affiliate License Agreement.
  c) In the event of termination of the Affiliate License Agreement, the use of Open Dental "+programVersion+@" will be subject to the End User limitations noted in 4.";
					#endregion
					MsgBoxCopyPaste FormMBCP=new MsgBoxCopyPaste(EULA);
					FormMBCP.ShowDialog();
					if(FormMBCP.DialogResult!=DialogResult.OK) {
						MsgBox.Show("CodeSystemImporter","SNOMED CT codes will not be imported.");
						return false;//next selected index
					}
					break;
				case "LOINC"://Main + third party
					#region Loinc EULA
					string LoincEULA=@"LOINC and RELMA version 2.44
Released June 29, 2013

This product includes all or a portion of the LOINC® table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file, or is derived from one or more of the foregoing, subject to a license from Regenstrief Institute, Inc. Your use of the LOINC table, LOINC codes, LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file also is subject to this license, a copy of which is available at http://loinc.org/terms-of-use. The current complete LOINC table, LOINC Users' Guide, LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file are available for download at http://loinc.org. The LOINC table and LOINC codes are copyright © 1995-2013, Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee. The LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file are copyright © 1995-2013, Regenstrief Institute, Inc. All rights reserved. THE LOINC TABLE (IN ALL FORMATS), LOINC PANELS AND FORMS FILE, LOINC DOCUMENT ONTOLOGY FILE, AND LOINC HIERARCHIES ARE PROVIDED ""AS IS.""  ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. LOINC® is a registered United States trademark of Regenstrief Institute, Inc. A small portion of the LOINC table may include content (e.g., survey instruments) that is subject to copyrights owned by third parties. Such content has been mapped to LOINC terms under applicable copyright and terms of use. Notice of such third party copyright and license terms would need to be included if such content is included.

Copyright Notice and License: http://loinc.org/terms-of-use 
The LOINC® codes, LOINC® table (regardless of format), LOINC® Release Notes, LOINC® Changes File, and LOINC® Users' Guide are copyright © 1995-2013, Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee. All rights reserved. 
The RELMA® program, RELMA® database and associated search index files (subject to the copyright above with respect to the LOINC® codes and LOINC® table included therein), RELMA® Community Mapping Feature Database, RELMA® Release Notes, and RELMA® Users' Manual are copyright © 1995-2013, Regenstrief Institute, Inc. All rights reserved.
The LOINC® panels and forms file, LOINC® document ontology file, and the LOINC® hierarchies file (subject to the copyright above with respect to the LOINC® codes and LOINC® table to the extent included therein), are copyright © 1995-2013, Regenstrief Institute, Inc. All rights reserved.
LOINC® and RELMA® are registered United States trademarks of Regenstrief Institute, Inc.  
Permission is hereby granted in perpetuity, without payment of license fees or royalties, to use, copy, or distribute the RELMA® program, RELMA® Users' Manual, RELMA® Release Notes, RELMA® database and associated search index files, LOINC® codes, LOINC® Users' Guide, LOINC® table (in all formats in which it is distributed by Regenstrief Institute, Inc. and the LOINC Committee), LOINC® Release Notes, LOINC® Changes File, LOINC® panels and forms file, LOINC® document ontology file, and LOINC® hierarchies file (collectively, the ""Licensed Materials"") for any commercial or non-commercial purpose, subject to the following terms and conditions:
1. To prevent the dilution of the purpose of the LOINC codes and LOINC table of providing a definitive standard for identifying clinical information in electronic reports, users shall not use any of the Licensed Materials for the purpose of developing or promulgating a different standard for identifying patient observations, such as laboratory test results; other diagnostic service test results; clinical observations and measurements; reports produced by clinicians and diagnostic services about patients; panels, forms, and collections that define aggregations of these observations; and orders for these entities in electronic reports and messages.
2. If the user elects to use the RELMA program, users receive the full RELMA database and associated search index files with the RELMA program, including the LOINC table and other database tables comprising the RELMA database. In addition to its use with the RELMA program, users may use the LOINC table by itself and may modify the LOINC table as permitted herein. Users may not use or modify the other database tables from the RELMA database or the associated search index files except in conjunction with their authorized use of the RELMA program, unless prior written permission is granted by the Regenstrief Institute, Inc. To request written permission, please contact [email protected]. The RELMA program also provides access to certain internet-based content copyrighted by Regenstrief Institute. No additional permission to modify or distribute this internet-based content is granted through the user’s use of the RELMA program.
3. The RELMA program also includes the RELMA Community Mappings feature and access to the RELMA Community Mappings feature database. The accuracy and completeness of the information in the RELMA Community Mappings feature is not verified by Regenstrief or the LOINC Committee. Through the RELMA Community Mappings feature, users will have the option of submitting information, including user’s local mappings, back to the RELMA Community Mappings feature database.
a. By using the RELMA Community Mappings feature, users agree as follows:
i. Users may not copy, distribute, or share access to the information provided by the RELMA Community Mappings feature.
ii. Users accept the risk of using the information provided by the RELMA Community Mappings feature, recognize that such information is submitted by other users, and understand that neither Regenstrief Institute, Inc. nor the LOINC Committee are liable for the information provided by the RELMA Community Mappings feature.
iii. Regenstrief may contact users regarding:
1. Use of the RELMA Community Mappings feature;
2. Submission requests for additional information; and
3. Any mapping submissions that the user makes to the RELMA Community Mappings feature database;
iv. Others may contact user about submissions made to the RELMA Community Mappings feature database;
v. Regenstrief may collect information about use of these services including, but not limited to:
1. Device specific information such as hardware model, operating system, and version;
2. Internet Protocol address;
3. How user used the service (such as search queries run and about which LOINC code terms accessory information was reviewed);
4. User’s contact name, email, and organization; and
5. Regenstrief may associate this information with a user’s account on loinc.org;
vi. User will make reasonable efforts to submit user’s mappings back to the RELMA Community Mappings feature database, which may contain the following information (as applicable):
1. Local battery/panel/test code
2. Local battery/panel/test name/description
3. Units of Measure
4. LOINC code to which it is mapped
5. Date of mapping
6. Language of test names
7. Version of LOINC used to do the mapping
8. Contact information;
vii. If a user submits mappings on behalf of an organization, the user represents that the user has the authority to agree to these terms on behalf of user’s organization.
viii. If a user submits mappings back to the RELMA Community Mappings feature database, then the user hereby grants, on behalf of themselves and user’s organization, Regenstrief a non-exclusive license without payment or fees to submitted mappings in perpetuity for purposes related to LOINC, RELMA, and Regenstrief’s mission, including, but not limited to:
1. Making information publicly available;
2. Performing aggregate analysis;
3. Conducting and publishing research that does not identify user or user’s organization by name;
4. Developing and enhancing LOINC and associated software tools. 
4. Users shall not change the meaning of any of the LOINC codes. Users shall not change the name of, or any contents of, any fields in the LOINC table. Users may add new fields to the LOINC table to attach additional information to existing LOINC records. Users shall not change the content or structure of the LOINC document ontology file or the LOINC panels and forms from the LOINC panels and forms file, but may notify the Regenstrief Institute of any potential inconsistencies or corrections needed by contacting [email protected].
5. A user may delete records from the LOINC table to deal with the user's local requirements. A user also may add new records to the LOINC table to deal with the users' local requirements, provided that if new records are added, any new entry in the LOINC_NUM field of such new records must contain a leading alphabetic ""X"" so that the new codes and records cannot be confused with existing LOINC codes or new LOINC codes as they are defined in later releases of the LOINC table. Records deleted or added by users to deal with local requirements are not reflected in the official LOINC table maintained by the Regenstrief Institute and the LOINC Committee. Users must also make reasonable efforts to submit requests to LOINC for new records to cover observations that are not found in the LOINC table in order to minimize the need for X-codes.
6. LOINC codes and other information from the LOINC table may be used in electronic messages for laboratory test results and clinical observations such as HL7 ORU messages, without the need to include this Copyright Notice and License or a reference thereto in the message (and without the need to include all fields required by Section 8 hereof). When the LOINC code (from the LOINC_NUM field) is included in the message, users are encouraged, but not required, to include the corresponding LOINC short name (from the SHORTNAME field) or the LOINC long common name (from the LONG_COMMON_NAME field) in the message if the message provides a place for a text name representation of the code. 
7. Users may make and distribute an unlimited number of copies of the Licensed Materials. Each copy thereof must include this Copyright Notice and License, and must include the appropriate version number of the Licensed Materials if the Licensed Materials have a version number, or the release date if the Licensed Materials do not have a version number. This Copyright Notice and License must appear on every printed copy of the LOINC table. Where the Licensed Materials are distributed on a fixed storage medium (such as CD-ROM), a printed copy of this Copyright Notice and License must be included on or with the storage medium, and a text file containing this information also must be stored on the storage medium in a file called ""license.txt"". Where the Licensed Materials are distributed via the Internet, this Copyright Notice and License must be accessible on the same Internet page from which the Licensed Materials are available for download. This Copyright Notice and License must appear verbatim on every electronic or printed copy of the RELMA Users' Manual and the LOINC Users' Guide. The RELMA Users' Manual and the LOINC Users' Guide may not be modified, nor may derivative works of the RELMA Users' Manual or LOINC Users' Guide be created, without the prior written permission of the Regenstrief Institute, Inc. To request written permission, please contact [email protected]. The Regenstrief Institute retains the right to approve any modification to, or derivative work of, the RELMA Users' Manual or the LOINC Users' Guide.
8.  Subject to Section 1 and the other restrictions hereof, users may incorporate portions of the LOINC table, LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file into another master term dictionary (e.g. laboratory test definition database), or software program for distribution outside of the user's corporation or organization, provided that any such master term dictionary or software program includes the following fields reproduced in their entirety from the LOINC table: LOINC_NUM, COMPONENT, PROPERTY, TIME_ASPCT, SYSTEM, SCALE_TYP, METHOD_TYP, STATUS, and SHORTNAME. Users are also required to either: (1) include the EXTERNAL_COPYRIGHT_NOTICE or (2) delete the rows that include third party copyrighted content (e.g., third party survey instruments and answers). If third party content is included, users are required to comply with any such third party copyright license terms. Users are encouraged, but not required, to also include the RelatedNames2 and the LONG_COMMON_NAME in any such database. Further description of these fields is provided in Appendix A of the LOINC Users' Guide. Every copy of the LOINC table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file incorporated into or distributed in conjunction with another database or software program must include the following notice:

""This product includes all or a portion of the LOINC® table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file, or is derived from one or more of the foregoing, subject to a license from Regenstrief Institute, Inc. Your use of the LOINC table, LOINC codes, LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file also is subject to this license, a copy of which is available at http://loinc.org/terms-of-use. The current complete LOINC table, LOINC Users' Guide, LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file are available for download athttp://loinc.org. The LOINC table and LOINC codes are copyright © 1995-2013, Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee. The LOINC panels and forms file, LOINC document ontology file, and LOINC hierarchies file are copyright © 1995-2013, Regenstrief Institute, Inc. All rights reserved. THE LOINC TABLE (IN ALL FORMATS), LOINC PANELS AND FORMS FILE, LOINC DOCUMENT ONTOLOGY FILE, AND LOINC HIERARCHIES ARE PROVIDED ""AS IS.""  ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. LOINC® is a registered United States trademark of Regenstrief Institute, Inc. A small portion of the LOINC table may include content (e.g., survey instruments) that is subject to copyrights owned by third parties. Such content has been mapped to LOINC terms under applicable copyright and terms of use. Notice of such third party copyright and license terms would need to be included if such content is included.""

If the master term dictionary or software program containing the LOINC table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file is distributed with a printed license, this statement must appear in the printed license. Where the master term dictionary or software program containing the LOINC table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file is distributed on a fixed storage medium, a text file containing this information also must be stored on the storage medium in a file called ""LOINC_short_license.txt"". Where the master term dictionary or software program containing the LOINC table, LOINC panels and forms file, LOINC document ontology file, and/or LOINC hierarchies file is distributed via the Internet, this information must be accessible on the same Internet page from which the product is available for download. 
9. Subject to Section 1 and the other restrictions hereof, users may incorporate portions of the LOINC table and LOINC panels and forms file into another document (e.g., an implementation guide or other technical specification) for distribution outside of the user's corporation or organization, subject to these terms:
a. Every copy of the document that contains portions of the LOINC table or LOINC panels and forms file must include the following notice:

""This material contains content from LOINC® (http://loinc.org). The LOINC table, LOINC codes, and LOINC panels and forms file are copyright © 1995-2013, Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee and available at no cost under the license at http://loinc.org/terms-of-use.”
b. Users are strongly encouraged, but not required, to indicate the appropriate version number of the Licensed Material used.
c. Any information in the document that is extracted from the LOINC table or LOINC panels and forms file must always be associated with the corresponding LOINC code.
d. Along with the LOINC code, users are required to include one of the following LOINC display names:
i. The fully-specified name, which includes the information from the COMPONENT, PROPERTY, TIME_ASPCT, SYSTEM, SCALE_TYP, and METHOD_TYP fields;
ii. The LOINC short name (from the SHORTNAME field); and
iii. The LOINC long common name (from the LONG_COMMON_NAME field).
e. Users are also required to either:
i. Include the EXTERNAL_COPYRIGHT_NOTICE, or
ii. Exclude information from the rows that include third party copyrighted content (e.g., third party survey instruments and answers). If third party content is included, users are required to comply with any such third party copyright license terms.
10. Use and distribution of the Licensed Materials in ways that are not specifically discussed herein shall always be accompanied by the notice provided in Section 8 hereof. The guidelines for providing the notice that are contained in the last paragraph of Section 8 also shall apply. If a user has a question about whether a particular use of any of the Licensed Materials is permissible, the user is invited to contact the Regenstrief Institute by e-mail at [email protected].
11. If the user desires to translate any of the Licensed Materials into a language other than English, then user shall notify Regenstrief via email at [email protected]. Any such translation is a derivative work, and the user agrees and does hereby assign all right, title and interest in and to such derivative work: (1) to Regenstrief and the LOINC Committee if the translation is a derivative of the LOINC codes, LOINC Users' Guide, or LOINC table, and (2) to Regenstrief if the translation is a derivative work of the RELMA program, LOINC panels and forms file, LOINC document ontology file, LOINC hierarchies file, RELMA Users' Manual, RELMA database or associated search index files. Further, user shall fully cooperate with Regenstrief in the filing and reviewing of any copyright applications or other legal documents, and signing any documents (such as declarations, assignments, affidavits, and the like) that are reasonably necessary to the preparation of any such copyright application. The assignment granted by this paragraph extends to all proprietary rights both in the United States, and in all foreign countries. No other right to create a derivative work of any of the Licensed Materials is hereby granted (except the right to translate into a language other than English granted in this Section), and Regenstrief and the LOINC Committee respectively reserve all other rights not specifically granted herein. All such translations shall be electronically transmitted to Regenstrief, and such translations shall be made available and are subject to the same license rights and restrictions contained herein. Regenstrief will give credit on the LOINC website (and on screens in RELMA) to the user and/or entity that did the translation.
12. The Regenstrief Institute, Inc. and the LOINC Committee welcome requests for new LOINC content (terms, codes, or associated material such as text descriptions and synonyms) and suggestions about revisions to existing content within the Licensed Materials. Any content submitted in conjunction with such a request is subject to the LOINC Submissions Policy, which is available at http://loinc.org/submissions-policy.
13. The names ""Regenstrief,"" ""Regenstrief Foundation,"" ""Regenstrief Institute,"" and ""LOINC Committee"" may not be used in a way which could be interpreted as an endorsement or a promotion of any product or service without prior written permission of the Regenstrief Institute, Inc. Further, no right to use the trademarks of Regenstrief is licensed hereunder. To request written permission, please contact [email protected].
14. DISCLAIMER:  REGENSTRIEF INSTITUTE, INC. AND THE LOINC COMMITTEE, AS WELL AS ANY CONTRIBUTORS WHO HAVE PROVIDED TRANSLATIONS OF THE LICENSED MATERIALS, DO NOT ACCEPT LIABILITY FOR ANY OMISSIONS OR ERRORS IN THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE LOINC COMMITTEE. THE LICENSED MATERIALS AND ALL OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE LOINC COMMITTEE ARE PROVIDED ""AS IS,"" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESSED OR IMPLIED WARRANTIES ARE HEREBY DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND WARRANTIES ARISING FROM A COURSE OF DEALING, TRADE USAGE, OR TRADE PRACTICE. FURTHER, NO WARRANTY OR REPRESENTATION IS MADE CONCERNING THE ACCURACY, COMPLETENESS, SEQUENCE, TIMELINESS OR AVAILABILITY OF THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE LOINC COMMITTEE, OR ANY TRANSLATIONS OR DERIVATIVE WORKS OF ANY OF THE FOREGOING. IN NO EVENT SHALL REGENSTRIEF INSTITUTE, INC. OR THE LOINC COMMITTEE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RELIANCE, OR CONSEQUENTIAL DAMAGES OR ATTORNEYS' FEES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; OPPORTUNITY COSTS; LOSS OF USE, DATA, SAVINGS OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE LOINC COMMITTEE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE OR IF SUCH DAMAGES WERE FORESEEABLE. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF CERTAIN WARRANTIES OR CONDITIONS, SO SOME OF THE FOREGOING MAY NOT APPLY TO YOU.
15. This license shall be construed and interpreted in accordance with the laws of the State of Indiana, United States of America, excluding its conflicts of law rules.
 
Notice of Third Party Content and Copyright Terms
A small portion of the content of the LOINC table, LOINC panels and forms file, LOINC document ontology file, LOINC hierarchies file, RELMA database and associated search index files consists of content subject to copyright from third parties. This third party content is either used with permission or under the applicable terms of use. In all such cases, we have included the copyright notice. The copyright of the LOINC codes per se remain owned by Regenstrief Institute, Inc. and the LOINC Committee and subject to the LOINC Copyright Notice and License.
The third party content is identified in the LOINC table by the applicable copyright notice (up to 250 characters) stored in the EXTERNAL_COPYRIGHT_NOTICE field. In RELMA and our web-based search application (http://search.loinc.org), the third party content is highlighted as follows: When such content appears in a search result grid, the programs will display a field with a link to a page containing the copyright notice and terms of use for that content. The programs may also visually highlight the rows of these LOINC codes.
We have included third party content that allows use and distribution at least for clinical, administrative, and research purposes. The third party copyright owners generally ask for attribution of the source, allow the free use of the content for treatment, health care management, and research purposes. They generally forbid alteration of their content (e.g., survey questions and/or answers) and use for commercial purpose, which usually means the direct sale of the survey instruments. They often do allow use of their content in commercial software, medical record and other clinical database systems, and the messaging of patient information collected through the use of these instruments.";
					#endregion
					MsgBoxCopyPaste FormLoincEula=new MsgBoxCopyPaste(LoincEULA);
					FormLoincEula.ShowDialog();
					if(FormLoincEula.DialogResult!=DialogResult.OK) {
						MsgBox.Show("CodeSystemImporter","LOINC codes will not be imported.");
						return false;//next selected index
					}
					#region External Loinc copyrights
					string externalCopyright=@"External Copyright Notice

Copyright © 2010 FACIT.org. Used with permission

InterRAI holds the copyright to Version 2.0 of the RAI for long term care outside of the US. Content for MDS items in LOINC was derived from Version 2.0 of the RAI/MDS, and should not be reproduced outside of the United States without permission of InterRAI. Within the US, Version 2.0 is in the public domain.

©2010 PROMIS Health Organization or other individuals/entities that have contributed information and materials to Assessment Center, and are being used with the permission of the copyright holders. Use of PROMIS instruments (e.g., item banks, short forms, profile measures) are subject to the PROMIS Terms and Conditions available at: http://www.nihpromis.org/Web%20Pages/Network%20Testing.aspx

©2010 David Cella, PhD. Used with permission. All of these Neuro-QOL instruments can be used at no charge. We do ask, however, that you contact Neuro-QOL project manager, Vitali Ustsinovich, at [email protected] and let him know that you intend to use Neuro-QOL.

The Outcome and Assessment Information Set (OASIS)© Copyright © 2002 Center for Health Services Research, UCHSC, Denver, CO. All Rights Reserved.

Copyright © Pfizer Inc. All rights reserved. Developed by Drs. Robert L. Spitzer, Janet B.W. Williams, Kurt Kroenke and colleagues, with an educational grant from Pfizer Inc. No permission required to reproduce, translate, display or distribute.

©2005 American Physical Therapy Association. All rights reserved. Used with permission per LOINC Terms of Use, and in addition: Any further distribution or reproduction must include the following copyright statement: ""Copyright �2005 American Physical Therapy Association. All rights reserved."" Contact [email protected] with questions or for further information.

©2004. All rights reserved. Used with permission per LOINC Terms of Use. The Veterans RAND 12 Item Health Survey (VR-12) was developed from the Veterans RAND 36 Item Health Survey (VR-36) which was developed from the MOS RAND SF-36 Version 1.0. Details involving the VR-36 and VR-12 questionnaires, scoring algorithms for PCS and MCS summary measures, and imputation programs for missing values can be obtained on request by agreeing to the stipulations given by the RAND Corporation website (See http://www.rand.org/health/surveys_tools/mos/mos_core_36item_terms.html) in a letter to Dr. Lewis Kazis ([email protected]) on institutional letter head. Users of the VR-12 or VR-36 in clinical research studies should also notify Dr. Kazis.

©2001 Authors: Suzann K. Campbell, Gay L. Girolami, Thubi, H. A. Kolobe, Elizabeth T. Osten, Maureen C. Lenke. All rights reserved. Reproduced with permission.

Copyright ©PSM ZI Mannheim /Germany

© World Health Organization 2006© World Health Organization 2006. All rights reserved. Used with permission. Publications of the World Health Organization can be obtained from WHO Press, World Health Organization, 20 Avenue Appia, 1211 Geneva 27, Switzerland (tel: +41 22 791 2476; fax: +41 22 791 4857; email: [email protected]). Requests for permission to reproduce or translate WHO publications - whether for sale or for noncommercial distribution - should be addressed to WHO Press, at the above address (fax: +41 22 791 4806; email: [email protected]).The designations employed and the presentation of the material in this publication do not imply the expression of any opinion whatsoever on the part of the World Health Organization concerning the legal status of any country, territory, city or area or of its authorities, or concerning the delimitation of its frontiers or boundaries. Dotted lines on maps represent approximate border lines for which there may not yet be full agreement.

Used with permission

© World Health Organization 2006. All rights reserved. Used with permission. Publications of the World Health Organization can be obtained from WHO Press, World Health Organization, 20 Avenue Appia, 1211 Geneva 27, Switzerland (tel: +41 22 791 2476; fax: +41 22 791 4857; email: [email protected]). Requests for permission to reproduce or translate WHO publications - whether for sale or for noncommercial distribution - should be addressed to WHO Press, at the above address (fax: +41 22 791 4806; email: [email protected]).The designations employed and the presentation of the material in this publication do not imply the expression of any opinion whatsoever on the part of the World Health Organization concerning the legal status of any country, territory, city or area or of its authorities, or concerning the delimitation of its frontiers or boundaries. Dotted lines on maps represent approximate border lines for which there may not yet be full agreement.The mention of specific companies or of certain manufacturers' products does not imply that they are endorsed or recommended by the World Health Organization in preference to others of a similar nature that are not mentioned. Errors and omissions excepted, the names of proprietary products are distinguished by initial capital letters.All reasonable precautions have been taken by WHO to verify the information contained in this publication. However, the published material is being distributed without warranty of any kind, either express or implied. The responsibility for the interpretation and use of the material lies with the reader. In no event shall the World Health Organization be liable for damages arising from its use.

Copyright © 1996-2005 John Spertus MD MPH, used with permission

Adapted from: Inouye SK, vanDyck CH, Alessi CA, Balkin S, Siegal AP, Horwitz RI. Clarifying confusion: The Confusion Assessment Method. A new method for detection of delirium. Ann Intern Med. 1990; 113: 941-948. Confusion Assessment Method: Training Manual and Coding Guide, Copyright 2003, Sharon K. Inouye, M.D., MPH.

Portions © 1997 Barbara Huffines, used with permission

© Barbara Braden and Nancy Bergstrom 1988. All rights reserved. Used with permission. It is understood that the name of the instrument and the indication that the copyright belongs to Braden and Bergstrom remain on any copies and that you do not make any changes to the wording or scoring of this tool.

© 2002, The Regents of the University of Michigan. Include the following when printing the FLACC on documentation records, etc: Printed with permission © 2002, The Regents of the University of Michigan

Used with permission.

© World Health Organization 2006. All rights reserved. Used with permission. Publications of the World Health Organization can be obtained from WHO Press, World Health Organization, 20 Avenue Appia, 1211 Geneva 27, Switzerland (tel: +41 22 791 2476; fax: +41 22 791 4857; email: [email protected]). Requests for permission to reproduce or translate WHO publications - whether for sale or for noncommercial distribution - should be addressed to WHO Press, at the above address (fax: +41 22 791 4806; email: [email protected]).The designations employed and the presentation of the material in this publication do not imply the expression of any opinion whatsoever on the part of the World Health Organization concerning the legal status of any country, territory, city or area or of its authorities, or concerning the delimitation of its frontiers or boundaries. Dotted lines on maps represent approximate border lines for which there may not yet be full agreement.

©1986 Regents of the University of Minnesota, All rights reserved.  Do not copy or reproduce without permission. LIVING WITH HEART FAILURE� is a registered trademark of the Regents of the University of Minnesota.

Copyright © The Hartford Institute for Geriatric Nursing, College of Nursing, New York University, used with permission

MiniCog

Copyright © Pfizer Inc. All rights reserved. Reproduced with permission.Developed by Drs. Robert L. Spitzer, Janet B.W. Williams, Kurt Kroenke and colleagues, with an educational grant from Pfizer Inc. No permission required to reproduce, translate, display or distribute.

Copyright 2011 International Association for the Study of Pain (IASP). Used with permission. Before translating text into a language other than found on the Pediatric Pain Sourcebook (www.painsourcebook.ca), please contact IASP to gain permission.

Copyright © Pfizer Inc. All rights reserved. Reproduced with permission.

Copyright © 2009 by Paul H. Brookes Publishing Co., Inc

Copyright ©NPUAP, used with permission of the National Pressure Ulcer Advisory Panel 2012
";
					#endregion
					MsgBoxCopyPaste FormLoincEula2=new MsgBoxCopyPaste(externalCopyright);
					FormLoincEula2.ShowDialog();
					if(FormLoincEula2.DialogResult!=DialogResult.OK) {
						MsgBox.Show("CodeSystemImporter","LOINC codes will not be imported.");
						return false;//next selected index
					}
					break;
				case "UCUM":
					#region UCUM EULA
					string UcumEULA=@"Unified Codes for Units of Measures (UCUM) version 1.7
This product includes all or a portion of the UCUM table, UCUM codes, and UCUM definitions or is derived from it, subject to a license from Regenstrief Institute, Inc. and The UCUM Organization. Your use of the UCUM table, UCUM codes, UCUM definitions also is subject to this license, a copy of which is available at http://unitsofmeasure.org. The current complete UCUM table, UCUM Specification are available for download at http://unitsofmeasure.org. The UCUM table and UCUM codes are copyright © 1995-2009, Regenstrief Institute, Inc. and the Unified Codes for Units of Measures (UCUM) Organization. All rights reserved.

THE UCUM TABLE (IN ALL FORMATS), UCUM DEFINITIONS, AND SPECIFICATION ARE PROVIDED ""AS IS."" ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 

Copyright Notice and License
The UCUM codes, UCUM table (regardless of format), and UCUM Specification are copyright © 1999-2009, Regenstrief Institute, Inc. and the Unified Codes for Units of Measures (UCUM) Organization. All rights reserved.
Regenstrief Institute, Inc. and the Unified Codes for Units of Measures (UCUM) Organization are hereunder collectively referred to as ""The Organization"".
Permission is hereby granted in perpetuity, without payment of license fees or royalties, to use, copy, or distribute the UCUM codes, UCUM Specification, and UCUM table (in all formats in which it is distributed by The Organization and the UCUM Organization) (collectively, the ""Licensed Materials"") for any commercial or non-commercial purpose, subject to the following terms and conditions:
1) To prevent the dilution of the purpose of the Licensed Materials, i.e., that of providing a definitive standard for identifying units of measures in electronic documents and messages, users shall not use any of the Licensed Materials for the purpose of developing or promulgating a different standard for identifying units of measure, regardless of whether the intended use is in the field of medicine, or any other field of science or trade.
2) Users shall not modify the Licensed Materials and may not distribute modified versions of the UCUM table (regardless of format) or UCUM Specification. Users shall not modify any existing contents, fields, description, or comments of the Licensed Materials, and may not add any new contents to it.
3) Users shall not use any of the UCUM codes in a way that expressly or implicitly changes their meaning.
4) RESERVED
5) UCUM codes and other information from the UCUM table may be used in electronic messages communicating measurements without the need to include this Copyright Notice and License or a reference thereto in the message (and without the need to include all fields required by Section 7 hereof).
6) Users may make and distribute an unlimited number of copies of the Licensed Materials. Each copy thereof must include this Copyright Notice and License, and must include the appropriate version or revision number of the Licensed Materials if the Licensed Materials have a version or revision number, or the release date if the Licensed Materials do not have a version or revision number. This Copyright Notice and License must appear on every printed copy of the Licensed Materials. Where the Licensed Materials are distributed on a fixed storage medium (such as a CD-ROM), a printed copy of this Copyright Notice and License must be included on or with the storage medium, and a text file containing this information also must be stored on the storage medium in a file called ""license.txt"". Where the Licensed Materials are distributed via the Internet, this Copyright Notice and License must be accessible on the same Internet page from which the Licensed Materials are available for download. This Copyright Notice and License must appear verbatim on every electronic or printed copy of the Licensed Materials. The UCUM Specification and related documents may not be modified, nor may derivative works be created from it, without the prior written permission of The Organization. To request written permission, please contact ucum@… (at unitsofmeasure.org). The Organization retains the right to approve any modification to, or derivative work of the Licensed Materials.
7) Subject to Section 1 and the other restrictions hereof, users may incorporate portions of the UCUM table and definitions into another master term dictionary (e.g. laboratory test definition database), or software program for distribution outside of the user's corporation or organization, provided that any such master term dictionary or software program includes the following fields reproduced in their entirety from the UCUM table: UCUM code, definition value and unit. Every copy of the UCUM table incorporated into or distributed in conjunction with another database or software program must include the following notice:
""This product includes all or a portion of the UCUM table, UCUM codes, and UCUM definitions or is derived from it, subject to a license from Regenstrief Institute, Inc. and The UCUM Organization. Your use of the UCUM table, UCUM codes, UCUM definitions also is subject to this license, a copy of which is available at http://unitsofmeasure.org. The current complete UCUM table, UCUM Specification are available for download at http://unitsofmeasure.org. The UCUM table and UCUM codes are copyright © 1995-2009, Regenstrief Institute, Inc. and the Unified Codes for Units of Measures (UCUM) Organization. All rights reserved.
THE UCUM TABLE (IN ALL FORMATS), UCUM DEFINITIONS, AND SPECIFICATION ARE PROVIDED ""AS IS."" ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.""
If the master term dictionary or software program containing the UCUM table, UCUM definitions and/or UCUM specification is distributed with a printed license, this statement must appear in the printed license. Where the master term dictionary or software program containing the UCUM table, UCUM definitions, and/or UCUM specification is distributed on a fixed storage medium, a text file containing this information also must be stored on the storage medium in a file called ""UCUM_short_license.txt"". Where the master term dictionary or software program containing the UCUM table, UCUM definitions, and/or UCUM specification is distributed via the Internet, this information must be accessible on the same Internet page from which the product is available for download.
8) Use and distribution of the Licensed Materials in ways that are not specifically discussed herein shall always be accompanied by the notice provided in Section 7 hereof. The guidelines for providing the notice that are contained in the last paragraph of Section 7 also shall apply. If a user has a question about whether a particular use of any of the Licensed Materials is permissible, the user is invited to contact The Organization by e-mail at ucum@… (at unitsofmeasure.org).
9) If the user desires to translate any of the Licensed Materials into a language other than English, then user shall notify The Organization via email at ucum@… (at unitsofmeasure.org). Any such translation is a derivative work, and the user agrees and does hereby assign all right, title and interest in and to such derivative work to The Organization. Further, user shall fully cooperate with The Organization in the filing and reviewing of any copyright applications or other legal documents, and signing any documents (such as declarations, assignments, affidavits, and the like) that are reasonably necessary to the preparation of any such copyright application. The assignment granted by this paragraph extends to all proprietary rights both in the United States, and in all foreign countries. No other right to create a derivative work of any of the Licensed Materials is hereby granted (except the right to translate into a language other than English granted in this Section 9), and The Organization reserves all other rights not specifically granted herein. All such translations shall be electronically transmitted to The Organization, and such translations shall be made available and are subject to the same license rights and restrictions contained herein. The Organization will give credit on its website to the user and/or entity that did the translation.
10) The Organization welcome requests for new UCUM content (terms, codes or associated material such as text descriptions and synonyms) and suggestions about revisions to existing content within the Licensed Materials. Such submissions should be done on The Organization's web site http://unitsofmeasure.org/trac/newticket.
11) The names ""UCUM Organization"" may not be used in a way which could be interpreted as an endorsement or a promotion of any product or service without prior written permission of The Organization. To request written permission, please contact ucum@… (at unitsofmeasure.org).
12) DISCLAIMER: REGENSTRIEF INSTITUTE, INC. AND THE UCUM ORGANIZATION DO NOT ACCEPT LIABILITY FOR ANY OMISSIONS OR ERRORS IN THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE UCUM ORGANIZATION. THE LICENSED MATERIALS AND ALL OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE UCUM ORGANIZATION ARE PROVIDED ""AS IS,"" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESSED OR IMPLIED WARRANTIES ARE HEREBY DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND WARRANTIES ARISING FROM A COURSE OF DEALING, TRADE USAGE, OR TRADE PRACTICE. FURTHER, NO WARRANTY OR REPRESENTATION IS MADE CONCERNING THE ACCURACY, COMPLETENESS, SEQUENCE, TIMELINESS OR AVAILABILITY OF THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE UCUM ORGANIZATION, OR ANY TRANSLATIONS OR DERIVATIVE WORKS OF ANY OF THE FOREGOING. IN NO EVENT SHALL REGENSTRIEF INSTITUTE, INC. OR THE UCUM ORGANIZATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RELIANCE, OR CONSEQUENTIAL DAMAGES OR ATTORNEYS' FEES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; OPPORTUNITY COSTS; LOSS OF USE, DATA, SAVINGS OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE LICENSED MATERIALS OR ANY OTHER MATERIALS OBTAINED FROM REGENSTRIEF INSTITUTE, INC. AND/OR THE UCUM ORGANIZATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE OR IF SUCH DAMAGES WERE FORESEEABLE. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF CERTAIN WARRANTIES OR CONDITIONS, SO SOME OF THE FOREGOING MAY NOT APPLY TO YOU.
13) This license shall be construed and interpreted in accordance with the laws of the State of Indiana, United States of America, excluding its conflicts of law rules.";
					#endregion
					MsgBoxCopyPaste FormUcumEULA=new MsgBoxCopyPaste(UcumEULA);
					FormUcumEULA.ShowDialog();
					if(FormUcumEULA.DialogResult!=DialogResult.OK) {
						MsgBox.Show("CodeSystemImporter","UCUM codes will not be imported.");
						return false;//next selected index
					}
					break;
			}
			return true;
		}
		private void butPreviewRequest_Click(object sender,EventArgs e) {
			KnowledgeRequestNotification.KnowledgeRequestNotification krn;
			for(int i=0;i<gridMain.Rows.Count;i++){
				if(gridMain.Rows[i].Tag==null){
					MsgBox.Show(this,"Cannot search without a valid code.");
					continue;
				}
				krn = new KnowledgeRequestNotification.KnowledgeRequestNotification();
				krn.AddObject(gridMain.Rows[i].Tag);
				MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste("http://apps.nlm.nih.gov/medlineplus/services/mpconnect.cfm?"+krn.ToUrl());
				msgbox.ShowDialog();
				//msgbox=new MsgBoxCopyPaste("http://apps2.nlm.nih.gov/medlineplus/services/servicedemo.cfm?"+krn.ToUrl());
				//msgbox.ShowDialog();
			}//end gridMain.Rows

		}
		public void ShowDisplayMessages(){
			StringBuilder message=new StringBuilder();
			CCDField[] displayMessageFields=formData.GetFieldsById("G32");
			for(int i=0;i<displayMessageFields.Length;i++){
				if(message.Length>0){
					message.Append(Environment.NewLine);
				}
				message.Append(displayMessageFields[i].valuestr);
			}
			CCDField[] noteOutputFlags=formData.GetFieldsById("G41");
			CCDField[] noteNumbers=formData.GetFieldsById("G45");
			CCDField[] noteTexts=formData.GetFieldsById("G26");
			List<string> displayMessages=new List<string>();
			List<int> displayMessageNumbers=new List<int>();
			for(int i=0;i<noteOutputFlags.Length;i++) {
				//We display notes on screen only if they are marked with output flag 1 (display notes on screen). Output flag 0 (prompt) is ignored here because such notes are printed on the physical printout.
				if(PIn.Int(noteOutputFlags[i].valuestr)!=1) { 
					continue;
				}
				displayMessages.Add(noteTexts[i].valuestr);
				if(i<noteNumbers.Length) {
					displayMessageNumbers.Add(PIn.Int(noteNumbers[i].valuestr));
				}
				else {
					displayMessageNumbers.Add(i+1);
				}
			}
			while(displayMessages.Count>0) {
				int indexOfMinVal=0;
				for(int j=1;j<displayMessageNumbers.Count;j++) {
					if(displayMessageNumbers[j]<displayMessageNumbers[indexOfMinVal]) {
						indexOfMinVal=j;
					}
				}
				doc.StartElement();
				if(message.Length>0) {
					message.Append(Environment.NewLine);
				}
				message.Append(displayMessages[indexOfMinVal]);
				displayMessages.RemoveAt(indexOfMinVal);
				displayMessageNumbers.RemoveAt(indexOfMinVal);
			}
			string msg=message.ToString();
			if(msg.Length>0){
				MsgBoxCopyPaste msgBox=new MsgBoxCopyPaste(msg);
				msgBox.Text="Messages";
				msgBox.ShowDialog();
			}
		}
		private void butPreview_Click(object sender,EventArgs e) {
			if(!isValidHL7DataSet()) {
				return;
			}
			MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(GenerateKnowledgeRequestNotification());
			msgbox.ShowDialog();
		}