Beispiel #1
0
		///<summary></summary>
		public static long Insert(MedicationPat Cur) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Cur.MedicationPatNum=Meth.GetLong(MethodBase.GetCurrentMethod(),Cur);
				return Cur.MedicationPatNum;
			}
			return Crud.MedicationPatCrud.Insert(Cur);
		}
Beispiel #2
0
		///<summary>For CPOE.  Used for both manual rx and eRx through NewCrop.  Creates or updates a medical order using the given prescription information.
		///Since rxCui is not part of the prescription, it must be passed in as a separate parameter.
		///If isProvOrder is true, then the medical order provNum will be set to the prescription provNum.  If isProvOrder is false, then the medical order provNum will be set to 0.
		///The MedDescript and NewCropGuid will always be copied from the prescription to the medical order and the medical order MedicationNum will be set to 0.
		///This method return the medOrderNum for the new/updated medicationPat. Unlike most medical orders this does not create an entry in the medical order table.</summary>
		public static long InsertOrUpdateMedOrderForRx(RxPat rxPat,long rxCui,bool isProvOrder) {
			long medOrderNum;
			MedicationPat medOrder=new MedicationPat();//The medication order corresponding to the prescription.
			medOrder.DateStart=rxPat.RxDate;
			medOrder.DateStop=rxPat.RxDate.AddDays(7);//Is there a way to easily calculate this information from the prescription information? The medical order will be inactive after this date.
			medOrder.MedDescript=rxPat.Drug;
			medOrder.RxCui=rxCui;
			medOrder.NewCropGuid=rxPat.NewCropGuid;
			medOrder.PatNote=rxPat.Sig;
			medOrder.PatNum=rxPat.PatNum;
			if(isProvOrder) {
				medOrder.ProvNum=rxPat.ProvNum;
				medOrder.IsCpoe=true;
			}
			MedicationPat medOrderOld=null;
			if(!String.IsNullOrEmpty(rxPat.NewCropGuid)) { //This check prevents an extra db call when the order is being created for a prescription written from inside of OD manually instead of using NewCrop.
				medOrderOld=MedicationPats.GetMedicationOrderByNewCropGuid(rxPat.NewCropGuid);
			}
			if(medOrderOld==null) {
				medOrder.IsNew=true;//Might not be necessary, but does not hurt.
				medOrderNum=MedicationPats.Insert(medOrder);
			}
			else {//The medication order was already in our database. Update it.
				medOrder.MedicationPatNum=medOrderOld.MedicationPatNum;
				MedicationPats.Update(medOrder);
				medOrderNum=medOrder.MedicationPatNum;
			}
			return medOrderNum;
		}
Beispiel #3
0
		///<summary></summary>
		public static void Update(MedicationPat Cur){
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),Cur);
				return;
			}
			Crud.MedicationPatCrud.Update(Cur);
		}
Beispiel #4
0
 public static bool IsMedActive(MedicationPat medicationPat)
 {
     if (medicationPat.DateStop.Year < 1880 || medicationPat.DateStop >= DateTime.Today)
     {
         return(true);
     }
     return(false);
 }
Beispiel #5
0
 ///<summary></summary>
 public static void Update(MedicationPat Cur)
 {
     if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
     {
         Meth.GetVoid(MethodBase.GetCurrentMethod(), Cur);
         return;
     }
     Crud.MedicationPatCrud.Update(Cur);
 }
Beispiel #6
0
 ///<summary></summary>
 public static long Insert(MedicationPat Cur)
 {
     if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
     {
         Cur.MedicationPatNum = Meth.GetLong(MethodBase.GetCurrentMethod(), Cur);
         return(Cur.MedicationPatNum);
     }
     return(Crud.MedicationPatCrud.Insert(Cur));
 }
Beispiel #7
0
 ///<summary></summary>
 public static void Delete(MedicationPat Cur)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         Meth.GetVoid(MethodBase.GetCurrentMethod(),Cur);
         return;
     }
     string command = "DELETE from medicationpat WHERE medicationpatNum = '"
         +Cur.MedicationPatNum.ToString()+"'";
     Db.NonQ(command);
     DeletedObjects.SetDeleted(DeletedObjectType.MedicationPat,Cur.MedicationPatNum);
 }
Beispiel #8
0
        ///<summary></summary>
        public static void Delete(MedicationPat Cur)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), Cur);
                return;
            }
            string command = "DELETE from medicationpat WHERE medicationpatNum = '"
                             + Cur.MedicationPatNum.ToString() + "'";

            Db.NonQ(command);
        }
Beispiel #9
0
 ///<summary></summary>
 public static void Update(MedicationPat Cur, bool canClearGuid = true)
 {
     if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
     {
         Meth.GetVoid(MethodBase.GetCurrentMethod(), Cur, canClearGuid);
         return;
     }
     if (canClearGuid && Erx.IsTwoWayIntegrated(Cur.ErxGuid))             //Reset two way integrated medications so they are resent to the eRx solution.
     {
         Cur.ErxGuid = "";
     }
     Crud.MedicationPatCrud.Update(Cur);
 }
 private void butAdd_Click(object sender,EventArgs e)
 {
     //select medication from list.  Additional meds can be added to the list from within that dlg
     FormMedications FormM=new FormMedications();
     FormM.IsSelectionMode=true;
     FormM.ShowDialog();
     if(FormM.DialogResult!=DialogResult.OK) {
         return;
     }
     MedicationPat MedicationPatCur=new MedicationPat();
     MedicationPatCur.PatNum=PatCur.PatNum;
     MedicationPatCur.MedicationNum=FormM.SelectedMedicationNum;
     MedicationPatCur.ProvNum=PatCur.PriProv;
     FormMedPat FormMP=new FormMedPat();
     FormMP.MedicationPatCur=MedicationPatCur;
     FormMP.IsNew=true;
     FormMP.ShowDialog();
     if(FormMP.DialogResult!=DialogResult.OK) {
         return;
     }
     FillMeds();
 }
