public static long Insert(EmailAttach attach) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				attach.EmailAttachNum=Meth.GetLong(MethodBase.GetCurrentMethod(),attach);
				return attach.EmailAttachNum;
			}
			return Crud.EmailAttachCrud.Insert(attach);
		}
Example #2
0
 public static long Insert(EmailAttach attach)
 {
     if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
     {
         attach.EmailAttachNum = Meth.GetLong(MethodBase.GetCurrentMethod(), attach);
         return(attach.EmailAttachNum);
     }
     return(Crud.EmailAttachCrud.Insert(attach));
 }
Example #3
0
		///<summary>Throws exceptions.  Creates a new file inside of the email attachment path (inside OpenDentImages) and returns an EmailAttach object referencing the new file.  If isOutbound is true, then the file will be saved to the "Out" subfolder, otherwise the file will be saved to the "In" subfolder.  The displayFileName will always contain valid file name characters, because it is either a hard coded value or is based on an existing valid file name.  If a file already exists matching the actualFileName, then an exception will occur.  Set actualFileName to empty string to generate a unique actual file name.  If the actual file name is generated, then actual file name will end with the displayFileName, so that the actual files are easier to locate and have the same file extension as the displayedFileName.</summary>
		public static EmailAttach CreateAttach(string displayedFileName,string actualFileName,byte[] arrayData,bool isOutbound) {
			//No need to check RemotingRole; no call to db.
			EmailAttach emailAttach=new EmailAttach();
			emailAttach.DisplayedFileName=displayedFileName;
			if(String.IsNullOrEmpty(emailAttach.DisplayedFileName)) {
				//This could only happen for malformed incoming emails, but should not happen.  Name uniqueness is virtually guaranteed below.
				//The actual file name will not have an extension, so the user will be asked to pick the program to open the attachment with when
				//the attachment is double-clicked.
				emailAttach.DisplayedFileName="attach";
			}
			string attachDir=GetAttachPath();
			string subDir="In";
			if(isOutbound) {
				subDir="Out";
			}
			if(!Directory.Exists(ODFileUtils.CombinePaths(attachDir,subDir))) {
				Directory.CreateDirectory(ODFileUtils.CombinePaths(attachDir,subDir));
			}
			if(String.IsNullOrEmpty(actualFileName)) {
				while(String.IsNullOrEmpty(emailAttach.ActualFileName) || File.Exists(ODFileUtils.CombinePaths(attachDir,emailAttach.ActualFileName))) {
					//Display name is tacked onto actual file name last as to ensure file extensions are the same.
					emailAttach.ActualFileName=ODFileUtils.CombinePaths(subDir,
						DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()
							+"_"+MiscUtils.CreateRandomAlphaNumericString(4)+"_"+emailAttach.DisplayedFileName);
				}
			}
			else {
				//The caller wants a specific actualFileName.  Use the given name as is.
				emailAttach.ActualFileName=ODFileUtils.CombinePaths(subDir,actualFileName);
			}
			string attachFilePath=ODFileUtils.CombinePaths(attachDir,emailAttach.ActualFileName);
			if(File.Exists(attachFilePath)) {
				throw new ApplicationException("Email attachment could not be saved because a file with the same name already exists.");
			}
			try {
				File.WriteAllBytes(attachFilePath,arrayData);
			}
			catch(Exception ex) {
				try {
					if(File.Exists(attachFilePath)) {
						File.Delete(attachFilePath);
					}
				}
				catch {
					//We tried our best to delete the file, and there is nothing else to try.
				}
				throw ex;//Show the initial error message, even if the Delete() failed.
			}
			return emailAttach;
		}
Example #4
0
		internal static void Insert(EmailAttach attach){
			if(PrefB.RandomKeys) {
				attach.EmailAttachNum=MiscDataB.GetKey("emailattach","EmailAttachNum");
			}
			string command= "INSERT INTO emailattach (";
			if(PrefB.RandomKeys) {
				command+="EmailAttachNum,";
			}
			command+="EmailMessageNum, DisplayedFileName, ActualFileName) VALUES(";
			if(PrefB.RandomKeys) {
				command+="'"+POut.PInt(attach.EmailAttachNum)+"', ";
			}
			command+=
				 "'"+POut.PInt   (attach.EmailMessageNum)+"', "
				+"'"+POut.PString(attach.DisplayedFileName)+"', "
				+"'"+POut.PString(attach.ActualFileName)+"')";
			//MessageBox.Show(cmd.CommandText);
			DataConnection dcon=new DataConnection();
			dcon.NonQ(command);
		}
