PageRenderTime 73ms CodeModel.GetById 37ms RepoModel.GetById 1ms app.codeStats 0ms

/DocuVision.EDD.EFD/BaseJob.cs

https://bitbucket.org/docuvision/docuvision.edd.efd
C# | 1292 lines | 1086 code | 118 blank | 88 comment | 81 complexity | 96efddb32eaf15d90125c657b36910c4 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. using iTextSharp.text;
  2. using iTextSharp.text.pdf;
  3. using iTextSharp.text.pdf.parser;
  4. using Newtonsoft.Json;
  5. using Quartz;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Configuration;
  10. using System.Data.SqlClient;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Mail;
  15. using System.Net.Mime;
  16. using System.Net.NetworkInformation;
  17. using System.Net.Security;
  18. using System.Reflection;
  19. using System.Security.Cryptography;
  20. using System.Security.Cryptography.X509Certificates;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. using System.Xml.Linq;
  25. using System.Xml.XPath;
  26. namespace DocuVision.EDD.EFD
  27. {
  28. [DisallowConcurrentExecution]
  29. class BaseJob : IJob
  30. {
  31. #region Declarations
  32. static ServiceProperties serviceProperties = new ServiceProperties();
  33. private static string inputPath;
  34. private static string outputPath;
  35. private static string auditPath;
  36. private static string smtpHost;
  37. private static int smtpPort;
  38. private static bool archive;
  39. private static bool ssl;
  40. private static string embeddedImagePath;
  41. private static string BCC;
  42. private static string smtpUserName;
  43. private static string smtpPassword;
  44. private static string smtpFrom;
  45. private static string Body;
  46. private static string Subject;
  47. private static string CC;
  48. private static string DocumentCategory;
  49. private static string XMLField;
  50. private static int smtpTimeOut;
  51. private static string replyToAddress;
  52. private static string toAddress = string.Empty;
  53. private static string fromAddress = string.Empty;
  54. private static string DocumentFolder = string.Empty;
  55. private static string TemplateName = string.Empty;
  56. private static string DocNo = string.Empty;
  57. private static string waterMarkText;
  58. private static string table;
  59. private static string efdFolder;
  60. private static Dictionary<string, string> dicParser = new Dictionary<string, string>();
  61. private static log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  62. #endregion
  63. #region Constructor
  64. public BaseJob()
  65. {
  66. ExeConfigurationFileMap map = new ExeConfigurationFileMap()
  67. {
  68. ExeConfigFilename = string.Concat(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "\\serviceApp.config")
  69. };
  70. Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
  71. if (string.IsNullOrEmpty(cfg.AppSettings.Settings["ServiceProperties"].Value)) return;
  72. serviceProperties = JsonConvert.DeserializeObject<ServiceProperties>(cfg.AppSettings.Settings["ServiceProperties"].Value);
  73. //Config
  74. inputPath = serviceProperties.Inputpath;
  75. outputPath = serviceProperties.OutputPath;
  76. auditPath = serviceProperties.AuditPath ?? System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  77. smtpHost = serviceProperties.SmtpHost;
  78. smtpPort = serviceProperties.SmtpPort;
  79. archive = serviceProperties.ArchiveToEdms;
  80. ssl = serviceProperties.SSLEnabled;
  81. smtpTimeOut = serviceProperties.SmtpTimeout;
  82. }
  83. #endregion
  84. #region Events
  85. public void Execute(IJobExecutionContext context)
  86. {
  87. try
  88. {
  89. #region Licensing
  90. //LicenseModule lm = new LicenseModule();
  91. //if (lm.checkLicense(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "eMailer") == false)
  92. //{
  93. // logger.Info("License file invalid");
  94. // return;
  95. //}
  96. //Config cfg = new Config();
  97. //if (cfg.checkConfig() == false)
  98. //{
  99. // log.Info("Configuration invalid");
  100. // return;
  101. //}
  102. #endregion
  103. #region Check Directories
  104. if (!Directory.Exists(inputPath)) Directory.CreateDirectory(inputPath);
  105. if (!Directory.Exists(inputPath + "\\Processed\\")) Directory.CreateDirectory(inputPath + "\\Processed\\");
  106. if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
  107. if (!Directory.Exists(outputPath + "\\Rejected")) Directory.CreateDirectory(outputPath + "\\Rejected");
  108. //if (!Directory.Exists(outputPath + "\\Rejected\\Transaction Logs")) Directory.CreateDirectory(outputPath + "\\Rejected\\Transaction Logs");
  109. if (!Directory.Exists(outputPath + "\\Processing\\")) Directory.CreateDirectory(outputPath + "\\Processing\\");
  110. if (!Directory.Exists(serviceProperties.AuditPath)) Directory.CreateDirectory(serviceProperties.AuditPath);
  111. if (!Directory.Exists(serviceProperties.EFDExportPath)) Directory.CreateDirectory(serviceProperties.EFDExportPath);
  112. if (!Directory.Exists(serviceProperties.EFDImportPath)) Directory.CreateDirectory(serviceProperties.EFDImportPath);
  113. #endregion
  114. #region Split&Save
  115. log.Info(String.Format("Retrieving all file info in '{0}'", inputPath));
  116. FileInfo[] files = new DirectoryInfo(inputPath).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
  117. foreach (var ftp in files)
  118. {
  119. try
  120. {
  121. log.Info(string.Format("File received : {0}", ftp.Name));
  122. SplitAndSave(ftp.FullName, outputPath);
  123. Thread.Sleep(100);
  124. //move file
  125. ftp.MoveTo(System.IO.Path.GetDirectoryName(ftp.FullName) + "\\Processed\\" + System.IO.Path.GetFileNameWithoutExtension(ftp.Name) + "_" + Guid.NewGuid() + ftp.Extension);
  126. }
  127. catch (Exception ex)
  128. {
  129. log.Error(ex.Message, ex);
  130. }
  131. }
  132. #endregion
  133. #region Merge
  134. log.Info("Perparing for merge.");
  135. DirectoryInfo[] directories = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*", SearchOption.AllDirectories);
  136. foreach (var directory in directories)
  137. {
  138. try
  139. {
  140. log.Info(String.Format("Processing folder {0}", directory.Name));
  141. FileInfo[] dirFiles = new DirectoryInfo(directory.FullName).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
  142. string[] arrMerge = new string[dirFiles.Length];
  143. int count = 0;
  144. log.Info(String.Format("{0} file found to process.", dirFiles.Length));
  145. if (dirFiles.Length != 0)
  146. {
  147. foreach (var fileToMerge in dirFiles.OrderBy(x => x.CreationTime.Ticks).ToList())
  148. {
  149. log.Info(String.Format("Listing {0} for merging.", fileToMerge.FullName));
  150. arrMerge[count] = fileToMerge.FullName;
  151. count++;
  152. }
  153. string filename = string.Empty;
  154. try
  155. {
  156. filename = System.IO.Path.Combine(directory.FullName, dirFiles[0].Name);
  157. log.Info(String.Format("New filename set to '{0}'. Merging to start", filename));
  158. Thread.Sleep(100);
  159. filename = MergePDF(arrMerge, filename);
  160. log.Info("Merge complete, File created : " + filename);
  161. foreach (var item in arrMerge)
  162. {
  163. Thread.Sleep(100);
  164. GC.Collect();
  165. File.Delete(item);
  166. }
  167. File.Move(filename, filename.Substring(0, filename.LastIndexOf("-")));
  168. filename = filename.Substring(0, filename.LastIndexOf("-"));
  169. //foreach (var item in arrMerge)
  170. //{
  171. // if (item.ToString().Substring(item.LastIndexOf(@"\") + 1) != filename.Substring(filename.LastIndexOf(@"\") + 1))
  172. // {
  173. // File.Delete(outputPath + "\\Transaction Logs\\" + item.ToString().Substring(item.LastIndexOf(@"\") + 1).Replace(".pdf", ".txt"));
  174. // }
  175. //}
  176. }
  177. catch (Exception ex)
  178. {
  179. log.Error(ex.Message, ex);
  180. }
  181. }
  182. else
  183. {
  184. try
  185. {
  186. directory.Delete();
  187. }
  188. catch (Exception ex)
  189. {
  190. log.Error(ex.Message, ex);
  191. }
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. log.Error(ex.Message, ex);
  197. }
  198. }
  199. #endregion
  200. #region Exporting Items
  201. DirectoryInfo[] mailDirs = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*");
  202. foreach (var mailDir in mailDirs)
  203. {
  204. files = new DirectoryInfo(mailDir.FullName).GetFiles("*.pdf", SearchOption.AllDirectories);
  205. foreach (var file in files)
  206. {
  207. string folder = string.Empty;
  208. string mailAddress = string.Empty;
  209. string response = string.Empty;
  210. string retVal = string.Empty;
  211. Thread.Sleep(100);
  212. try
  213. {
  214. #region Get Info
  215. var info = file.Name.Split('#');
  216. DocNo = info.Length > 0 ? info[0] : DocNo;
  217. toAddress = info.Length > 1 ? info[1] : toAddress;
  218. TemplateName = info.Length > 2 ? info[2] : DocumentFolder;
  219. //Get Template Data
  220. if (!GetTemplateValues(TemplateName))
  221. {
  222. log.Error("A template has not been setup for the folder " + TemplateName + " or the template is incorrect");
  223. }
  224. #endregion
  225. #region Database Authentication
  226. if (serviceProperties.EnableDatabase)
  227. {
  228. try
  229. {
  230. //Build SQL ConnectionString
  231. System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
  232. builder.DataSource = serviceProperties.DataSource;
  233. builder.UserID = serviceProperties.UserID;
  234. builder.Password = serviceProperties.Password;
  235. builder.InitialCatalog = serviceProperties.Database;
  236. using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
  237. {
  238. conn.Open();
  239. SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT DocumentID FROM " + table + " WHERE " + XMLField + " = '" + DocNo + "') "
  240. + "BEGIN "
  241. + " SELECT FILEID FROM XTDocuments WHERE DocumentID in (SELECT DocumentID FROM " + table + " WHERE " + XMLField + " = '" + DocNo + "')"
  242. + "END "
  243. + "ELSE "
  244. + "BEGIN "
  245. + " SELECT 1 "
  246. + "END", conn);
  247. retVal = (cmd.ExecuteScalar() ?? "1").ToString();
  248. if (string.IsNullOrEmpty(retVal) || retVal == "1")
  249. {
  250. //Copy file to EFD Location
  251. file.MoveTo(System.IO.Path.Combine(serviceProperties.EFDExportPath, file.Name));
  252. //write log
  253. AuditLog(DocNo, DocumentFolder, DocumentCategory, mailAddress, fromAddress, "EFD Export");
  254. continue;
  255. }
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. log.Error("There was an error in the sql connection process.", ex);
  261. }
  262. }
  263. #endregion
  264. #region Add WaterMark
  265. if (!string.IsNullOrEmpty(waterMarkText)) //Check flag
  266. {
  267. string timeStamp = (DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + "_" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond).ToString();
  268. AddWatermarkText(TemplateName, System.IO.Path.Combine(serviceProperties.RepoPath, retVal), System.IO.Path.Combine(serviceProperties.EFDImportPath, $"{DocNo}#{toAddress}#{TemplateName}#{timeStamp}#false.pdf"), waterMarkText, null, 55f, BaseColor.RED, 0.3f, 45f);
  269. file.Delete();
  270. }
  271. #endregion
  272. }
  273. catch (Exception ex)
  274. {
  275. log.Error("An error occurred. Moving files to rejected folder");
  276. file.MoveTo(outputPath + "\\Rejected\\" + file.Name);
  277. //File.Move(outputPath + "\\Transaction Logs\\" + file.Name.Replace("pdf", "txt"), outputPath + "\\Rejected\\Transaction Logs\\" + file.Name.Replace("pdf", "txt"));
  278. log.Error(ex.Message, ex);
  279. AuditLog(DocNo, DocumentFolder, DocumentCategory, mailAddress, fromAddress, "REJECTED");
  280. }
  281. }
  282. }
  283. #region EFD Import
  284. files = new DirectoryInfo(serviceProperties.EFDImportPath).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
  285. foreach (var file in files)
  286. {
  287. try
  288. {
  289. #region Copy to Processed
  290. if (!Directory.Exists(serviceProperties.EFDImportPath + "\\Processed\\")) Directory.CreateDirectory(serviceProperties.EFDImportPath + "\\Processed\\");
  291. file.CopyTo(serviceProperties.EFDImportPath + "\\Processed\\" + file.Name, true);
  292. #endregion
  293. #region Get Info
  294. toAddress = string.Empty;
  295. DocNo = string.Empty;
  296. var info = file.Name.Split('#');
  297. DocNo = info.Length > 0 ? info[0] : DocNo;
  298. toAddress = info.Length > 1 ? info[1] : toAddress;
  299. TemplateName = info.Length > 2 ? info[2] : DocumentFolder;
  300. archive = info.Length > 4 ? bool.Parse(info[4].Replace(".pdf", "")) : archive;
  301. //Get Template Data
  302. if (!GetTemplateValues(TemplateName))
  303. {
  304. log.Error("A template has not been setup for the folder " + TemplateName + " or the template is incorrect");
  305. }
  306. #endregion
  307. #region Send Via Email
  308. try
  309. {
  310. if (!string.IsNullOrEmpty(toAddress) && !string.IsNullOrEmpty(serviceProperties.SmtpHost) && ValidateAddress(toAddress))
  311. {
  312. if (!Directory.Exists(outputPath + "\\Rejected\\")) Directory.CreateDirectory(outputPath + "\\Rejected\\");
  313. //Encrypt
  314. log.Info("Preparing to encrypt files");
  315. log.Info(String.Format("Encrypting file '{0}'", file.FullName));
  316. EncryptPDF(file.FullName);
  317. File.Delete(file.FullName);
  318. File.Move(file.FullName.Replace(".pdf", ".nef"), file.FullName);
  319. //Send Encrypted file via Email
  320. SendMail(toAddress, file.FullName, TemplateName);
  321. }
  322. else
  323. {
  324. log.Warn("A valid email address could not be retrieved from the file " + file.FullName);
  325. }
  326. }
  327. catch (Exception ex)
  328. {
  329. log.Error("Email Failure, Skipping file due to the following exception: " + ex.Message, ex);
  330. //Replace encrypted file with backed up file
  331. File.Copy(serviceProperties.EFDImportPath + "\\Processed\\" + file.Name, file.FullName, true);
  332. continue;
  333. }
  334. #endregion
  335. #region Archive To Folder
  336. //Archive item to Folder
  337. try
  338. {
  339. string newDir = outputPath + "\\Success\\" + TemplateName;
  340. if (!Directory.Exists(newDir)) Directory.CreateDirectory(newDir);
  341. string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();
  342. if (archive)
  343. {
  344. if (!Directory.Exists(newDir + "\\Images")) Directory.CreateDirectory(newDir + "\\Images");
  345. if (!Directory.Exists(newDir + "\\xml")) Directory.CreateDirectory(newDir + "\\xml");
  346. if (string.IsNullOrEmpty(DocumentCategory)) DocumentCategory = TemplateName;
  347. if (string.IsNullOrEmpty(XMLField)) XMLField = "DocumentNo";
  348. using (StreamWriter xml = new StreamWriter(newDir + "\\xml\\" + file.Name.Replace(".pdf", ".xml")))
  349. {
  350. xml.WriteLine("<BaseDocument>");
  351. xml.WriteLine("<" + XMLField + ">" + DocNo + "</" + XMLField + ">");
  352. xml.WriteLine("<SentTo>" + toAddress + "</SentTo>");
  353. xml.WriteLine("<DocumentCategory>" + DocumentCategory + "</DocumentCategory>");
  354. if (!string.IsNullOrEmpty(toAddress))
  355. {
  356. dicParser.Add("DocNo", DocNo);
  357. dicParser.Add("DocumentCategory", DocumentCategory);
  358. Subject = ExpressionParser(Subject ?? "", dicParser);
  359. xml.WriteLine("<Subject>" + Subject + "</Subject>");
  360. dicParser.Clear();
  361. }
  362. xml.WriteLine("</BaseDocument>");
  363. }
  364. newDir = newDir + "\\Images";
  365. string path = System.IO.Path.GetDirectoryName(file.FullName);
  366. file.MoveTo(newDir + "\\" + file.Name);
  367. GC.Collect();
  368. //log.Debug($"TODO DELETE ME : BEFORE PATH {path}");
  369. //Directory.Delete(path);
  370. //write log
  371. AuditLog(DocNo, DocumentFolder, DocumentCategory, toAddress, fromAddress, "ARCHIVE");
  372. }
  373. else
  374. {
  375. file.Delete();
  376. }
  377. }
  378. catch (Exception ex)
  379. {
  380. log.Error(ex.Message, ex);
  381. }
  382. #endregion Archive To Folder
  383. }
  384. catch (Exception ex)
  385. {
  386. log.Error(ex.Message, ex);
  387. }
  388. }
  389. #endregion
  390. #endregion
  391. #region TidyUp
  392. Thread.Sleep(100);
  393. directories = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*", SearchOption.TopDirectoryOnly);
  394. foreach (var dir in directories)
  395. {
  396. try
  397. {
  398. if (dir.GetFileSystemInfos().Length == 0) dir.Delete();
  399. }
  400. catch (Exception ex)
  401. {
  402. log.Error(ex.Message, ex);
  403. files = new DirectoryInfo(dir.FullName).GetFiles(".nef");
  404. foreach (var file in files)
  405. {
  406. try
  407. {
  408. file.Delete();
  409. dir.Delete();
  410. }
  411. catch (Exception exc)
  412. {
  413. log.Error(exc.Message, exc);
  414. }
  415. }
  416. }
  417. }
  418. //files = new DirectoryInfo(outputPath + "\\Rejected").GetFiles("*", SearchOption.AllDirectories);
  419. //TODO: Remove Decrypting for now untill its fixed
  420. //foreach (var file in files)
  421. //{
  422. // DecryptPDF(file.FullName);
  423. // File.Delete(file.FullName);
  424. // File.Move(file.FullName + "_Decyrpt", file.FullName);
  425. //}
  426. #endregion
  427. }
  428. catch (Exception ex)
  429. {
  430. log.Error(ex.Message, ex);
  431. }
  432. }
  433. #endregion
  434. #region Methods
  435. public static bool ValidateAddress(string eMAilAddress)
  436. {
  437. if (!string.IsNullOrEmpty(eMAilAddress))
  438. {
  439. string[] arrAddresses = eMAilAddress.Split(';');
  440. foreach (var item in arrAddresses)
  441. {
  442. if (!string.IsNullOrEmpty(item))
  443. {
  444. try
  445. {
  446. MailAddress m = new MailAddress(item);
  447. }
  448. catch (Exception ex)
  449. {
  450. log.Error(item + " is not a valid email address, error: " + ex.Message);
  451. return false;
  452. }
  453. }
  454. else
  455. {
  456. return false;
  457. }
  458. }
  459. return true;
  460. }
  461. return false;
  462. }
  463. public static string ExtractTextFromPdf(string path, int pageNo)
  464. {
  465. try
  466. {
  467. PdfReader.unethicalreading = true;
  468. using (PdfReader reader = new PdfReader(path))
  469. {
  470. PdfReader.unethicalreading = true;
  471. ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
  472. string pdftext = PdfTextExtractor.GetTextFromPage(reader, pageNo, Strategy);
  473. StringBuilder text = new StringBuilder();
  474. //text.Append(PdfTextExtractor.GetTextFromPage(reader, pageNo).Replace('\n',' '));
  475. foreach (string row in pdftext.Split('\n'))
  476. {
  477. if (row.Contains(serviceProperties.SplitChar))
  478. {
  479. text.Append(row.Replace('\n', ' '));
  480. }
  481. }
  482. return text.ToString();
  483. }
  484. }
  485. catch (Exception ex)
  486. {
  487. log.Error(ex.Message, ex);
  488. throw;
  489. }
  490. }
  491. public static void SplitAndSave(string inputPath, string outputPath)
  492. {
  493. try
  494. {
  495. FileInfo file = new FileInfo(inputPath);
  496. //StringBuilder sbLog = new StringBuilder();
  497. //string errorTimeStamp = "[" + DateTime.Now + "]";
  498. PdfReader.unethicalreading = true;
  499. using (PdfReader reader = new PdfReader(inputPath))
  500. {
  501. PdfReader.unethicalreading = true;
  502. int pagenumber = 1;
  503. //errorTimeStamp = "[" + DateTime.Now + "]";
  504. for (pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
  505. {
  506. string timeStamp = (DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + "_" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond).ToString();
  507. try
  508. {
  509. GC.Collect();
  510. Thread.Sleep(100);
  511. string text = ExtractTextFromPdf(file.FullName, pagenumber);
  512. if (string.IsNullOrEmpty(text))
  513. {
  514. log.Error("The file " + file.Name + " was not in the in a readable format, please ensure that the file is an image over text PDF file.");
  515. }
  516. if (!text.Contains(serviceProperties.SplitChar))
  517. {
  518. log.Error("The file " + file.Name + " did not contain the necessary start and end tags," + " please ensure that the file has the necessary start and end tags and try again.");
  519. }
  520. string[] split = text.Split(new string[] { serviceProperties.SplitChar }, StringSplitOptions.None);
  521. //if (split.Length > 9)
  522. //{
  523. DocNo = split.Length > 1 ? split[1] : DocNo;
  524. toAddress = split.Length > 3 ? split[3] : toAddress;
  525. fromAddress = split.Length > 5 ? split[5] : fromAddress;
  526. DocumentFolder = split.Length > 7 ? split[7] : DocumentFolder;
  527. DocumentCategory = split.Length > 9 ? split[9] : DocumentCategory;
  528. //TODO check if any blank, so we can populate them with Defaults
  529. string filename = DocNo + "#" + toAddress + "#" + DocumentFolder + "#" + timeStamp + ".pdf";
  530. if (!string.IsNullOrEmpty(DocNo))
  531. {
  532. if (!Directory.Exists(outputPath + "\\Processing\\" + DocumentFolder + "-" + DocNo)) Directory.CreateDirectory(outputPath + "\\Processing\\" + DocumentFolder + "-" + DocNo);
  533. filename = System.IO.Path.Combine(outputPath, "Processing", DocumentFolder + "-" + DocNo, filename);
  534. }
  535. else
  536. {
  537. filename = outputPath + "\\rejected\\" + filename;
  538. }
  539. using (Document document = new Document())
  540. {
  541. if (!Directory.Exists(filename)) Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename));
  542. PdfCopy copy = new PdfCopy(document, new FileStream(filename, FileMode.Create));
  543. document.Open();
  544. copy.AddPage(copy.GetImportedPage(reader, pagenumber));
  545. }
  546. if (string.IsNullOrEmpty(DocNo))
  547. {
  548. log.Error("A document number could not be retrieved from page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name);
  549. }
  550. else if ((string.IsNullOrEmpty(toAddress) || !ValidateAddress(toAddress)))
  551. {
  552. log.Warn("One or more eMail addresses on page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " is invalid");
  553. }
  554. log.Info("Completed page extraction of page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + filename);
  555. //if (!Directory.Exists(outputPath + "\\Transaction Logs\\")) Directory.CreateDirectory(outputPath + "\\Transaction Logs\\");
  556. ////Write Tansactions Logs
  557. //using (StreamWriter sw = new StreamWriter(outputPath + "\\Transaction Logs\\" + System.IO.Path.GetFileName(filename.Replace(".pdf", ".txt"))))
  558. //{
  559. // sw.WriteLine(toAddress);
  560. // sw.WriteLine(DocNo);
  561. // sw.WriteLine(DocumentFolder);
  562. // sw.WriteLine(DocumentCategory);
  563. // sw.WriteLine(fromAddress);
  564. //}
  565. //write log
  566. AuditLog(DocNo, DocumentFolder, DocumentCategory, toAddress, fromAddress, "SPLIT - " + pagenumber + " of " + reader.NumberOfPages);
  567. //}
  568. //else
  569. //{
  570. // log.Error("Page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " did not contain the correct formula");
  571. //}
  572. }
  573. catch (Exception ex)
  574. {
  575. log.Error("Failed page extraction of page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " with error - " + ex.Message);
  576. }
  577. }
  578. }
  579. }
  580. catch (Exception ex)
  581. {
  582. log.Error(ex.Message, ex);
  583. throw;
  584. }
  585. //return sbLog.ToString();
  586. }
  587. public static bool GetTemplateValues(string folderProcessed)
  588. {
  589. try
  590. {
  591. foreach (Template template in serviceProperties.Templates)
  592. {
  593. if (template.TemplateName.Trim().ToLower() == folderProcessed.Trim().ToLower())
  594. {
  595. log.Info("Matching Template found, Populating values");
  596. smtpUserName = template.SmtpUserName;
  597. smtpPassword = template.SmtpPassword;
  598. smtpFrom = template.SmtpFrom;
  599. Body = template.Body;
  600. Subject = template.Subject;
  601. CC = template.CC;
  602. DocumentCategory = string.IsNullOrWhiteSpace(DocumentCategory) ? template.DocumentCategory : DocumentCategory;
  603. XMLField = template.XMLField;
  604. embeddedImagePath = template.EmbeddedImagePath;
  605. BCC = template.BCC;
  606. replyToAddress = template.SmtpReplyTo;
  607. waterMarkText = template.WatermarkPrint;
  608. table = template.Table;
  609. toAddress = string.IsNullOrWhiteSpace(toAddress) ? template.DefaultToEmail : toAddress;
  610. return true;
  611. }
  612. }
  613. }
  614. catch (Exception ex)
  615. {
  616. log.Error(ex.Message, ex);
  617. return false;
  618. }
  619. log.Error("No matching Template was found");
  620. return false;
  621. }
  622. static byte[] GetBytes(string str)
  623. {
  624. try
  625. {
  626. byte[] bytes = new byte[str.Length * sizeof(char)];
  627. System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
  628. return bytes;
  629. }
  630. catch (Exception ex)
  631. {
  632. log.Error(ex.Message, ex);
  633. throw;
  634. }
  635. }
  636. public static void DecryptPDF(string inputFile)
  637. {
  638. try
  639. {
  640. PdfReader.unethicalreading = true;
  641. using (PdfReader reader = new PdfReader(inputFile, GetBytes("D0cuV1s10n")))
  642. {
  643. PdfReader.unethicalreading = true;
  644. using (MemoryStream memoryStream = new MemoryStream())
  645. {
  646. using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
  647. {
  648. stamper.SetFullCompression();
  649. //File.Delete(inputFile);
  650. File.WriteAllBytes(inputFile + "_decrypt", memoryStream.ToArray());
  651. }
  652. }
  653. }
  654. }
  655. catch (Exception ex)
  656. {
  657. log.Error(ex.Message, ex);
  658. throw;
  659. }
  660. }
  661. public static void EncryptPDF(string input)
  662. {
  663. try
  664. {
  665. PdfReader.unethicalreading = true;
  666. using (PdfReader reader = new PdfReader(input))
  667. {
  668. PdfReader.unethicalreading = true;
  669. if (File.Exists(input.Replace(".pdf", ".nef"))) File.Delete(input.Replace(".pdf", ".nef"));
  670. using (FileStream fs = new FileStream(input.Replace(".pdf", ".nef"), FileMode.Create))
  671. {
  672. using (PdfStamper stamper = new PdfStamper(reader, fs))
  673. {
  674. try
  675. {
  676. stamper.SetEncryption(null, GetBytes("D0cuV1s10n"), PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_256);
  677. stamper.SetFullCompression();
  678. stamper.Reader.RemoveUnusedObjects();
  679. stamper.FormFlattening = true;
  680. }
  681. catch (Exception ex)
  682. {
  683. //if (ex.Message == "PdfReader not opened with owner password")
  684. //{
  685. // File.Delete(input.Replace(".pdf", ".nef"));
  686. // return;
  687. //}
  688. //File.Copy(input, input.Replace(".pdf", ".nef"));
  689. log.Error(ex.Message, ex);
  690. }
  691. //File.Delete(input);
  692. //File.Move(input.Replace(".pdf", ".nef"), input);
  693. }
  694. }
  695. }
  696. }
  697. catch (Exception ex)
  698. {
  699. log.Error(ex.Message, ex);
  700. throw;
  701. }
  702. }
  703. public static string MergePDF(string[] InFiles, string OutFile)
  704. {
  705. try
  706. {
  707. OutFile = OutFile + "-" + Guid.NewGuid().ToString().ToUpper().Replace("-", string.Empty);
  708. string response = string.Empty;
  709. if (File.Exists(OutFile)) return OutFile; //+ " merged successfully 0x00001";
  710. using (FileStream fileStream = new FileStream(OutFile, FileMode.Create))
  711. {
  712. using (Document document = new Document())
  713. {
  714. using (PdfCopy pdfCopy = new PdfCopy(document, fileStream))
  715. {
  716. document.Open();
  717. for (int i = 0; i < InFiles.Length; i++)
  718. {
  719. try
  720. {
  721. PdfReader.unethicalreading = true;
  722. using (PdfReader pdfReader = new PdfReader(InFiles[i]))
  723. {
  724. PdfReader.unethicalreading = true;
  725. for (int j = 0; j < pdfReader.NumberOfPages; j++)
  726. {
  727. pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, j + 1));
  728. }
  729. pdfCopy.FreeReader(pdfReader);
  730. }
  731. }
  732. catch (Exception ex)
  733. {
  734. log.Error(string.Format("Failed to merge file : {0}, with error : {1}", InFiles[i], ex.Message));
  735. }
  736. }
  737. }
  738. }
  739. }
  740. }
  741. catch (Exception ex)
  742. {
  743. log.Error(ex.Message, ex);
  744. }
  745. return OutFile;
  746. }
  747. public static void SendMail(string eMailAddress, string FileName, string templateCode)
  748. {
  749. FileInfo file = new FileInfo(FileName);
  750. using (SmtpClient smtp = new SmtpClient())
  751. {
  752. try
  753. {
  754. string strName = Guid.NewGuid().ToString().ToUpper().Replace("-", string.Empty);
  755. //if (!setMailValues(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\eMailer Templates.xml", templateCode))
  756. //if (!GetTemplateValues(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\eMailer Templates.xml", templateCode))
  757. //{
  758. // log.Error("A template has not been setup fo the folder " + templateCode + " or the template is incorrect");
  759. // return;
  760. //}
  761. #region Normal
  762. smtp.Port = smtpPort;
  763. smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //TODO: Check if this should be parameterized
  764. smtp.EnableSsl = ssl;
  765. smtp.Timeout = smtpTimeOut;
  766. smtp.Host = smtpHost;
  767. if (!string.IsNullOrEmpty(smtpPassword) & !string.IsNullOrEmpty(smtpUserName))
  768. {
  769. smtp.UseDefaultCredentials = false;
  770. smtp.Credentials = new NetworkCredential(smtpUserName.TrimStart().TrimEnd(), smtpPassword.TrimStart().TrimEnd());
  771. }
  772. else
  773. {
  774. smtp.UseDefaultCredentials = true;
  775. }
  776. #endregion
  777. //if (!string.IsNullOrEmpty(config.AppSettings.Settings["TestMail"].Value))
  778. if (!string.IsNullOrEmpty(serviceProperties.TestEmail))
  779. {
  780. //eMailAddress = config.AppSettings.Settings["TestMail"].Value;
  781. eMailAddress = serviceProperties.TestEmail;
  782. }
  783. using (MailMessage mail = new MailMessage())
  784. {
  785. string[] arrAddresses = eMailAddress.Split(';');
  786. if (arrAddresses.Count() != 0)
  787. {
  788. foreach (var item in arrAddresses)
  789. {
  790. if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
  791. {
  792. mail.To.Add(new MailAddress(item.ToString()));
  793. }
  794. }
  795. }
  796. else
  797. {
  798. mail.To.Add(new MailAddress(eMailAddress));
  799. }
  800. if (!string.IsNullOrEmpty(replyToAddress))
  801. {
  802. mail.ReplyToList.Add(new MailAddress(replyToAddress));
  803. }
  804. if (!string.IsNullOrEmpty(fromAddress))
  805. {
  806. //mail.Sender = new MailAddress(fromAddress);
  807. try
  808. {
  809. mail.From = new MailAddress(fromAddress);
  810. log.Info("From address : " + fromAddress);
  811. }
  812. catch (Exception ex)
  813. {
  814. log.Error("Invalid email address in From field found, " + fromAddress + "\n" + ex.Message);
  815. }
  816. }
  817. else if (!string.IsNullOrEmpty(smtpFrom))
  818. {
  819. log.Warn("No From Address found, using the Template Default: " + smtpFrom);
  820. mail.From = new MailAddress(smtpFrom);
  821. }
  822. mail.IsBodyHtml = true; //TODO make this configurable
  823. if (!string.IsNullOrEmpty(CC) & CC != " ")
  824. {
  825. string[] arrAddressesCC = CC.Split(';');
  826. if (arrAddressesCC.Count() != 0)
  827. {
  828. foreach (var item in arrAddressesCC)
  829. {
  830. if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
  831. {
  832. mail.CC.Add(new MailAddress(item.ToString()));
  833. }
  834. }
  835. }
  836. else
  837. {
  838. mail.CC.Add(new MailAddress(CC));
  839. }
  840. }
  841. if (!string.IsNullOrEmpty(BCC) & BCC != " ")
  842. {
  843. string[] arrAddressesBCC = BCC.Split(';');
  844. if (arrAddressesBCC.Count() != 0)
  845. {
  846. foreach (var item in arrAddressesBCC)
  847. {
  848. if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
  849. {
  850. mail.Bcc.Add(new MailAddress(item.ToString()));
  851. }
  852. }
  853. }
  854. else
  855. {
  856. mail.Bcc.Add(new MailAddress(BCC));
  857. }
  858. }
  859. mail.Attachments.Add(new Attachment(file.FullName));
  860. //mail.Subject = Subject; //TODO: Create Text Parser, where we substitude values <##>
  861. dicParser.Add("DocNo", DocNo);
  862. dicParser.Add("DocumentCategory", DocumentCategory);
  863. Subject = ExpressionParser(Subject ?? "", dicParser);
  864. mail.Subject = Subject;
  865. mail.Body = ExpressionParser(Body ?? "", dicParser);
  866. dicParser.Clear(); //TODO : resolve this better
  867. //if (File.Exists(Body))
  868. if (!string.IsNullOrEmpty(embeddedImagePath) & embeddedImagePath != " ")
  869. {
  870. if (File.Exists(embeddedImagePath))
  871. {
  872. log.Info("Embedded Image found.");
  873. AlternateView avHtml = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html);
  874. // Create a LinkedResource object for the embedded image
  875. LinkedResource pic1 = new LinkedResource(embeddedImagePath, MediaTypeNames.Image.Jpeg);
  876. pic1.ContentId = "Pic1";
  877. avHtml.LinkedResources.Add(pic1);
  878. // Add the alternate views instead of using MailMessage.Body
  879. mail.AlternateViews.Add(avHtml);
  880. }
  881. }
  882. ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; //TODO: WTF is this???
  883. smtp.Send(mail);
  884. log.Info(file.Name + " successfully sent to " + eMailAddress);
  885. //sbLog.Append("[" + DateTime.Now + "] " + file.Name + " successfully sent to " + eMailAddress);
  886. //log.Debug($"TODO DELETE, BEFORE DELETE (EMAIL) {file.FullName.Replace(file.Name, strName)}");
  887. //File.Delete(file.FullName.Replace(file.Name, strName));
  888. string To_Address = "";
  889. foreach (var address in mail.To)
  890. {
  891. To_Address += address.Address + ";";
  892. }
  893. AuditLog(DocNo, DocumentFolder, DocumentCategory, To_Address, mail.From.Address, "EMAIL");
  894. }
  895. }
  896. catch (SmtpException ex)
  897. {
  898. dicParser.Clear();
  899. log.Error(file.Name + " failed to send to " + eMailAddress + " with the error - " + ex.Message, ex);
  900. throw;
  901. //sbLog.Append("[" + DateTime.Now + "] " + file.Name + " failed to send to " + eMailAddress + " with the error - " + ex.Message + "-" + ex.InnerException);
  902. }
  903. catch (Exception ex)
  904. {
  905. dicParser.Clear();
  906. log.Error(ex.Message, ex);
  907. throw;
  908. //sbLog.Append("[" + DateTime.Now + "] " + file.Name.Substring(file.Name.LastIndexOf("~") + 1).Replace(file.Extension, string.Empty) + " failed to send to " + eMailAddress + " with the error - " + ex.Message + "-" + ex.InnerException);
  909. }
  910. }
  911. }
  912. public static string ExpressionParser(string inputString, Dictionary<string, string> arrValues)
  913. {
  914. string retVal = inputString;
  915. try
  916. {
  917. //loop through keys
  918. foreach (string item in arrValues.Keys)
  919. {
  920. string replaceKey = string.Concat("<#", item, "#>");
  921. string replaceVal = string.Empty;
  922. if (inputString.Contains(replaceKey))
  923. {
  924. //Retrieve Values from Keys
  925. arrValues.TryGetValue(item, out replaceVal);
  926. retVal = retVal.Replace(replaceKey, replaceVal

Large files files are truncated, but you can click here to view the full file