Beispiel #11
0
        ///<summary>For CPOE.  Used for both manual rx and eRx through NewCrop.  Creates or updates a medical order using the given prescription information.
        ///Since rxCui is not part of the prescription, it must be passed in as a separate parameter.
        ///If isProvOrder is true, then the medical order provNum will be set to the prescription provNum.  If isProvOrder is false, then the medical order provNum will be set to 0.
        ///The MedDescript and NewCropGuid will always be copied from the prescription to the medical order and the medical order MedicationNum will be set to 0.
        ///This method return the medOrderNum for the new/updated medicationPat. Unlike most medical orders this does not create an entry in the medical order table.</summary>
        public static long InsertOrUpdateMedOrderForRx(RxPat rxPat, long rxCui, bool isProvOrder)
        {
            long          medOrderNum;
            MedicationPat medOrder = new MedicationPat();          //The medication order corresponding to the prescription.

            medOrder.DateStart   = rxPat.RxDate;
            medOrder.DateStop    = rxPat.RxDate.AddDays(7);       //Is there a way to easily calculate this information from the prescription information? The medical order will be inactive after this date.
            medOrder.MedDescript = rxPat.Drug;
            medOrder.RxCui       = rxCui;
            medOrder.NewCropGuid = rxPat.NewCropGuid;
            medOrder.PatNote     = rxPat.Sig;
            medOrder.PatNum      = rxPat.PatNum;
            if (isProvOrder)
            {
                medOrder.ProvNum = rxPat.ProvNum;
                medOrder.IsCpoe  = true;
            }
            MedicationPat medOrderOld = null;

            if (!String.IsNullOrEmpty(rxPat.NewCropGuid))              //This check prevents an extra db call when the order is being created for a prescription written from inside of OD manually instead of using NewCrop.
            {
                medOrderOld = MedicationPats.GetMedicationOrderByNewCropGuid(rxPat.NewCropGuid);
            }
            if (medOrderOld == null)
            {
                medOrder.IsNew = true;              //Might not be necessary, but does not hurt.
                medOrderNum    = MedicationPats.Insert(medOrder);
            }
            else              //The medication order was already in our database. Update it.
            {
                medOrder.MedicationPatNum = medOrderOld.MedicationPatNum;
                MedicationPats.Update(medOrder);
                medOrderNum = medOrder.MedicationPatNum;
            }
            return(medOrderNum);
        }
Beispiel #12
0
		private void butRemove_Click(object sender, System.EventArgs e) {
			if(IsNew) {
				DialogResult=DialogResult.Cancel;
				return;
			}
			if(!MsgBox.Show(this,MsgBoxButtons.OKCancel,"Remove this medication from this patient?  Patient notes will be lost.")){
				return;
			}
			MedicationPats.Delete(MedicationPatCur);
			if(MedicationPatCur.MedicationNum==0) {
				SecurityLogs.MakeLogEntry(Permissions.PatMedicationListEdit,MedicationPatCur.PatNum,MedicationPatCur.MedDescript+" deleted");
			}
			else {
				SecurityLogs.MakeLogEntry(Permissions.PatMedicationListEdit,MedicationPatCur.PatNum,Medications.GetMedication(MedicationPatCur.MedicationNum).MedName+" deleted");
			}
			MedicationPatCur=null;//This prevents other windows trying to use the medication pat after this window has closed.
			DialogResult=DialogResult.OK;
		}
Beispiel #13
0
        ///<summary>For CPOE.  Used for both manual rx and eRx through NewCrop.  Creates or updates a medical order using the given prescription information.
        ///Since rxCui is not part of the prescription, it must be passed in as a separate parameter.
        ///If isProvOrder is true, then the medical order provNum will be set to the prescription provNum.  If isProvOrder is false, then the medical order provNum will be set to 0.
        ///The MedDescript and ErxGuid will always be copied from the prescription to the medical order and the medical order MedicationNum will be set to 0.
        ///This method return the medOrderNum for the new/updated medicationPat. Unlike most medical orders this does not create an entry in the medical order table.</summary>
        public static long InsertOrUpdateMedOrderForRx(RxPat rxPat, long rxCui, bool isProvOrder)
        {
            long          medOrderNum;
            MedicationPat medOrderOld = null;

            if (!string.IsNullOrWhiteSpace(rxPat.ErxGuid))             //This check prevents an extra db call when making a new prescription manually inside OD.
            {
                medOrderOld = MedicationPats.GetMedicationOrderByErxIdAndPat(rxPat.ErxGuid, rxPat.PatNum);
            }
            MedicationPat medOrder = null;          //The medication order corresponding to the prescription.

            if (medOrderOld == null)
            {
                medOrder = new MedicationPat();
            }
            else
            {
                medOrder = medOrderOld.Clone();              //Maintain primary key and medicationnum for the update below.
            }
            medOrder.DateStart = rxPat.RxDate;
            int numDays = PrefC.GetInt(PrefName.MedDefaultStopDays);

            if (numDays != 0)
            {
                medOrder.DateStop = rxPat.RxDate.AddDays(numDays);
            }
            medOrder.MedDescript = rxPat.Drug;
            medOrder.RxCui       = rxCui;
            if (rxCui != 0)
            {
                //The customer may not have a medication entered for this RxCui the first few times they get this particular medication back from eRx.
                //Once the customer adds the medication to their medication list, then we can automatically attach the order to the medication.
                //The reason we decided not to automatically create the medication if one does not already exist is because we do not want to
                //accidentally bloat the medication list, if for example, the user has the medication entered but has not set the RxCui on it yet.
                List <Medication> listMeds = Medications.GetAllMedsByRxCui(rxCui);
                if (listMeds.Count > 0)
                {
                    medOrder.MedicationNum = listMeds[0].MedicationNum;
                }
            }
            medOrder.ErxGuid = rxPat.ErxGuid;
            medOrder.PatNote = rxPat.Sig;
            medOrder.PatNum  = rxPat.PatNum;
            if (isProvOrder)
            {
                medOrder.ProvNum = rxPat.ProvNum;
                medOrder.IsCpoe  = true;
            }
            if (medOrderOld == null)
            {
                medOrder.IsNew = true;              //Might not be necessary, but does not hurt.
                medOrderNum    = MedicationPats.Insert(medOrder);
                //If the ErxGuid has not been set, and it is a new medication, set the ErxGuid so that the medication can be sent to DoseSpot
                if (Erx.IsManualRx(rxPat.ErxGuid))
                {
                    try {
                        int medPatNumAsInt = (int)medOrderNum;
                        rxPat.ErxGuid = Erx.OpenDentalErxPrefix + medPatNumAsInt;
                        RxPats.Update(rxPat);
                    }
                    catch (Exception ex) {
                        //If we cannot downgrade a long to an int for the ErxGuid we can simply ignore trying to update the rxPat.
                        //This is because this medication would never be sent to eRx because we would attempt this downgrade again in the exact same manner.
                        ex.DoNothing();
                    }
                }
            }
            else              //The medication order was already in our database. Update it.
            {
                medOrder.MedicationPatNum = medOrderOld.MedicationPatNum;
                MedicationPats.Update(medOrder, false);               //Don't ErxGuid here, it was already purposefully set above.
                medOrderNum = medOrder.MedicationPatNum;
            }
            return(medOrderNum);
        }