Example #5
0
		/// <summary>Saves the statement.  Attaches a pdf to it by creating a doc object.  Prints it or emails it.  </summary>
		private void PrintStatement(Statement stmt) {
			Cursor=Cursors.WaitCursor;
			Statements.Insert(stmt);
			FormRpStatement FormST=new FormRpStatement();
			DataSet dataSet=AccountModules.GetStatementDataSet(stmt);
			FormST.CreateStatementPdf(stmt,PatCur,FamCur,dataSet);
			//if(ImageStore.UpdatePatient == null){
			//	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
			//}
			Patient guar=Patients.GetPat(stmt.PatNum);
			string guarFolder=ImageStore.GetPatientFolder(guar,ImageStore.GetPreferredAtoZpath());
			//OpenDental.Imaging.ImageStoreBase imageStore = OpenDental.Imaging.ImageStore.GetImageStore(guar);
			if(stmt.Mode_==StatementMode.Email) {
				string attachPath=EmailMessages.GetEmailAttachPath();
				Random rnd=new Random();
				string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
				string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
				File.Copy(ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder),filePathAndName);
				//Process.Start(filePathAndName);
				EmailMessage message=Statements.GetEmailMessageForStatement(stmt,guar);
				EmailAttach attach=new EmailAttach();
				attach.DisplayedFileName="Statement.pdf";
				attach.ActualFileName=fileName;
				message.Attachments.Add(attach);
				FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
				FormE.IsNew=true;
				FormE.ShowDialog();
				//If user clicked delete or cancel, delete pdf and statement
				if(FormE.DialogResult==DialogResult.Cancel) {
					Patient pat;
					string patFolder;
					if(stmt.DocNum!=0) {
						//delete the pdf
						pat=Patients.GetPat(stmt.PatNum);
						patFolder=ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath());
						List<Document> listdocs=new List<Document>();
						listdocs.Add(Documents.GetByNum(stmt.DocNum));
						try {  
							ImageStore.DeleteDocuments(listdocs,patFolder);
						}
						catch {  //Image could not be deleted, in use.
							//This should never get hit because the file was created by this user within this method.  
							//If the doc cannot be deleted, then we will not stop them, they will have to manually delete it from the images module.
						}
					}
					//delete statement
					Procedures.DetachFromInvoice(stmt.StatementNum);
					Adjustments.DetachFromInvoice(stmt.StatementNum);
					Statements.DeleteObject(stmt);
				}
			}
			else {//not email
				#if DEBUG
					//don't bother to check valid path because it's just debug.
					string imgPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder);
					DateTime now=DateTime.Now;
					while(DateTime.Now<now.AddSeconds(5) && !File.Exists(imgPath)) {//wait up to 5 seconds.
						Application.DoEvents();
					}
					Process.Start(imgPath);
				#else
					FormST.PrintStatement(stmt,false,dataSet,FamCur,PatCur);
				#endif
			}
			Cursor=Cursors.Default;
		}
Example #6
0
File: EhrCCD.cs Project: mnisl/OD
		public static bool IsCcdEmailAttachment(EmailAttach emailAttach) {
			string strFilePathAttach=ODFileUtils.CombinePaths(EmailAttaches.GetAttachPath(),emailAttach.ActualFileName);
			if(Path.GetExtension(strFilePathAttach).ToLower()!=".xml") {
				return false;
			}
			string strTextXml=File.ReadAllText(strFilePathAttach);
			if(!EhrCCD.IsCCD(strTextXml)) {
				return false;
			}
			return true;
		}
Example #7
0
		/// <summary>Also displays the dialog for the email.  Must have already created and attached the pdf.  Returns false if it could not create the email.</summary>
		private bool CreateEmailMessage(){
			string attachPath=EmailAttaches.GetAttachPath();
			Random rnd=new Random();
			string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
			string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
			if(!PrefC.AtoZfolderUsed){
				MsgBox.Show(this,"Could not create email because no AtoZ folder.");
				return false;
			}
			Patient pat=Patients.GetPat(StmtCur.PatNum);
			string oldPath=ODFileUtils.CombinePaths(ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath()),Documents.GetByNum(StmtCur.DocNum).FileName);
			File.Copy(oldPath,filePathAndName);//
			//Process.Start(filePathAndName);
			EmailMessage message=Statements.GetEmailMessageForStatement(StmtCur,pat);
			EmailAttach attach=new EmailAttach();
			attach.DisplayedFileName="Statement.pdf";
			attach.ActualFileName=fileName;
			message.Attachments.Add(attach);
			FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
			FormE.IsNew=true;
			FormE.ShowDialog();
			if(FormE.DialogResult==DialogResult.OK){
				return true;
			}
			return false;
		}
		private void butAttach_Click(object sender,EventArgs e) {
			OpenFileDialog dlg=new OpenFileDialog();
			dlg.Multiselect=true;
			//PatCur=Patients.GetPat(MessageCur.PatNum);
			if(_patCur.ImageFolder!=""){
				if(PrefC.AtoZfolderUsed){
					dlg.InitialDirectory=ODFileUtils.CombinePaths(ImageStore.GetPreferredAtoZpath(),
																																				_patCur.ImageFolder.Substring(0,1).ToUpper(),
																																				_patCur.ImageFolder);
				}
				else{
					//Use the OS default directory for this type of file viewer.
					dlg.InitialDirectory="";
				}
			}
			if(dlg.ShowDialog()!=DialogResult.OK){
				return;
			}
			Random rnd=new Random();
			string newName;
			EmailAttach attach;
			string attachPath=EmailMessages.GetEmailAttachPath();
			try{
				for(int i=0;i<dlg.FileNames.Length;i++){
					//copy the file
					newName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+Path.GetExtension(dlg.FileNames[i]);
					File.Copy(dlg.FileNames[i],ODFileUtils.CombinePaths(attachPath,newName));
					//create the attachment
					attach=new EmailAttach();
					attach.DisplayedFileName=Path.GetFileName(dlg.FileNames[i]);
					attach.ActualFileName=newName;
					MessageCur.Attachments.Add(attach);
				}
			}
			catch(Exception ex){
				MessageBox.Show(ex.Message);
			}
			FillAttachments();
		}
Example #9
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
 }
Example #10
0
		private void ToolBarMainEmail_Click() {
			if(PrefC.GetBool(PrefName.FuchsOptionsOn)) {
				if(checkShowDiscount.Checked || checkShowIns.Checked) {
					if(MessageBox.Show(this,string.Format(Lan.g(this,"Do you want to remove insurance estimates and PPO discounts from e-mailed treatment plan?")),"Open Dental",MessageBoxButtons.YesNo,MessageBoxIcon.Question) != DialogResult.No) {
						checkShowDiscount.Checked=false;
						checkShowIns.Checked=false;
						FillMain();
					}
				}
			}
			PrepImageForPrinting();
			string attachPath=EmailMessages.GetEmailAttachPath();
			Random rnd=new Random();
			string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
			string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
			MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer=new MigraDoc.Rendering.PdfDocumentRenderer(true,PdfFontEmbedding.Always);
			pdfRenderer.Document=CreateDocument();
			pdfRenderer.RenderDocument();
			pdfRenderer.PdfDocument.Save(filePathAndName);
			//Process.Start(filePathAndName);
			EmailMessage message=new EmailMessage();
			message.PatNum=PatCur.PatNum;
			message.ToAddress=PatCur.Email;
			message.FromAddress=EmailAddresses.GetByClinic(PatCur.ClinicNum).SenderAddress;
			message.Subject=Lan.g(this,"Treatment Plan");
			EmailAttach attach=new EmailAttach();
			attach.DisplayedFileName="TreatmentPlan.pdf";
			attach.ActualFileName=fileName;
			message.Attachments.Add(attach);
			FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
			FormE.IsNew=true;
			FormE.ShowDialog();
			//if(FormE.DialogResult==DialogResult.OK) {
			//	RefreshCurrentModule();
			//}
		}
Example #11
0
		private void PrintStatementSheets(Statement stmt) {
			Cursor=Cursors.WaitCursor;
			Statements.Insert(stmt);
			SheetDef sheetDef=SheetUtil.GetStatementSheetDef();
			Sheet sheet=SheetUtil.CreateSheet(sheetDef,stmt.PatNum,stmt.HidePayment);
			SheetFiller.FillFields(sheet,stmt);
			SheetUtil.CalculateHeights(sheet,Graphics.FromImage(new Bitmap(sheet.HeightPage,sheet.WidthPage)),stmt);
			string tempPath=CodeBase.ODFileUtils.CombinePaths(PrefL.GetTempFolderPath(),stmt.PatNum.ToString()+".pdf");
			SheetPrinting.CreatePdf(sheet,tempPath,stmt);//We don't delete this from temp folder
			long category=0;
			for(int i=0;i<DefC.Short[(int)DefCat.ImageCats].Length;i++) {
				if(Regex.IsMatch(DefC.Short[(int)DefCat.ImageCats][i].ItemValue,@"S")) {
					category=DefC.Short[(int)DefCat.ImageCats][i].DefNum;
					break;
				}
			}
			if(category==0) {
				category=DefC.Short[(int)DefCat.ImageCats][0].DefNum;//put it in the first category.
			}
			//create doc--------------------------------------------------------------------------------------
			OpenDentBusiness.Document docc=null;
			try {
				docc=ImageStore.Import(tempPath,category,Patients.GetPat(stmt.PatNum));
			}
			catch {
				MsgBox.Show(this,"Error saving document.");
				//this.Cursor=Cursors.Default;
				return;
			}
			docc.ImgType=ImageType.Document;
			docc.DateCreated=stmt.DateSent;
			Documents.Update(docc);
			stmt.DocNum=docc.DocNum;//this signals the calling class that the pdf was created successfully.
			Statements.AttachDoc(stmt.StatementNum,docc.DocNum);
			//if(ImageStore.UpdatePatient == null){
			//	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
			//}
			Patient guar=Patients.GetPat(stmt.PatNum);
			string guarFolder=ImageStore.GetPatientFolder(guar,ImageStore.GetPreferredAtoZpath());
			//OpenDental.Imaging.ImageStoreBase imageStore = OpenDental.Imaging.ImageStore.GetImageStore(guar);
			if(stmt.Mode_==StatementMode.Email) {
				if(!Security.IsAuthorized(Permissions.EmailSend)) {
					Cursor=Cursors.Default;
					return;
				}
				string attachPath=EmailAttaches.GetAttachPath();
				Random rnd=new Random();
				string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
				string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
				File.Copy(ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder),filePathAndName);
				//Process.Start(filePathAndName);
				EmailMessage message=Statements.GetEmailMessageForStatement(stmt,guar);
				EmailAttach attach=new EmailAttach();
				attach.DisplayedFileName="Statement.pdf";
				attach.ActualFileName=fileName;
				message.Attachments.Add(attach);
				FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
				FormE.IsNew=true;
				FormE.ShowDialog();
				//If user clicked delete or cancel, delete pdf and statement
				if(FormE.DialogResult==DialogResult.Cancel) {
					Patient pat;
					string patFolder;
					if(stmt.DocNum!=0) {
						//delete the pdf
						pat=Patients.GetPat(stmt.PatNum);
						patFolder=ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath());
						List<Document> listdocs=new List<Document>();
						listdocs.Add(Documents.GetByNum(stmt.DocNum));
						try {
							ImageStore.DeleteDocuments(listdocs,patFolder);
						}
						catch {  //Image could not be deleted, in use.
							//This should never get hit because the file was created by this user within this method.  
							//If the doc cannot be deleted, then we will not stop them, they will have to manually delete it from the images module.
						}
					}
					//delete statement
					Statements.Delete(stmt);
				}
			}
			else {//not email
#if DEBUG
				//don't bother to check valid path because it's just debug.
				string imgPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder);
				DateTime now=DateTime.Now;
				while(DateTime.Now<now.AddSeconds(5) && !File.Exists(imgPath)) {//wait up to 5 seconds.
					Application.DoEvents();
				}
				Process.Start(imgPath);