Beispiel #14
0
 private void Tool_EHR_Click(bool onLoadShowOrders)
 {
     #if EHRTEST
         //so we can step through for debugging.
     /*
         EhrQuarterlyKey keyThisQ=EhrQuarterlyKeys.GetKeyThisQuarter();
         if(keyThisQ==null) {
             MessageBox.Show("No quarterly key entered for this quarter.");
             return;
         }
         if(!((FormEHR)FormOpenDental.FormEHR).QuarterlyKeyIsValid((DateTime.Today.Year-2000).ToString(),EhrQuarterlyKeys.MonthToQuarter(DateTime.Today.Month).ToString(),
             PrefC.GetString(PrefName.PracticeTitle),keyThisQ.KeyValue)) {
             MessageBox.Show("Invalid quarterly key.");
             return;
         }
     */
         ((FormEHR)FormOpenDental.FormEHR).PatNum=PatCur.PatNum;
         ((FormEHR)FormOpenDental.FormEHR).OnShowLaunchOrders=onLoadShowOrders;
         ((FormEHR)FormOpenDental.FormEHR).ShowDialog();
         if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.None) {
             //return;
         }
         if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.RxEdit) {
             FormRxEdit FormRXE=new FormRxEdit(PatCur,RxPats.GetRx(((FormEHR)FormOpenDental.FormEHR).LaunchRxNum));
             FormRXE.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);//recursive.  The only way out of the loop is EhrFormResult.None.
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.RxSelect) {
             FormRxSelect FormRS=new FormRxSelect(PatCur);
             FormRS.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.Medical) {
             FormMedical formM=new FormMedical(PatientNoteCur,PatCur);
             formM.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.PatientEdit) {
             FormPatientEdit formP=new FormPatientEdit(PatCur,FamCur);
             formP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.Online) {
             FormEhrOnlineAccess formO=new FormEhrOnlineAccess();
             formO.PatCur=PatCur;
             formO.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.MedReconcile) {
             FormMedicationReconcile FormMR=new FormMedicationReconcile();
             FormMR.PatCur=PatCur;
             FormMR.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.Referrals) {
             FormReferralsPatient formRP=new FormReferralsPatient();
             formRP.PatNum=PatCur.PatNum;
             formRP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.MedicationPatEdit) {
             FormMedPat formMP=new FormMedPat();
             formMP.MedicationPatCur=MedicationPats.GetOne(((FormEHR)FormOpenDental.FormEHR).LaunchMedicationPatNum);
             formMP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(true);
         }
         else if(((FormEHR)FormOpenDental.FormEHR).ResultOnClosing==EhrFormResult.MedicationPatNew) {
             //This cannot happen unless a provider is logged in with a valid ehr key
             FormMedications FormM=new FormMedications();
             FormM.IsSelectionMode=true;
             FormM.ShowDialog();
             if(FormM.DialogResult==DialogResult.OK) {
                 Medication med=Medications.GetMedicationFromDb(FormM.SelectedMedicationNum);
                 if(med.RxCui==0 //if the med has no Cui, it won't trigger an alert
                     || RxAlertL.DisplayAlerts(PatCur.PatNum,med.RxCui,0))//user sees alert and wants to continue
                 {
                     MedicationPat medicationPat=new MedicationPat();
                     medicationPat.PatNum=PatCur.PatNum;
                     medicationPat.MedicationNum=FormM.SelectedMedicationNum;
                     medicationPat.ProvNum=Security.CurUser.ProvNum;
                     medicationPat.DateStart=DateTime.Today;
                     FormMedPat FormMP=new FormMedPat();
                     FormMP.MedicationPatCur=medicationPat;
                     FormMP.IsNew=true;
                     FormMP.IsNewMedOrder=true;
                     FormMP.ShowDialog();
                     if(FormMP.DialogResult==DialogResult.OK) {
                         ModuleSelected(PatCur.PatNum);
                     }
                 }
             }
             Tool_EHR_Click(true);
         }
     #else
         Type type=FormOpenDental.AssemblyEHR.GetType("EHR.FormEHR");//namespace.class
         object[] args;
         EhrQuarterlyKey keyThisQ=EhrQuarterlyKeys.GetKeyThisQuarter();
         if(keyThisQ==null) {
             MessageBox.Show("No quarterly key entered for this quarter.");
             return;
         }
         args=new object[] { (DateTime.Today.Year-2000).ToString(),EhrQuarterlyKeys.MonthToQuarter(DateTime.Today.Month).ToString(),
             PrefC.GetString(PrefName.PracticeTitle),keyThisQ.KeyValue };
         if(!(bool)type.InvokeMember("QuarterlyKeyIsValid",System.Reflection.BindingFlags.InvokeMethod,null,FormOpenDental.FormEHR,args)) {
             MessageBox.Show("Invalid quarterly key.");
             return;
         }
         args=new object[] {PatCur.PatNum};
         type.InvokeMember("PatNum",System.Reflection.BindingFlags.SetField,null,FormOpenDental.FormEHR,args);
         type.InvokeMember("ShowDialog",System.Reflection.BindingFlags.InvokeMethod,null,FormOpenDental.FormEHR,null);
         if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.None) {
             return;
         }
         if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.RxEdit) {
             long launchRxNum=(long)type.InvokeMember("LaunchRxNum",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null);
             FormRxEdit FormRXE=new FormRxEdit(PatCur,RxPats.GetRx(launchRxNum));
             FormRXE.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.RxSelect) {
             FormRxSelect FormRS=new FormRxSelect(PatCur);
             FormRS.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.Medical) {
             FormMedical formM=new FormMedical(PatientNoteCur,PatCur);
             formM.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.PatientEdit) {
             FormPatientEdit formP=new FormPatientEdit(PatCur,FamCur);
             formP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.Online) {
             FormEhrOnlineAccess formO=new FormEhrOnlineAccess();
             formO.PatCur=PatCur;
             formO.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.MedReconcile) {
             FormMedicationReconcile FormMR=new FormMedicationReconcile();
             FormMR.PatCur=PatCur;
             FormMR.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.Referrals) {
             FormReferralsPatient formRP=new FormReferralsPatient();
             formRP.PatNum=PatCur.PatNum;
             formRP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(false);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.MedicationPatEdit) {
             long medicationPatNum=(long)type.InvokeMember("LaunchMedicationPatNum",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null);
             FormMedPat formMP=new FormMedPat();
             formMP.MedicationPatCur=MedicationPats.GetOne(medicationPatNum);
             formMP.ShowDialog();
             ModuleSelected(PatCur.PatNum);
             Tool_EHR_Click(true);
         }
         else if(((EhrFormResult)type.InvokeMember("ResultOnClosing",System.Reflection.BindingFlags.GetField,null,FormOpenDental.FormEHR,null))==EhrFormResult.MedicationPatNew) {
             //This cannot happen unless a provider is logged in with a valid ehr key
             FormMedications FormM=new FormMedications();
             FormM.IsSelectionMode=true;
             FormM.ShowDialog();
             if(FormM.DialogResult==DialogResult.OK) {
                 Medication med=Medications.GetMedicationFromDb(FormM.SelectedMedicationNum);
                 if(med.RxCui==0 //if the med has no Cui, it won't trigger an alert
                     || RxAlertL.DisplayAlerts(PatCur.PatNum,med.RxCui,0))//user sees alert and wants to continue
                 {
                     MedicationPat medicationPat=new MedicationPat();
                     medicationPat.PatNum=PatCur.PatNum;
                     medicationPat.MedicationNum=FormM.SelectedMedicationNum;
                     medicationPat.ProvNum=Security.CurUser.ProvNum;
                     FormMedPat FormMP=new FormMedPat();
                     FormMP.MedicationPatCur=medicationPat;
                     FormMP.IsNew=true;
                     FormMP.ShowDialog();
                     if(FormMP.DialogResult==DialogResult.OK) {
                         ModuleSelected(PatCur.PatNum);
                     }
                 }
             }
             Tool_EHR_Click(true);
         }
     #endif
 }
		private void butOK_Click(object sender,EventArgs e) {
			bool importsPresent=false;
			for(int i=0;i<Rows.Count;i++) {
				if(Rows[i].DoImport) {
					importsPresent=true;
					break;
				}
			}
			if(!importsPresent) {
				MsgBox.Show(this,"No rows are set for import.");
				return;
			}
			#region Patient Form
			if(SheetCur.SheetType==SheetTypeEnum.PatientForm) {
				bool importPriIns=false;
				bool importSecIns=false;
				for(int i=0;i<Rows.Count;i++) {
					if(!Rows[i].DoImport) {
						continue;
					}
					//Importing insurance happens later.
					if(Rows[i].FieldName.StartsWith("ins1")) {
						importPriIns=true;
						continue;
					}
					if(Rows[i].FieldName.StartsWith("ins2")) {
						importSecIns=true;
						continue;
					}
					switch(Rows[i].FieldName) {
						#region Personal
						case "LName":
							PatCur.LName=Rows[i].ImpValDisplay;
							break;
						case "FName":
							PatCur.FName=Rows[i].ImpValDisplay;
							break;
						case "MiddleI":
							PatCur.MiddleI=Rows[i].ImpValDisplay;
							break;
						case "Preferred":
							PatCur.Preferred=Rows[i].ImpValDisplay;
							break;
						case "Gender":
							PatCur.Gender=(PatientGender)Rows[i].ImpValObj;
							break;
						case "Position":
							PatCur.Position=(PatientPosition)Rows[i].ImpValObj;
							break;
						case "Birthdate":
							PatCur.Birthdate=(DateTime)Rows[i].ImpValObj;
							break;
						case "SSN":
							PatCur.SSN=Rows[i].ImpValDisplay;
							break;
						case "WkPhone":
							PatCur.WkPhone=Rows[i].ImpValDisplay;
							break;
						case "WirelessPhone":
							PatCur.WirelessPhone=Rows[i].ImpValDisplay;
							break;
						case "Email":
							PatCur.Email=Rows[i].ImpValDisplay;
							break;
						case "PreferContactMethod":
							PatCur.PreferContactMethod=(ContactMethod)Rows[i].ImpValObj;
							break;
						case "PreferConfirmMethod":
							PatCur.PreferConfirmMethod=(ContactMethod)Rows[i].ImpValObj;
							break;
						case "PreferRecallMethod":
							PatCur.PreferRecallMethod=(ContactMethod)Rows[i].ImpValObj;
							break;
						case "referredFrom":
							RefAttach ra=new RefAttach();
							ra.IsFrom=true;
							ra.ItemOrder=1;
							ra.PatNum=PatCur.PatNum;
							ra.RefDate=DateTimeOD.Today;
							ra.ReferralNum=((Referral)Rows[i].ImpValObj).ReferralNum;
							RefAttaches.Insert(ra);//no security to block this action.
							SecurityLogs.MakeLogEntry(Permissions.RefAttachAdd,PatCur.PatNum,"Referred From "+Referrals.GetNameFL(ra.ReferralNum));
							break;
						#endregion
						#region Address and Home Phone
						//AddressSameForFam already set, but not really importable by itself
						case "Address":
							PatCur.Address=Rows[i].ImpValDisplay;
							break;
						case "Address2":
							PatCur.Address2=Rows[i].ImpValDisplay;
							break;
						case "City":
							PatCur.City=Rows[i].ImpValDisplay;
							break;
						case "State":
							PatCur.State=Rows[i].ImpValDisplay;
							break;
						case "Zip":
							PatCur.Zip=Rows[i].ImpValDisplay;
							break;
						case "HmPhone":
							PatCur.HmPhone=Rows[i].ImpValDisplay;
							break;
						#endregion
					}
				}
				//Insurance importing happens before updating the patient information because there is a possibility of returning for more information.
				if(HasRequiredInsFields) {//Do not attempt to import any insurance unless they have the required fields for importing.
					#region Insurance importing
					bool primaryImported=false;
					if(importPriIns) {//A primary insurance field was flagged for importing.
						if(!ValidateAndImportInsurance(true)) {
							//Field missing or user chose to back out to correct information.
							return;//Nothing has been updated so it's okay to just return here.
						}
						primaryImported=true;
					}
					if(importSecIns) {//A secondary insurance field was flagged for importing.
						if(!ValidateAndImportInsurance(false)) {
							//Field missing or user chose to back out to correct information.
							if(primaryImported) {
								//Primary has been imported, we cannot return at this point.  Simply notify the user that secondary could not be imported correctly.
								MsgBox.Show(this,"Primary insurance was imported successfully but secondary was unable to import.");
							}
							else {//Secondary had problems importing or the user chose to back out and correct information.
								return;//Nothing has been updated so it's okay to just return here.
							}
						}
					}
					#endregion
				}
				else {//Sheet does not contain the required ins fields.
					if(importPriIns) {//The user has manually flagged a primary ins row for importing.
						MsgBox.Show(this,"Required primary insurance fields are missing on this sheet.  You cannot import primary insurance with this sheet until it contains all of required fields.  Required fields: Relationship, Subscriber, SubscriberID, CarrierName, and CarrierPhone.");
					}
					if(importSecIns) {//The user has manually flagged a secondary ins row for importing.
						MsgBox.Show(this,"Required secondary insurance fields are missing on this sheet.  You cannot import secondary insurance with this sheet until it contains all of required fields.  Required fields: Relationship, Subscriber, SubscriberID, CarrierName, and CarrierPhone.");
					}
				}
				//Patient information updating---------------------------------------------------------------------------------------------------------
				Patients.Update(PatCur,PatOld);
				if(AddressSameForFam) {
					Patients.UpdateAddressForFam(PatCur);
				}
			}
			#endregion
			#region Medical History
			else if(SheetCur.SheetType==SheetTypeEnum.MedicalHistory) {
				for(int i=0;i<Rows.Count;i++) {
					if(!Rows[i].DoImport) {
						continue;
					}
					if(Rows[i].ObjType==null) {//Should never happen.
						continue;
					}
					YN hasValue=YN.Unknown;
					if(Rows[i].ImpValDisplay=="Y") {
						hasValue=YN.Yes;
					}
					if(Rows[i].ImpValDisplay=="N") {
						hasValue=YN.No;
					}
					if(hasValue==YN.Unknown) {//Unknown, nothing to do.
						continue;
					}
					#region Allergies
					if(Rows[i].ObjType==typeof(Allergy)) {
						//Patient has this allergy in the db so just update the value.
						if(Rows[i].OldValObj!=null) {
							Allergy oldAllergy=(Allergy)Rows[i].OldValObj;
							if(hasValue==YN.Yes) {
								oldAllergy.StatusIsActive=true;
							}
							else {
								oldAllergy.StatusIsActive=false;
							}
							Allergies.Update(oldAllergy);
							continue;
						}
						if(hasValue==YN.No) {//We never import allergies with inactive status.
							continue;
						}
						//Allergy does not exist for this patient yet so create one.
						List<AllergyDef> allergyList=AllergyDefs.GetAll(false);
						SheetField allergySheet=(SheetField)Rows[i].NewValObj;
						//Find what allergy user wants to import.
						for(int j=0;j<allergyList.Count;j++) {
							if(allergyList[j].Description==allergySheet.FieldName.Remove(0,8)) {
								Allergy newAllergy=new Allergy();
								newAllergy.AllergyDefNum=allergyList[j].AllergyDefNum;
								newAllergy.PatNum=PatCur.PatNum;
								newAllergy.StatusIsActive=true;
								Allergies.Insert(newAllergy);
								break;
							}
						}
					}
					#endregion
					#region Medications
					else if(Rows[i].ObjType==typeof(MedicationPat)) {
					  //Patient has this medication in the db so leave it alone or set the stop date.
					  if(Rows[i].OldValObj!=null) {
					    //Set the stop date for the current medication(s).
					    MedicationPat oldMedPat=(MedicationPat)Rows[i].OldValObj;
					    if(hasValue==YN.Yes) {
								if(!MedicationPats.IsMedActive(oldMedPat)) {
									oldMedPat.DateStop=new DateTime(0001,1,1);//This will activate the med.
					      }
					    }
							else {
								oldMedPat.DateStop=DateTime.Today;//Set the med as inactive.
							}
							MedicationPats.Update(oldMedPat);
					    continue;
					  }
						if(hasValue==YN.No) {//Don't import medications with inactive status.
							continue;
						}
					  //Medication does not exist for this patient yet so create it.
					  List<Medication> medList=Medications.GetList("");
					  SheetField medSheet=(SheetField)Rows[i].NewValObj;
					  //Find what medication user wants to import.
					  for(int j=0;j<medList.Count;j++) {
					    if(Medications.GetDescription(medList[j].MedicationNum)==medSheet.FieldValue) {
					      MedicationPat medPat=new MedicationPat();
					      medPat.PatNum=PatCur.PatNum;
					      medPat.MedicationNum=medList[j].MedicationNum;
					      MedicationPats.Insert(medPat);
					      break;
					    }
					  }
					}
					#endregion
					#region Diseases
					else if(Rows[i].ObjType==typeof(Disease)) {
						//Patient has this problem in the db so just update the value.
						if(Rows[i].OldValObj!=null) {
							Disease oldDisease=(Disease)Rows[i].OldValObj;
							if(hasValue==YN.Yes) {
								oldDisease.ProbStatus=ProblemStatus.Active;
							}
							else {
								oldDisease.ProbStatus=ProblemStatus.Inactive;
							}
							Diseases.Update(oldDisease);
							continue;
						}
						if(hasValue==YN.No) {//Don't create new problem with inactive status.
							continue;
						}
						//Problem does not exist for this patient yet so create one.
						SheetField diseaseSheet=(SheetField)Rows[i].NewValObj;
						//Find what allergy user wants to import.
						for(int j=0;j<DiseaseDefs.List.Length;j++) {
							if(DiseaseDefs.List[j].DiseaseName==diseaseSheet.FieldName.Remove(0,8)) {
								Disease newDisease=new Disease();
								newDisease.PatNum=PatCur.PatNum;
								newDisease.DiseaseDefNum=DiseaseDefs.List[j].DiseaseDefNum;
								newDisease.ProbStatus=ProblemStatus.Active;
								Diseases.Insert(newDisease);
								break;
							}
						}
					}
					#endregion
				}
			}
			#endregion
			MsgBox.Show(this,"Done.");
			DialogResult=DialogResult.OK;
		}
Beispiel #16
0
		public static bool IsMedActive(MedicationPat medicationPat) {
			if(medicationPat.DateStop.Year<1880 || medicationPat.DateStop>=DateTime.Today) {
				return true;
			}
			return false;
		}
Beispiel #17
0
		private void butAdd_Click(object sender, System.EventArgs e) {
			//select medication from list.  Additional meds can be added to the list from within that dlg
			FormMedications FormM=new FormMedications();
			FormM.IsSelectionMode=true;
			FormM.ShowDialog();
			if(FormM.DialogResult!=DialogResult.OK){
				return;
			} 
			if(CDSPermissions.GetForUser(Security.CurUser.UserNum).ShowCDS && CDSPermissions.GetForUser(Security.CurUser.UserNum).MedicationCDS) {
				FormCDSIntervention FormCDSI=new FormCDSIntervention();
				FormCDSI.ListCDSI=EhrTriggers.TriggerMatch(Medications.GetMedication(FormM.SelectedMedicationNum),PatCur);
				FormCDSI.ShowIfRequired();
				if(FormCDSI.DialogResult==DialogResult.Abort) {
					return;//do not add medication
				}
			}
			MedicationPat MedicationPatCur=new MedicationPat();
			MedicationPatCur.PatNum=PatCur.PatNum;
			MedicationPatCur.MedicationNum=FormM.SelectedMedicationNum;
			MedicationPatCur.RxCui=Medications.GetMedication(FormM.SelectedMedicationNum).RxCui;
			MedicationPatCur.ProvNum=PatCur.PriProv;
			FormMedPat FormMP=new FormMedPat();
			FormMP.MedicationPatCur=MedicationPatCur;
			FormMP.IsNew=true;
			FormMP.ShowDialog();
			if(FormMP.DialogResult!=DialogResult.OK){
				return;
			}
			FillMeds();
		}
		private void butOK_Click(object sender,EventArgs e) {
			//validate--------------------------------------
			DateTime date;
			if(textDate.Text=="") {
				MsgBox.Show(this,"Please enter a date.");
				return;
			}
			try {
				date=DateTime.Parse(textDate.Text);
			}
			catch {
				MsgBox.Show(this,"Please fix date first.");
				return;
			}
			string codeVal="";
			string codeSys="";
			if(gridMain.GetSelectedIndex()==-1) {//no intervention code selected
				MsgBox.Show(this,"You must select a code for this intervention.");
				return;
			}
			else {
				codeVal=listCodes[gridMain.GetSelectedIndex()].CodeValue;
				codeSys=listCodes[gridMain.GetSelectedIndex()].CodeSystem;
				Description=gridMain.Rows[gridMain.GetSelectedIndex()].Cells[2].Text;
			}
			//save--------------------------------------
			//Intervention grid may contain medications, have to insert a new med if necessary and load FormMedPat for user to input data
			if(codeSys=="RXNORM") {
				//codeVal will be RxCui of medication, see if it already exists in Medication table
				Medication medCur=Medications.GetMedicationFromDbByRxCui(PIn.Long(codeVal));
				if(medCur==null) {//no med with this RxCui, create one
					medCur=new Medication();
					Medications.Insert(medCur);//so that we will have the primary key
					medCur.GenericNum=medCur.MedicationNum;
					medCur.RxCui=PIn.Long(codeVal);
					medCur.MedName=RxNorms.GetDescByRxCui(codeVal);
					Medications.Update(medCur);
					Medications.Refresh();//refresh cache to include new medication
				}
				MedicationPat medPatCur=new MedicationPat();
				medPatCur.PatNum=InterventionCur.PatNum;
				medPatCur.ProvNum=InterventionCur.ProvNum;
				medPatCur.MedicationNum=medCur.MedicationNum;
				medPatCur.RxCui=medCur.RxCui;
				medPatCur.DateStart=date;
				FormMedPat FormMP=new FormMedPat();
				FormMP.MedicationPatCur=medPatCur;
				FormMP.IsNew=true;
				FormMP.ShowDialog();
				if(FormMP.DialogResult!=DialogResult.OK) {
					return;
				}
				if(FormMP.MedicationPatCur.DateStart.Date<InterventionCur.DateEntry.AddMonths(-6).Date || FormMP.MedicationPatCur.DateStart.Date>InterventionCur.DateEntry.Date) {
					MsgBox.Show(this,"The medication order just entered is not within the 6 months prior to the date of this intervention.  You can modify the date of the medication order in the patient's medical history section.");
				}
				DialogResult=DialogResult.OK;
				return;
			}
			InterventionCur.DateEntry=date;
			InterventionCur.CodeValue=codeVal;
			InterventionCur.CodeSystem=codeSys;
			InterventionCur.Note=textNote.Text;
			string selectedCodeSet=comboCodeSet.SelectedItem.ToString().Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)[0];
			if(IsAllTypes) {//CodeSet will be set by calling function unless showing all types, in which case we need to determine which InterventionCodeSet to assign
				if(selectedCodeSet=="All") {//All types showing and set to All, have to determine which InterventionCodeSet this code belongs to
					List<string> listVSFound=new List<string>();
					foreach(KeyValuePair<string,string> kvp in dictValueCodeSets) {
						List<EhrCode> listCodes=EhrCodes.GetForValueSetOIDs(new List<string> { kvp.Value },true);
						for(int i=0;i<listCodes.Count;i++) {
							if(listCodes[i].CodeValue==codeVal) {
								listVSFound.Add(kvp.Key);
								break;
							}
						}
					}
					if(listVSFound.Count>1) {//Selected code found in more than one value set, ask the user which InterventionCodeSet to assign to this intervention
						InputBox chooseSet=new InputBox(Lan.g(this,"The selected code belongs to more than one intervention code set.  Select the code set to assign to this intervention from the list below."),listVSFound);
						if(chooseSet.ShowDialog()!=DialogResult.OK) {
							return;
						}
						if(chooseSet.comboSelection.SelectedIndex==-1) {
							MsgBox.Show(this,"You must select an intervention code set for the selected code.");
							return;
						}
						selectedCodeSet=chooseSet.comboSelection.SelectedItem.ToString().Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)[0];
					}
					else {//the code must belong to at least one value set, since count in listVSFound is not greater than 1, it must be a code from exactly one set, use that for the InterventionCodeSet
						selectedCodeSet=listVSFound[0].Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)[0];
					}
				}
				InterventionCur.CodeSet=(InterventionCodeSet)Enum.Parse(typeof(InterventionCodeSet),selectedCodeSet);
			}
			//Nutrition is used for both nutrition and physical activity counseling for children, we have to determine which set this code belongs to
			else if(InterventionCur.CodeSet==InterventionCodeSet.Nutrition && selectedCodeSet!="Nutrition") {//Nutrition set by calling form, user is showing all or physical activity codes only
				if(selectedCodeSet=="All") {//showing all codes from Nutrition and PhysicalActivity interventions, determine which set it belongs to
					//No codes exist in both code sets, so if it is not in the PhysicalActivity code set, we can safely assume this is a Nutrition intervention
					List<EhrCode> listCodes=EhrCodes.GetForValueSetOIDs(new List<string> { dictValueCodeSets[InterventionCodeSet.PhysicalActivity.ToString()+" Counseling"] },true);
					for(int i=0;i<listCodes.Count;i++) {
						if(listCodes[i].CodeValue==codeVal) {
							InterventionCur.CodeSet=InterventionCodeSet.PhysicalActivity;
							break;
						}
					}
				}
				else {
					InterventionCur.CodeSet=InterventionCodeSet.PhysicalActivity;
				}
			}
			else {
				//if not all types, and not Nutrition with All or PhysicalActivity selected in combo box, the code set sent in by calling form will remain the code set for this intervention
			}
			if(InterventionCur.IsNew) {
				Interventions.Insert(InterventionCur);
			}
			else {
				Interventions.Update(InterventionCur);
			}
			DialogResult=DialogResult.OK;
		}