#else
				//Thread thread=new Thread(new ParameterizedThreadStart(SheetPrinting.PrintStatement));
				//thread.Start(new List<object> { sheetDef,stmt,tempPath });
				//NOTE: This is printing a "fresh" GDI+ version of the statment which is ever so slightly different than the PDFSharp statment that was saved to disk.
				sheet=SheetUtil.CreateSheet(sheetDef,stmt.PatNum,stmt.HidePayment);
				SheetFiller.FillFields(sheet,stmt);
				SheetUtil.CalculateHeights(sheet,Graphics.FromImage(new Bitmap(sheet.HeightPage,sheet.WidthPage)),stmt);
				SheetPrinting.Print(sheet,1,false,stmt);//use GDI+ printing, which is slightly different than the pdf.
#endif
			}
			Cursor=Cursors.Default;

		}
Example #12
0
 private void butPrint_Click(object sender,EventArgs e)
 {
     if(!TryToSaveData()){
         return;
     }
     SheetCur=Sheets.GetSheet(SheetCur.SheetNum);
     //whether this is a new sheet, or one pulled from the database,
     //it will have the extra parameter we are looking for.
     //A new sheet will also have a PatNum parameter which we will ignore.
     FormSheetOutputFormat FormS=new FormSheetOutputFormat();
     if(SheetCur.SheetType==SheetTypeEnum.ReferralSlip
         || SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
     {
         FormS.PaperCopies=2;
     }
     else{
         FormS.PaperCopies=1;
     }
     if(SheetCur.PatNum!=0
         && SheetCur.SheetType!=SheetTypeEnum.DepositSlip)
     {
         Patient pat=Patients.GetPat(SheetCur.PatNum);
         if(SheetCur.SheetType==SheetTypeEnum.LabSlip) {
             FormS.IsForLab=true;//Changes label to "E-mail to Lab:"
         }
         else if(pat.Email!="") {
             FormS.EmailPatOrLabAddress=pat.Email;
             FormS.EmailPatOrLab=true;
             FormS.PaperCopies--;
         }
     }
     Referral referral=null;
     if(SheetCur.SheetType==SheetTypeEnum.ReferralSlip
         || SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
     {
         FormS.Email2Visible=true;
         SheetParameter parameter=SheetParameter.GetParamByName(SheetCur.Parameters,"ReferralNum");
         if(parameter==null){//it can be null sometimes because of old bug in db.
             FormS.Email2Visible=false;//prevents trying to attach email to nonexistent referral.
         }
         else{
             long referralNum=PIn.Long(parameter.ParamValue.ToString());
             referral=Referrals.GetReferral(referralNum);
             if(referral.EMail!=""){
                 FormS.Email2Address=referral.EMail;
                 FormS.Email2=true;
                 FormS.PaperCopies--;
             }
         }
     }
     else{
         FormS.Email2Visible=false;
     }
     FormS.ShowDialog();
     if(FormS.DialogResult!=DialogResult.OK){
         return;
     }
     if(FormS.PaperCopies>0){
         SheetPrinting.Print(SheetCur,FormS.PaperCopies,RxIsControlled);
     }
     EmailMessage message;
     Random rnd=new Random();
     string attachPath=FormEmailMessageEdit.GetAttachPath();
     string fileName;
     string filePathAndName;
     //Graphics g=this.CreateGraphics();
     if(FormS.EmailPatOrLab){
         fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
         filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
         SheetPrinting.CreatePdf(SheetCur,filePathAndName);
         //Process.Start(filePathAndName);
         message=new EmailMessage();
         message.PatNum=SheetCur.PatNum;
         message.ToAddress=FormS.EmailPatOrLabAddress;
         message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
         message.Subject=SheetCur.Description.ToString();//this could be improved
         EmailAttach attach=new EmailAttach();
         string shortFileName=Regex.Replace(SheetCur.Description.ToString(), @"[^\w'@-_()&]", "");
         attach.DisplayedFileName=shortFileName+".pdf";
         attach.ActualFileName=fileName;
         message.Attachments.Add(attach);
         FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
         FormE.IsNew=true;
         FormE.ShowDialog();
     }
     if((SheetCur.SheetType==SheetTypeEnum.ReferralSlip
         || SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
         && FormS.Email2)
     {
         //email referral
         fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
         filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
         SheetPrinting.CreatePdf(SheetCur,filePathAndName);
         //Process.Start(filePathAndName);
         message=new EmailMessage();
         message.PatNum=SheetCur.PatNum;
         message.ToAddress=FormS.Email2Address;
         message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
         message.Subject=SheetCur.Description.ToString()+" to "+Referrals.GetNameFL(referral.ReferralNum);//this could be improved
         EmailAttach attach=new EmailAttach();
         string shortFileName=Regex.Replace(SheetCur.Description.ToString(), @"[^\w,'@-_()&]", "");
         attach.DisplayedFileName=shortFileName+".pdf";
         attach.ActualFileName=fileName;
         message.Attachments.Add(attach);
         FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
         FormE.IsNew=true;
         FormE.ShowDialog();
     }
     //g.Dispose();
     DialogResult=DialogResult.OK;
 }
Example #13
0
 /// <summary>Also displays the dialog for the email.  Must have already created and attached the pdf.  Returns false if it could not create the email.</summary>
 private bool CreateEmailMessage()
 {
     string attachPath=FormEmailMessageEdit.GetAttachPath();
     Random rnd=new Random();
     string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
     string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
     if(!PrefC.UsingAtoZfolder){
         MsgBox.Show(this,"Could not create email because no AtoZ folder.");
         return false;
     }
     Patient pat=Patients.GetPat(StmtCur.PatNum);
     string oldPath=ODFileUtils.CombinePaths(ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath()),Documents.GetByNum(StmtCur.DocNum).FileName);
     File.Copy(oldPath,filePathAndName);//
     //Process.Start(filePathAndName);
     EmailMessage 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;
     EmailAttach attach=new EmailAttach();
     attach.DisplayedFileName="Statement.pdf";
     attach.ActualFileName=fileName;
     message.Attachments.Add(attach);
     FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
     FormE.IsNew=true;
     FormE.ShowDialog();
     if(FormE.DialogResult==DialogResult.OK){
         return true;
     }
     return false;
 }
Example #14
0
		///<summary>Creates a new file inside of the email attachment path (inside OpenDentImages) and returns an EmailAttach object referencing the new file, but with EmailMessageNum set to zero so it can be set later.</summary>
		private static EmailAttach CreateAttachInAttachPath(string strAttachFileName,string strAttachText) {
			//No need to check RemotingRole; no call to db.
			string strAttachFileNameAdjusted=strAttachFileName;
			if(String.IsNullOrEmpty(strAttachFileName)) {
				strAttachFileNameAdjusted=MiscUtils.CreateRandomAlphaNumericString(8)+".txt";//just in case
			}
			string strAttachPath=GetEmailAttachPath();
			string strAttachFile=ODFileUtils.CombinePaths(strAttachPath,DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+"_"+strAttachFileNameAdjusted);
			while(File.Exists(strAttachFile)) {
				strAttachFile=ODFileUtils.CombinePaths(strAttachPath,DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+"_"+strAttachFileNameAdjusted);
			}
			File.WriteAllText(strAttachFile,strAttachText);
			EmailAttach emailAttach=new EmailAttach();
			emailAttach.ActualFileName=Path.GetFileName(strAttachFile);
			emailAttach.DisplayedFileName=Path.GetFileName(strAttachFileNameAdjusted);//shorter name, excludes date and time stamp info.
			return emailAttach;
		}
Example #15
0
 /// <summary>Saves the statement.  Attaches a pdf to it by creating a doc object.  Prints it or emails it.  </summary>
 private void PrintStatement(Statement stmt)
 {
     Cursor=Cursors.WaitCursor;
     Statements.Insert(stmt);
     FormRpStatement FormST=new FormRpStatement();
     DataSet dataSet=AccountModules.GetStatementDataSet(stmt);
     FormST.CreateStatementPdf(stmt,PatCur,FamCur,dataSet);
     //if(ImageStore.UpdatePatient == null){
     //	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
     //}
     Patient guar=Patients.GetPat(stmt.PatNum);
     string guarFolder=ImageStore.GetPatientFolder(guar,ImageStore.GetPreferredAtoZpath());
     //OpenDental.Imaging.ImageStoreBase imageStore = OpenDental.Imaging.ImageStore.GetImageStore(guar);
     if(stmt.Mode_==StatementMode.Email){
         string attachPath=FormEmailMessageEdit.GetAttachPath();
         Random rnd=new Random();
         string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
         string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
         File.Copy(ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder),filePathAndName);
         //Process.Start(filePathAndName);
         EmailMessage message=new EmailMessage();
         message.PatNum=guar.PatNum;
         message.ToAddress=guar.Email;
         message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
         string str;
         str=PrefC.GetString(PrefName.BillingEmailSubject);
         str=str.Replace("[nameF]",guar.GetNameFirst());
         str=str.Replace("[nameFL]",guar.GetNameFL());
         str=str.Replace("[namePref]",guar.Preferred);
         str=str.Replace("[PatNum]",guar.PatNum.ToString());
         message.Subject=str;
         str=PrefC.GetString(PrefName.BillingEmailBodyText);
         str=str.Replace("[nameF]",guar.GetNameFirst());
         str=str.Replace("[nameFL]",guar.GetNameFL());
         str=str.Replace("[namePref]",guar.Preferred);
         str=str.Replace("[PatNum]",guar.PatNum.ToString());
         message.BodyText=str;
         EmailAttach attach=new EmailAttach();
         attach.DisplayedFileName="Statement.pdf";
         attach.ActualFileName=fileName;
         message.Attachments.Add(attach);
         FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
         FormE.IsNew=true;
         FormE.ShowDialog();
     }
     else{
         #if DEBUG
             //don't bother to check valid path because it's just debug.
             string imgPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),guarFolder);
             DateTime now=DateTime.Now;
             while(DateTime.Now<now.AddSeconds(5) && !File.Exists(imgPath)) {//wait up to 5 seconds.
                 Application.DoEvents();
             }
             Process.Start(imgPath);
         #else
             FormST.PrintStatement(stmt,false,dataSet,FamCur,PatCur);
         #endif
     }
     Cursor=Cursors.Default;
 }