Beispiel #19
0
		///<summary>Fills listMedicationPats and listMedications using the information found in the CCD document xmlDocCcd.  Does NOT insert any records into the db.</summary>
		public static void GetListMedicationPats(XmlDocument xmlDocCcd,List<MedicationPat> listMedicationPats) {
			//The length of listMedicationPats and listMedications will be the same. The information in listMedications might have duplicates.
			//Neither list of objects will be inserted into the db, so there will be no primary or foreign keys.
			//List<XmlNode> listMedicationDispenseTemplates=GetNodesByTagNameAndAttributes(xmlDocCcd,"templateId","root","2.16.840.1.113883.10.20.22.4.18");//Medication Dispense template.
			List<XmlNode> listMedicationDispenseTemplates=GetNodesByTagNameAndAttributes(xmlDocCcd,"templateId","root","2.16.840.1.113883.10.20.22.4.16");//Medication Activity template.
			List<XmlNode> listSupply=GetParentNodes(listMedicationDispenseTemplates);//POCD_HD00040.xls line 485
			for(int i=0;i<listSupply.Count;i++) {
				//We have to start fairly high in the tree so that we can get the effective time if it is available.
				List<XmlNode> xmlNodeEffectiveTimes=GetNodesByTagNameAndAttributes(listSupply[i],"effectiveTime");//POCD_HD00040.xls line 492. Not required.
				DateTime dateTimeEffectiveLow=DateTime.MinValue;
				DateTime dateTimeEffectiveHigh=DateTime.MinValue;
				if(xmlNodeEffectiveTimes.Count>0) {
					XmlNode xmlNodeEffectiveTime=xmlNodeEffectiveTimes[0];
					dateTimeEffectiveLow=GetEffectiveTimeLow(xmlNodeEffectiveTime);
					dateTimeEffectiveHigh=GetEffectiveTimeHigh(xmlNodeEffectiveTime);
				}
				List<XmlNode> listMedicationActivityTemplates=GetNodesByTagNameAndAttributes(listSupply[i],"templateId","root","2.16.840.1.113883.10.20.22.4.23");//Medication Activity template.
				List<XmlNode> listProducts=GetParentNodes(listMedicationActivityTemplates);//List of manufaturedProduct and/or manufacturedLabeledDrug. POCD_HD00040.xls line 472.
				List<XmlNode> listCodes=GetNodesByTagNameAndAttributesFromList(listProducts,"code");
				for(int j=0;j<listCodes.Count;j++) {
					XmlNode xmlNodeCode=listCodes[j];
					if(xmlNodeCode.Attributes["nullFlavor"]!=null) {
						continue;
					}
					string strCode=xmlNodeCode.Attributes["code"].Value;
					string strMedDescript=xmlNodeCode.Attributes["displayName"].Value;
					if(xmlNodeCode.Attributes["codeSystem"].Value!=strCodeSystemRxNorm) {
						continue;//We can only import RxNorms, because we have nowhere to pull in any other codes at this time (for example, SNOMED).
					}
					MedicationPat medicationPat=new MedicationPat();
					medicationPat.IsNew=true;//Needed for reconcile window to know this record is not in the db yet.
					medicationPat.RxCui=PIn.Long(strCode);
					medicationPat.MedDescript=strMedDescript;
					medicationPat.DateStart=dateTimeEffectiveLow;
					medicationPat.DateStop=dateTimeEffectiveHigh;
					listMedicationPats.Add(medicationPat);
				}
			}
			List<MedicationPat> listMedicationPatsNoDupes=new List<MedicationPat>();
			bool isDupe;
			for(int index=0;index<listMedicationPats.Count;index++) {
				isDupe=false;
				for(int index2=0;index2<listMedicationPatsNoDupes.Count;index2++) {
					if(listMedicationPatsNoDupes[index2].RxCui==listMedicationPats[index].RxCui) {
						isDupe=true;
						break;
					}
				}
				if(!isDupe) {
					listMedicationPatsNoDupes.Add(listMedicationPats[index]);
				}
			}
			listMedicationPats.Clear();
			for(int dupeIndex=0;dupeIndex<listMedicationPatsNoDupes.Count;dupeIndex++) {
				listMedicationPats.Add(listMedicationPatsNoDupes[dupeIndex]);
			}
		}