Example #16
0
		///<summary>Can throw an exception if there is a permission issue saving the file.</summary>
		public static void CreateAttachmentFromText(EmailMessage emailMessage,string strAttachText,string strDisplayFileName) {
			//No need to check RemotingRole; no call to db.
			Random rnd=new Random();
			EmailAttach emailAttach;
			//create the attachment
			emailAttach=new EmailAttach();
			emailAttach.DisplayedFileName=strDisplayFileName;
			emailAttach.ActualFileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+Path.GetExtension(strDisplayFileName);//To make unique.
			string strAttachFilePath=ODFileUtils.CombinePaths(EmailMessages.GetEmailAttachPath(),emailAttach.ActualFileName);
			File.WriteAllText(strAttachFilePath,strAttachText);
			emailMessage.Attachments.Add(emailAttach);
		}
Example #17
0
        ///<summary>Throws exceptions.  Creates a new file inside of the email attachment path (inside OpenDentImages) and returns an EmailAttach object
        ///referencing the new file.  If isOutbound is true, then the file will be saved to the "Out" subfolder, otherwise the file will be saved to the
        ///"In" subfolder.  The displayFileName will always contain valid file name characters, because it is either a hard coded value or is based on an
        ///existing valid file name.  If a file already exists matching the actualFileName, then an exception will occur.  Set actualFileName to empty
        ///string to generate a unique actual file name.  If the actual file name is generated, then actual file name will end with the displayFileName,
        ///so that the actual files are easier to locate and have the same file extension as the displayedFileName.</summary>
        public static EmailAttach CreateAttach(string displayedFileName, string actualFileName, byte[] arrayData, bool isOutbound)
        {
            //No need to check RemotingRole; no call to db.
            EmailAttach emailAttach = new EmailAttach();

            emailAttach.DisplayedFileName = displayedFileName;
            if (String.IsNullOrEmpty(emailAttach.DisplayedFileName))
            {
                //This could only happen for malformed incoming emails, but should not happen.  Name uniqueness is virtually guaranteed below.
                //The actual file name will not have an extension, so the user will be asked to pick the program to open the attachment with when
                //the attachment is double-clicked.
                emailAttach.DisplayedFileName = "attach";
            }
            string attachDir = GetAttachPath();
            string subDir    = "In";

            if (isOutbound)
            {
                subDir = "Out";
            }
            if (!CloudStorage.IsCloudStorage && !Directory.Exists(ODFileUtils.CombinePaths(attachDir, subDir)))
            {
                Directory.CreateDirectory(ODFileUtils.CombinePaths(attachDir, subDir));
            }
            if (String.IsNullOrEmpty(actualFileName))
            {
                while (String.IsNullOrEmpty(emailAttach.ActualFileName) ||
                       FileAtoZ.Exists(FileAtoZ.CombinePaths(attachDir, emailAttach.ActualFileName)))
                {
                    //Display name is tacked onto actual file name last as to ensure file extensions are the same.
                    emailAttach.ActualFileName = FileAtoZ.CombinePaths(subDir,
                                                                       DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.TimeOfDay.Ticks.ToString()
                                                                       + "_" + MiscUtils.CreateRandomAlphaNumericString(4) + "_" + emailAttach.DisplayedFileName);
                }
            }
            else
            {
                //The caller wants a specific actualFileName.  Use the given name as is.
                emailAttach.ActualFileName = FileAtoZ.CombinePaths(subDir, actualFileName);
            }
            string attachFilePath = FileAtoZ.CombinePaths(attachDir, emailAttach.ActualFileName);

            if (FileAtoZ.Exists(attachFilePath))
            {
                throw new ApplicationException("Email attachment could not be saved because a file with the same name already exists.");
            }
            try {
                FileAtoZ.WriteAllBytes(attachFilePath, arrayData);
            }
            catch (Exception ex) {
                try {
                    if (FileAtoZ.Exists(attachFilePath))
                    {
                        FileAtoZ.Delete(attachFilePath);
                    }
                }
                catch {
                    //We tried our best to delete the file, and there is nothing else to try.
                }
                throw ex;                //Show the initial error message, even if the Delete() failed.
            }
            return(emailAttach);
        }
Example #18
0
		private void butSendToPortal_Click(object sender,EventArgs e) {
			//Validate
			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;
			}
			strCcdValidationErrors=EhrCCD.ValidatePatient(PatCur);//Patient cannot be null, because a patient must be selected before the EHR dashboard will open.
			if(strCcdValidationErrors!="") {
				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;
			}
			Provider prov=null;
			if(Security.CurUser.ProvNum!=0) {//If the current user is a provider.
				prov=Providers.GetProv(Security.CurUser.ProvNum);
			}
			else {
				prov=Providers.GetProv(PatCur.PriProv);//PriProv is not 0, because EhrCCD.ValidatePatient() will block if PriProv is 0.
			}
			try {
				//Create the Clinical Summary.
				FormEhrExportCCD FormEEC=new FormEhrExportCCD(PatCur);
				FormEEC.ShowDialog();
				if(FormEEC.DialogResult!=DialogResult.OK) {//Canceled
					return;
				}
				//Save the clinical summary (ccd.xml) and style sheet (ccd.xsl) as webmail message attachments.
				//TODO: It would be more patient friendly if we instead generated a PDF file containing the Clinical Summary printout, or if we simply displayed the Clinical Summary in the portal.
				//The CMS definition does not prohibit sending human readable files, and sending a PDF to the portal mimics printing the Clinical Summary and handing to patient.
				Random rnd=new Random();
				string attachPath=EmailAttaches.GetAttachPath();
				List<EmailAttach> listAttachments=new List<EmailAttach>();
				EmailAttach attachCcd=new EmailAttach();
				attachCcd.DisplayedFileName="ccd.xml";
				attachCcd.ActualFileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".xml";
				listAttachments.Add(attachCcd);
				File.WriteAllText(ODFileUtils.CombinePaths(attachPath,attachCcd.ActualFileName),FormEEC.CCD);//Save Clinical Summary to file in the email attachments folder.
				EmailAttach attachSs=new EmailAttach();//Style sheet attachment.
				attachSs.DisplayedFileName="ccd.xsl";
				attachSs.ActualFileName=attachCcd.ActualFileName.Substring(0,attachCcd.ActualFileName.Length-4)+".xsl";//Same base name as the CCD.  The base names must match or the file will not display properly in internet browsers.
				listAttachments.Add(attachSs);
				File.WriteAllText(ODFileUtils.CombinePaths(attachPath,attachSs.ActualFileName),FormEHR.GetEhrResource("CCD"));
				//Create and save the webmail message containing the attachments.
				EmailMessage msgWebMail=new EmailMessage();				
				msgWebMail.FromAddress=prov.GetFormalName();
				msgWebMail.ToAddress=PatCur.GetNameFL();
				msgWebMail.PatNum=PatCur.PatNum;
				msgWebMail.SentOrReceived=EmailSentOrReceived.WebMailSent;
				msgWebMail.ProvNumWebMail=prov.ProvNum;
				msgWebMail.Subject="Clinical Summary";
				msgWebMail.BodyText="To view the clinical summary:\r\n1) Download all attachments to the same folder.  Do not rename the files.\r\n2) Open the ccd.xml file in an internet browser.";
				msgWebMail.MsgDateTime=DateTime.Now;
				msgWebMail.PatNumSubj=PatCur.PatNum;
				msgWebMail.Attachments=listAttachments;
				EmailMessages.Insert(msgWebMail);
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return;
			}
			EhrMeasureEvent newMeasureEvent=new EhrMeasureEvent();
			newMeasureEvent.DateTEvent=DateTime.Now;
			newMeasureEvent.EventType=EhrMeasureEventType.ClinicalSummaryProvidedToPt;
			newMeasureEvent.PatNum=PatCur.PatNum;
			EhrMeasureEvents.Insert(newMeasureEvent);
			FillGridEHRMeasureEvents();//This will cause the measure event to show in the grid below the popup message on the next line.  Reassures the user that the event was immediately recorded.
			MsgBox.Show(this,"Clinical Summary Sent");
		}
		private void butPrint_Click(object sender,EventArgs e) {
			if(!TryToSaveData()){
				return;
			}
			SheetCur=Sheets.GetSheet(SheetCur.SheetNum);
			//whether this is a new sheet, or one pulled from the database,
			//it will have the extra parameter we are looking for.
			//A new sheet will also have a PatNum parameter which we will ignore.
			FormSheetOutputFormat FormS=new FormSheetOutputFormat();
			if(SheetCur.SheetType==SheetTypeEnum.ReferralSlip
				|| SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
			{
				FormS.PaperCopies=2;
			}
			else{
				FormS.PaperCopies=1;
			}
			if(SheetCur.PatNum!=0
				&& SheetCur.SheetType!=SheetTypeEnum.DepositSlip) 
			{
				Patient pat=Patients.GetPat(SheetCur.PatNum);
				if(SheetCur.SheetType==SheetTypeEnum.LabSlip) {
					FormS.IsForLab=true;//Changes label to "E-mail to Lab:"
				}
				else if(pat.Email!="") {
					FormS.EmailPatOrLabAddress=pat.Email;
					//No need to email to a patient for sheet types: LabelPatient (0), LabelCarrier (1), LabelReferral (2), ReferralSlip (3), LabelAppointment (4), Rx (5), Consent (6), ReferralLetter (8), ExamSheet (13), DepositSlip (14)
					//The data is too private to email unencrypted for sheet types: PatientForm (9), RoutingSlip (10), MedicalHistory (11), LabSlip (12)
					//A patient might want email for the following sheet types and the data is not very private: PatientLetter (7)
					if(SheetCur.SheetType==SheetTypeEnum.PatientLetter) {
						//This just defines the default selection. The user can manually change selections in FormSheetOutputFormat.
						FormS.EmailPatOrLab=true;
						FormS.PaperCopies--;
					}
				}
			}
			Referral referral=null;
			if(SheetCur.SheetType==SheetTypeEnum.ReferralSlip
				|| SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
			{
				FormS.Email2Visible=true;
				SheetParameter parameter=SheetParameter.GetParamByName(SheetCur.Parameters,"ReferralNum");
				if(parameter==null){//it can be null sometimes because of old bug in db.
					FormS.Email2Visible=false;//prevents trying to attach email to nonexistent referral.
				}
				else{
					long referralNum=PIn.Long(parameter.ParamValue.ToString());
					referral=Referrals.GetReferral(referralNum);
					if(referral.EMail!=""){
						FormS.Email2Address=referral.EMail;
						FormS.Email2=true;
						FormS.PaperCopies--;
					}
				}
			}
			else{
				FormS.Email2Visible=false;
			}
			FormS.ShowDialog();
			if(FormS.DialogResult!=DialogResult.OK){
				return;
			}
			if(FormS.PaperCopies>0){
				SheetPrinting.Print(SheetCur,FormS.PaperCopies,RxIsControlled);
			}
			EmailMessage message;
			Random rnd=new Random();
			string attachPath=EmailMessages.GetEmailAttachPath();
			string fileName;
			string filePathAndName;
			EmailAddress emailAddress;
			Patient patCur=Patients.GetPat(SheetCur.PatNum);
			if(patCur==null) {
				emailAddress=EmailAddresses.GetByClinic(0);
			}
			else {
				emailAddress=EmailAddresses.GetByClinic(patCur.ClinicNum);
			}
			//Graphics g=this.CreateGraphics();
			if(FormS.EmailPatOrLab){
				fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
				filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
				SheetPrinting.CreatePdf(SheetCur,filePathAndName);
				//Process.Start(filePathAndName);
				message=new EmailMessage();
				message.PatNum=SheetCur.PatNum;
				message.ToAddress=FormS.EmailPatOrLabAddress;
				message.FromAddress=emailAddress.SenderAddress;//Can be blank just as it could with the old pref.
				message.Subject=SheetCur.Description.ToString();//this could be improved
				EmailAttach attach=new EmailAttach();
				string shortFileName=Regex.Replace(SheetCur.Description.ToString(), @"[^\w'@-_()&]", ""); 
				attach.DisplayedFileName=shortFileName+".pdf";
				attach.ActualFileName=fileName;
				message.Attachments.Add(attach);
				FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
				FormE.IsNew=true;
				FormE.ShowDialog();
			}
			if((SheetCur.SheetType==SheetTypeEnum.ReferralSlip
				|| SheetCur.SheetType==SheetTypeEnum.ReferralLetter)
				&& FormS.Email2)
			{
				//email referral
				fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
				filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
				SheetPrinting.CreatePdf(SheetCur,filePathAndName);
				//Process.Start(filePathAndName);
				message=new EmailMessage();
				message.PatNum=SheetCur.PatNum;
				message.ToAddress=FormS.Email2Address;
				message.FromAddress=emailAddress.SenderAddress;//Can be blank just as it could with the old pref.
				message.Subject=Lan.g(this,"RE: ")+Patients.GetLim(SheetCur.PatNum).GetNameLF();//works even if patnum invalid
					//SheetCur.Description.ToString()+" to "+Referrals.GetNameFL(referral.ReferralNum);//this could be improved
				EmailAttach attach=new EmailAttach();
				string shortFileName=Regex.Replace(SheetCur.Description.ToString(), @"[^\w,'@-_()&]", ""); 
				attach.DisplayedFileName=shortFileName+".pdf";
				attach.ActualFileName=fileName;
				message.Attachments.Add(attach);
				FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
				FormE.IsNew=true;
				FormE.ShowDialog();
			}
			//g.Dispose();
			DialogResult=DialogResult.OK;
		}
Example #20
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
		}