Beispiel #20
0
		///<summary>Helper for GenerateCCD().</summary>
		private void GenerateCcdSectionMedications(bool hasMedication) {
			_w.WriteComment(@"
=====================================================================================================
Medications
=====================================================================================================");
			List<MedicationPat> listMedPatsFiltered=new List<MedicationPat>();
			if(!hasMedication) {
				listMedPatsFiltered=new List<MedicationPat>();
			}
			else {
				listMedPatsFiltered=_listMedPatsFiltered;
			}
			Start("component");
			Start("section");
			TemplateId("2.16.840.1.113883.10.20.22.2.1.1");//Medication section with coded entries required.
			_w.WriteComment("Medications section template");
			StartAndEnd("code","code","10160-0","codeSystem",strCodeSystemLoinc,"codeSystemName",strCodeSystemNameLoinc,"displayName","History of medication use");
			_w.WriteElementString("title","Medications");
			Start("text");//The following text will be parsed as html with a style sheet to be human readable.
			if(listMedPatsFiltered.Count>0 && hasMedication) {
				Start("table","width","100%","border","1");
				Start("thead");
				Start("tr");
				_w.WriteElementString("th","Medication");
				_w.WriteElementString("th","Directions");
				_w.WriteElementString("th","Start Date");
				_w.WriteElementString("th","End Date");
				_w.WriteElementString("th","Status");
				_w.WriteElementString("th","Indications");
				_w.WriteElementString("th","Fill Instructions");
				End("tr");
				End("thead");
				Start("tbody");
				for(int i=0;i<listMedPatsFiltered.Count;i++) {
					string strMedName=listMedPatsFiltered[i].MedDescript;
					if(listMedPatsFiltered[i].MedicationNum!=0) {
						strMedName=Medications.GetNameOnly(listMedPatsFiltered[i].MedicationNum);
					}
					Start("tr");
					if(listMedPatsFiltered[i].RxCui==0) {
						_w.WriteElementString("td","");
					}
					else {
						_w.WriteElementString("td",listMedPatsFiltered[i].RxCui+" - "+strMedName);//Medication
					}
					_w.WriteElementString("td",listMedPatsFiltered[i].PatNote);//Directions
					if(listMedPatsFiltered[i].DateStart.Year<1880) {
						_w.WriteElementString("td","");//Directions
					}
					else {
						DateText("td",listMedPatsFiltered[i].DateStart);//Start Date
					}
					if(listMedPatsFiltered[i].DateStop.Year<1880) {
						_w.WriteElementString("td","");//Directions
					}
					else {
						DateText("td",listMedPatsFiltered[i].DateStop);//End Date
					}
					_w.WriteElementString("td",MedicationPats.IsMedActive(listMedPatsFiltered[i])?"Active":"Inactive");//Status
					_w.WriteElementString("td","");//Indications (The conditions which make the medication necessary). We do not record this information anywhere.
					_w.WriteElementString("td","");//Fill Instructions (Generic substitution allowed or not). We do not record this information anywhere.
					End("tr");
				}
				End("tbody");
				End("table");
			}
			else {
				_w.WriteString("None");
			}
			End("text");
			if(listMedPatsFiltered.Count==0) {//If there are no entries in the filtered list, then we want to add a dummy entry since at least one is required.
				MedicationPat medPat=new MedicationPat();
				listMedPatsFiltered.Add(medPat);
			}
			for(int i=0;i<listMedPatsFiltered.Count;i++) {
				string strMedName="";
				if(listMedPatsFiltered[i].MedDescript!=null) {
					strMedName=listMedPatsFiltered[i].MedDescript;//This might be blank, for example not from NewCrop.
				}
				if(listMedPatsFiltered[i].MedicationNum!=0) {//If NewCrop, this will be 0.  Also might be zero in the future when we start allowing freeform medications.
					strMedName=Medications.GetNameOnly(listMedPatsFiltered[i].MedicationNum);
				}
				Start("entry","typeCode","DRIV");
				Start("substanceAdministration","classCode","SBADM","moodCode","EVN");
				TemplateId("2.16.840.1.113883.10.20.22.4.16");
				_w.WriteComment("Medication activity template");
				Guid();
				if(String.IsNullOrEmpty(listMedPatsFiltered[i].PatNote)) {
					StartAndEnd("text","nullFlavor","UNK");
				}
				else {
					_w.WriteElementString("text",listMedPatsFiltered[i].PatNote);
				}
				StartAndEnd("statusCode","code","active");
				Start("effectiveTime");
				_w.WriteAttributeString("xsi","type",null,"IVL_TS");
				if(listMedPatsFiltered[i].DateStart.Year<1880) {
					StartAndEnd("low","nullFlavor","UNK");
				}
				else {
					DateElement("low",listMedPatsFiltered[i].DateStart);//Only one of these dates can be null, because of our filter above.
				}
				if(listMedPatsFiltered[i].DateStop.Year<1880) {
					StartAndEnd("high","nullFlavor","UNK");
				}
				else {
					DateElement("high",listMedPatsFiltered[i].DateStop);//Only one of these dates can be null, because of our filter above.
				}
				End("effectiveTime");
				Start("consumable");
				Start("manufacturedProduct","classCode","MANU");
				TemplateId("2.16.840.1.113883.10.20.22.4.23");//Medication Information template.
				Guid();
				Start("manufacturedMaterial");
				//The code must be an RxNorm.
				if(listMedPatsFiltered[i].RxCui==0) {
					Start("code","nullFlavor","UNK");
				}
				else {
					Start("code","code",listMedPatsFiltered[i].RxCui.ToString(),"codeSystem",strCodeSystemRxNorm,"displayName",strMedName,"codeSystemName",strCodeSystemNameRxNorm);
				}
				End("code");
				End("manufacturedMaterial");
				End("manufacturedProduct");
				End("consumable");
				End("substanceAdministration");
				End("entry");
			}
			End("section");
			End("component");
		}