/DocuVision.EDD.EFD/BaseJob.cs
C# | 1292 lines | 1086 code | 118 blank | 88 comment | 81 complexity | 96efddb32eaf15d90125c657b36910c4 MD5 | raw file
- using iTextSharp.text;
- using iTextSharp.text.pdf;
- using iTextSharp.text.pdf.parser;
- using Newtonsoft.Json;
- using Quartz;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Mail;
- using System.Net.Mime;
- using System.Net.NetworkInformation;
- using System.Net.Security;
- using System.Reflection;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- using System.Xml.XPath;
- namespace DocuVision.EDD.EFD
- {
- [DisallowConcurrentExecution]
- class BaseJob : IJob
- {
- #region Declarations
- static ServiceProperties serviceProperties = new ServiceProperties();
- private static string inputPath;
- private static string outputPath;
- private static string auditPath;
- private static string smtpHost;
- private static int smtpPort;
- private static bool archive;
- private static bool ssl;
- private static string embeddedImagePath;
- private static string BCC;
- private static string smtpUserName;
- private static string smtpPassword;
- private static string smtpFrom;
- private static string Body;
- private static string Subject;
- private static string CC;
- private static string DocumentCategory;
- private static string XMLField;
- private static int smtpTimeOut;
- private static string replyToAddress;
- private static string toAddress = string.Empty;
- private static string fromAddress = string.Empty;
- private static string DocumentFolder = string.Empty;
- private static string TemplateName = string.Empty;
- private static string DocNo = string.Empty;
- private static string waterMarkText;
- private static string table;
- private static string efdFolder;
- private static Dictionary<string, string> dicParser = new Dictionary<string, string>();
- private static log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- #endregion
- #region Constructor
- public BaseJob()
- {
- ExeConfigurationFileMap map = new ExeConfigurationFileMap()
- {
- ExeConfigFilename = string.Concat(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "\\serviceApp.config")
- };
- Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
- if (string.IsNullOrEmpty(cfg.AppSettings.Settings["ServiceProperties"].Value)) return;
- serviceProperties = JsonConvert.DeserializeObject<ServiceProperties>(cfg.AppSettings.Settings["ServiceProperties"].Value);
- //Config
- inputPath = serviceProperties.Inputpath;
- outputPath = serviceProperties.OutputPath;
- auditPath = serviceProperties.AuditPath ?? System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
- smtpHost = serviceProperties.SmtpHost;
- smtpPort = serviceProperties.SmtpPort;
- archive = serviceProperties.ArchiveToEdms;
- ssl = serviceProperties.SSLEnabled;
- smtpTimeOut = serviceProperties.SmtpTimeout;
- }
- #endregion
- #region Events
- public void Execute(IJobExecutionContext context)
- {
- try
- {
- #region Licensing
- //LicenseModule lm = new LicenseModule();
- //if (lm.checkLicense(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "eMailer") == false)
- //{
- // logger.Info("License file invalid");
- // return;
- //}
- //Config cfg = new Config();
- //if (cfg.checkConfig() == false)
- //{
- // log.Info("Configuration invalid");
- // return;
- //}
- #endregion
- #region Check Directories
- if (!Directory.Exists(inputPath)) Directory.CreateDirectory(inputPath);
- if (!Directory.Exists(inputPath + "\\Processed\\")) Directory.CreateDirectory(inputPath + "\\Processed\\");
- if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
- if (!Directory.Exists(outputPath + "\\Rejected")) Directory.CreateDirectory(outputPath + "\\Rejected");
- //if (!Directory.Exists(outputPath + "\\Rejected\\Transaction Logs")) Directory.CreateDirectory(outputPath + "\\Rejected\\Transaction Logs");
- if (!Directory.Exists(outputPath + "\\Processing\\")) Directory.CreateDirectory(outputPath + "\\Processing\\");
- if (!Directory.Exists(serviceProperties.AuditPath)) Directory.CreateDirectory(serviceProperties.AuditPath);
- if (!Directory.Exists(serviceProperties.EFDExportPath)) Directory.CreateDirectory(serviceProperties.EFDExportPath);
- if (!Directory.Exists(serviceProperties.EFDImportPath)) Directory.CreateDirectory(serviceProperties.EFDImportPath);
- #endregion
- #region Split&Save
- log.Info(String.Format("Retrieving all file info in '{0}'", inputPath));
- FileInfo[] files = new DirectoryInfo(inputPath).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
- foreach (var ftp in files)
- {
- try
- {
- log.Info(string.Format("File received : {0}", ftp.Name));
- SplitAndSave(ftp.FullName, outputPath);
- Thread.Sleep(100);
- //move file
- ftp.MoveTo(System.IO.Path.GetDirectoryName(ftp.FullName) + "\\Processed\\" + System.IO.Path.GetFileNameWithoutExtension(ftp.Name) + "_" + Guid.NewGuid() + ftp.Extension);
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- #endregion
- #region Merge
- log.Info("Perparing for merge.");
- DirectoryInfo[] directories = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*", SearchOption.AllDirectories);
- foreach (var directory in directories)
- {
- try
- {
- log.Info(String.Format("Processing folder {0}", directory.Name));
- FileInfo[] dirFiles = new DirectoryInfo(directory.FullName).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
- string[] arrMerge = new string[dirFiles.Length];
- int count = 0;
- log.Info(String.Format("{0} file found to process.", dirFiles.Length));
- if (dirFiles.Length != 0)
- {
- foreach (var fileToMerge in dirFiles.OrderBy(x => x.CreationTime.Ticks).ToList())
- {
- log.Info(String.Format("Listing {0} for merging.", fileToMerge.FullName));
- arrMerge[count] = fileToMerge.FullName;
- count++;
- }
- string filename = string.Empty;
- try
- {
- filename = System.IO.Path.Combine(directory.FullName, dirFiles[0].Name);
- log.Info(String.Format("New filename set to '{0}'. Merging to start", filename));
- Thread.Sleep(100);
- filename = MergePDF(arrMerge, filename);
- log.Info("Merge complete, File created : " + filename);
- foreach (var item in arrMerge)
- {
- Thread.Sleep(100);
- GC.Collect();
- File.Delete(item);
- }
- File.Move(filename, filename.Substring(0, filename.LastIndexOf("-")));
- filename = filename.Substring(0, filename.LastIndexOf("-"));
- //foreach (var item in arrMerge)
- //{
- // if (item.ToString().Substring(item.LastIndexOf(@"\") + 1) != filename.Substring(filename.LastIndexOf(@"\") + 1))
- // {
- // File.Delete(outputPath + "\\Transaction Logs\\" + item.ToString().Substring(item.LastIndexOf(@"\") + 1).Replace(".pdf", ".txt"));
- // }
- //}
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- else
- {
- try
- {
- directory.Delete();
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- #endregion
- #region Exporting Items
- DirectoryInfo[] mailDirs = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*");
- foreach (var mailDir in mailDirs)
- {
- files = new DirectoryInfo(mailDir.FullName).GetFiles("*.pdf", SearchOption.AllDirectories);
- foreach (var file in files)
- {
- string folder = string.Empty;
- string mailAddress = string.Empty;
- string response = string.Empty;
- string retVal = string.Empty;
- Thread.Sleep(100);
- try
- {
- #region Get Info
- var info = file.Name.Split('#');
- DocNo = info.Length > 0 ? info[0] : DocNo;
- toAddress = info.Length > 1 ? info[1] : toAddress;
- TemplateName = info.Length > 2 ? info[2] : DocumentFolder;
- //Get Template Data
- if (!GetTemplateValues(TemplateName))
- {
- log.Error("A template has not been setup for the folder " + TemplateName + " or the template is incorrect");
- }
- #endregion
- #region Database Authentication
- if (serviceProperties.EnableDatabase)
- {
- try
- {
- //Build SQL ConnectionString
- System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
- builder.DataSource = serviceProperties.DataSource;
- builder.UserID = serviceProperties.UserID;
- builder.Password = serviceProperties.Password;
- builder.InitialCatalog = serviceProperties.Database;
- using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT DocumentID FROM " + table + " WHERE " + XMLField + " = '" + DocNo + "') "
- + "BEGIN "
- + " SELECT FILEID FROM XTDocuments WHERE DocumentID in (SELECT DocumentID FROM " + table + " WHERE " + XMLField + " = '" + DocNo + "')"
- + "END "
- + "ELSE "
- + "BEGIN "
- + " SELECT 1 "
- + "END", conn);
- retVal = (cmd.ExecuteScalar() ?? "1").ToString();
- if (string.IsNullOrEmpty(retVal) || retVal == "1")
- {
- //Copy file to EFD Location
- file.MoveTo(System.IO.Path.Combine(serviceProperties.EFDExportPath, file.Name));
- //write log
- AuditLog(DocNo, DocumentFolder, DocumentCategory, mailAddress, fromAddress, "EFD Export");
- continue;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error("There was an error in the sql connection process.", ex);
- }
- }
- #endregion
- #region Add WaterMark
- if (!string.IsNullOrEmpty(waterMarkText)) //Check flag
- {
- 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();
- 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);
- file.Delete();
- }
- #endregion
- }
- catch (Exception ex)
- {
- log.Error("An error occurred. Moving files to rejected folder");
- file.MoveTo(outputPath + "\\Rejected\\" + file.Name);
- //File.Move(outputPath + "\\Transaction Logs\\" + file.Name.Replace("pdf", "txt"), outputPath + "\\Rejected\\Transaction Logs\\" + file.Name.Replace("pdf", "txt"));
- log.Error(ex.Message, ex);
- AuditLog(DocNo, DocumentFolder, DocumentCategory, mailAddress, fromAddress, "REJECTED");
- }
- }
- }
- #region EFD Import
- files = new DirectoryInfo(serviceProperties.EFDImportPath).GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
- foreach (var file in files)
- {
- try
- {
- #region Copy to Processed
- if (!Directory.Exists(serviceProperties.EFDImportPath + "\\Processed\\")) Directory.CreateDirectory(serviceProperties.EFDImportPath + "\\Processed\\");
- file.CopyTo(serviceProperties.EFDImportPath + "\\Processed\\" + file.Name, true);
- #endregion
- #region Get Info
- toAddress = string.Empty;
- DocNo = string.Empty;
- var info = file.Name.Split('#');
- DocNo = info.Length > 0 ? info[0] : DocNo;
- toAddress = info.Length > 1 ? info[1] : toAddress;
- TemplateName = info.Length > 2 ? info[2] : DocumentFolder;
- archive = info.Length > 4 ? bool.Parse(info[4].Replace(".pdf", "")) : archive;
- //Get Template Data
- if (!GetTemplateValues(TemplateName))
- {
- log.Error("A template has not been setup for the folder " + TemplateName + " or the template is incorrect");
- }
- #endregion
- #region Send Via Email
- try
- {
- if (!string.IsNullOrEmpty(toAddress) && !string.IsNullOrEmpty(serviceProperties.SmtpHost) && ValidateAddress(toAddress))
- {
- if (!Directory.Exists(outputPath + "\\Rejected\\")) Directory.CreateDirectory(outputPath + "\\Rejected\\");
- //Encrypt
- log.Info("Preparing to encrypt files");
- log.Info(String.Format("Encrypting file '{0}'", file.FullName));
- EncryptPDF(file.FullName);
- File.Delete(file.FullName);
- File.Move(file.FullName.Replace(".pdf", ".nef"), file.FullName);
- //Send Encrypted file via Email
- SendMail(toAddress, file.FullName, TemplateName);
- }
- else
- {
- log.Warn("A valid email address could not be retrieved from the file " + file.FullName);
- }
- }
- catch (Exception ex)
- {
- log.Error("Email Failure, Skipping file due to the following exception: " + ex.Message, ex);
- //Replace encrypted file with backed up file
- File.Copy(serviceProperties.EFDImportPath + "\\Processed\\" + file.Name, file.FullName, true);
- continue;
- }
- #endregion
- #region Archive To Folder
- //Archive item to Folder
- try
- {
- string newDir = outputPath + "\\Success\\" + TemplateName;
- if (!Directory.Exists(newDir)) Directory.CreateDirectory(newDir);
- string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();
- if (archive)
- {
- if (!Directory.Exists(newDir + "\\Images")) Directory.CreateDirectory(newDir + "\\Images");
- if (!Directory.Exists(newDir + "\\xml")) Directory.CreateDirectory(newDir + "\\xml");
- if (string.IsNullOrEmpty(DocumentCategory)) DocumentCategory = TemplateName;
- if (string.IsNullOrEmpty(XMLField)) XMLField = "DocumentNo";
- using (StreamWriter xml = new StreamWriter(newDir + "\\xml\\" + file.Name.Replace(".pdf", ".xml")))
- {
- xml.WriteLine("<BaseDocument>");
- xml.WriteLine("<" + XMLField + ">" + DocNo + "</" + XMLField + ">");
- xml.WriteLine("<SentTo>" + toAddress + "</SentTo>");
- xml.WriteLine("<DocumentCategory>" + DocumentCategory + "</DocumentCategory>");
- if (!string.IsNullOrEmpty(toAddress))
- {
- dicParser.Add("DocNo", DocNo);
- dicParser.Add("DocumentCategory", DocumentCategory);
- Subject = ExpressionParser(Subject ?? "", dicParser);
- xml.WriteLine("<Subject>" + Subject + "</Subject>");
- dicParser.Clear();
- }
- xml.WriteLine("</BaseDocument>");
- }
- newDir = newDir + "\\Images";
- string path = System.IO.Path.GetDirectoryName(file.FullName);
- file.MoveTo(newDir + "\\" + file.Name);
- GC.Collect();
- //log.Debug($"TODO DELETE ME : BEFORE PATH {path}");
- //Directory.Delete(path);
- //write log
- AuditLog(DocNo, DocumentFolder, DocumentCategory, toAddress, fromAddress, "ARCHIVE");
- }
- else
- {
- file.Delete();
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- #endregion Archive To Folder
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- #endregion
- #endregion
- #region TidyUp
- Thread.Sleep(100);
- directories = new DirectoryInfo(outputPath + "\\Processing").GetDirectories("*", SearchOption.TopDirectoryOnly);
- foreach (var dir in directories)
- {
- try
- {
- if (dir.GetFileSystemInfos().Length == 0) dir.Delete();
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- files = new DirectoryInfo(dir.FullName).GetFiles(".nef");
- foreach (var file in files)
- {
- try
- {
- file.Delete();
- dir.Delete();
- }
- catch (Exception exc)
- {
- log.Error(exc.Message, exc);
- }
- }
- }
- }
- //files = new DirectoryInfo(outputPath + "\\Rejected").GetFiles("*", SearchOption.AllDirectories);
- //TODO: Remove Decrypting for now untill its fixed
- //foreach (var file in files)
- //{
- // DecryptPDF(file.FullName);
- // File.Delete(file.FullName);
- // File.Move(file.FullName + "_Decyrpt", file.FullName);
- //}
- #endregion
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- #endregion
- #region Methods
- public static bool ValidateAddress(string eMAilAddress)
- {
- if (!string.IsNullOrEmpty(eMAilAddress))
- {
- string[] arrAddresses = eMAilAddress.Split(';');
- foreach (var item in arrAddresses)
- {
- if (!string.IsNullOrEmpty(item))
- {
- try
- {
- MailAddress m = new MailAddress(item);
- }
- catch (Exception ex)
- {
- log.Error(item + " is not a valid email address, error: " + ex.Message);
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- return true;
- }
- return false;
- }
- public static string ExtractTextFromPdf(string path, int pageNo)
- {
- try
- {
- PdfReader.unethicalreading = true;
- using (PdfReader reader = new PdfReader(path))
- {
- PdfReader.unethicalreading = true;
- ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
- string pdftext = PdfTextExtractor.GetTextFromPage(reader, pageNo, Strategy);
- StringBuilder text = new StringBuilder();
- //text.Append(PdfTextExtractor.GetTextFromPage(reader, pageNo).Replace('\n',' '));
- foreach (string row in pdftext.Split('\n'))
- {
- if (row.Contains(serviceProperties.SplitChar))
- {
- text.Append(row.Replace('\n', ' '));
- }
- }
- return text.ToString();
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- public static void SplitAndSave(string inputPath, string outputPath)
- {
- try
- {
- FileInfo file = new FileInfo(inputPath);
- //StringBuilder sbLog = new StringBuilder();
- //string errorTimeStamp = "[" + DateTime.Now + "]";
- PdfReader.unethicalreading = true;
- using (PdfReader reader = new PdfReader(inputPath))
- {
- PdfReader.unethicalreading = true;
- int pagenumber = 1;
- //errorTimeStamp = "[" + DateTime.Now + "]";
- for (pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
- {
- 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();
- try
- {
- GC.Collect();
- Thread.Sleep(100);
- string text = ExtractTextFromPdf(file.FullName, pagenumber);
- if (string.IsNullOrEmpty(text))
- {
- 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.");
- }
- if (!text.Contains(serviceProperties.SplitChar))
- {
- 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.");
- }
- string[] split = text.Split(new string[] { serviceProperties.SplitChar }, StringSplitOptions.None);
- //if (split.Length > 9)
- //{
- DocNo = split.Length > 1 ? split[1] : DocNo;
- toAddress = split.Length > 3 ? split[3] : toAddress;
- fromAddress = split.Length > 5 ? split[5] : fromAddress;
- DocumentFolder = split.Length > 7 ? split[7] : DocumentFolder;
- DocumentCategory = split.Length > 9 ? split[9] : DocumentCategory;
- //TODO check if any blank, so we can populate them with Defaults
- string filename = DocNo + "#" + toAddress + "#" + DocumentFolder + "#" + timeStamp + ".pdf";
- if (!string.IsNullOrEmpty(DocNo))
- {
- if (!Directory.Exists(outputPath + "\\Processing\\" + DocumentFolder + "-" + DocNo)) Directory.CreateDirectory(outputPath + "\\Processing\\" + DocumentFolder + "-" + DocNo);
- filename = System.IO.Path.Combine(outputPath, "Processing", DocumentFolder + "-" + DocNo, filename);
- }
- else
- {
- filename = outputPath + "\\rejected\\" + filename;
- }
- using (Document document = new Document())
- {
- if (!Directory.Exists(filename)) Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename));
- PdfCopy copy = new PdfCopy(document, new FileStream(filename, FileMode.Create));
- document.Open();
- copy.AddPage(copy.GetImportedPage(reader, pagenumber));
- }
- if (string.IsNullOrEmpty(DocNo))
- {
- log.Error("A document number could not be retrieved from page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name);
- }
- else if ((string.IsNullOrEmpty(toAddress) || !ValidateAddress(toAddress)))
- {
- log.Warn("One or more eMail addresses on page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " is invalid");
- }
- log.Info("Completed page extraction of page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + filename);
- //if (!Directory.Exists(outputPath + "\\Transaction Logs\\")) Directory.CreateDirectory(outputPath + "\\Transaction Logs\\");
- ////Write Tansactions Logs
- //using (StreamWriter sw = new StreamWriter(outputPath + "\\Transaction Logs\\" + System.IO.Path.GetFileName(filename.Replace(".pdf", ".txt"))))
- //{
- // sw.WriteLine(toAddress);
- // sw.WriteLine(DocNo);
- // sw.WriteLine(DocumentFolder);
- // sw.WriteLine(DocumentCategory);
- // sw.WriteLine(fromAddress);
- //}
- //write log
- AuditLog(DocNo, DocumentFolder, DocumentCategory, toAddress, fromAddress, "SPLIT - " + pagenumber + " of " + reader.NumberOfPages);
- //}
- //else
- //{
- // log.Error("Page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " did not contain the correct formula");
- //}
- }
- catch (Exception ex)
- {
- log.Error("Failed page extraction of page " + pagenumber.ToString() + " of " + reader.NumberOfPages.ToString() + " of file " + file.Name + " with error - " + ex.Message);
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- //return sbLog.ToString();
- }
- public static bool GetTemplateValues(string folderProcessed)
- {
- try
- {
- foreach (Template template in serviceProperties.Templates)
- {
- if (template.TemplateName.Trim().ToLower() == folderProcessed.Trim().ToLower())
- {
- log.Info("Matching Template found, Populating values");
- smtpUserName = template.SmtpUserName;
- smtpPassword = template.SmtpPassword;
- smtpFrom = template.SmtpFrom;
- Body = template.Body;
- Subject = template.Subject;
- CC = template.CC;
- DocumentCategory = string.IsNullOrWhiteSpace(DocumentCategory) ? template.DocumentCategory : DocumentCategory;
- XMLField = template.XMLField;
- embeddedImagePath = template.EmbeddedImagePath;
- BCC = template.BCC;
- replyToAddress = template.SmtpReplyTo;
- waterMarkText = template.WatermarkPrint;
- table = template.Table;
- toAddress = string.IsNullOrWhiteSpace(toAddress) ? template.DefaultToEmail : toAddress;
- return true;
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- return false;
- }
- log.Error("No matching Template was found");
- return false;
- }
- static byte[] GetBytes(string str)
- {
- try
- {
- byte[] bytes = new byte[str.Length * sizeof(char)];
- System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
- return bytes;
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- public static void DecryptPDF(string inputFile)
- {
- try
- {
- PdfReader.unethicalreading = true;
- using (PdfReader reader = new PdfReader(inputFile, GetBytes("D0cuV1s10n")))
- {
- PdfReader.unethicalreading = true;
- using (MemoryStream memoryStream = new MemoryStream())
- {
- using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
- {
- stamper.SetFullCompression();
- //File.Delete(inputFile);
- File.WriteAllBytes(inputFile + "_decrypt", memoryStream.ToArray());
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- public static void EncryptPDF(string input)
- {
- try
- {
- PdfReader.unethicalreading = true;
- using (PdfReader reader = new PdfReader(input))
- {
- PdfReader.unethicalreading = true;
- if (File.Exists(input.Replace(".pdf", ".nef"))) File.Delete(input.Replace(".pdf", ".nef"));
- using (FileStream fs = new FileStream(input.Replace(".pdf", ".nef"), FileMode.Create))
- {
- using (PdfStamper stamper = new PdfStamper(reader, fs))
- {
- try
- {
- stamper.SetEncryption(null, GetBytes("D0cuV1s10n"), PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_256);
- stamper.SetFullCompression();
- stamper.Reader.RemoveUnusedObjects();
- stamper.FormFlattening = true;
- }
- catch (Exception ex)
- {
- //if (ex.Message == "PdfReader not opened with owner password")
- //{
- // File.Delete(input.Replace(".pdf", ".nef"));
- // return;
- //}
- //File.Copy(input, input.Replace(".pdf", ".nef"));
- log.Error(ex.Message, ex);
- }
- //File.Delete(input);
- //File.Move(input.Replace(".pdf", ".nef"), input);
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- public static string MergePDF(string[] InFiles, string OutFile)
- {
- try
- {
- OutFile = OutFile + "-" + Guid.NewGuid().ToString().ToUpper().Replace("-", string.Empty);
- string response = string.Empty;
- if (File.Exists(OutFile)) return OutFile; //+ " merged successfully 0x00001";
- using (FileStream fileStream = new FileStream(OutFile, FileMode.Create))
- {
- using (Document document = new Document())
- {
- using (PdfCopy pdfCopy = new PdfCopy(document, fileStream))
- {
- document.Open();
- for (int i = 0; i < InFiles.Length; i++)
- {
- try
- {
- PdfReader.unethicalreading = true;
- using (PdfReader pdfReader = new PdfReader(InFiles[i]))
- {
- PdfReader.unethicalreading = true;
- for (int j = 0; j < pdfReader.NumberOfPages; j++)
- {
- pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, j + 1));
- }
- pdfCopy.FreeReader(pdfReader);
- }
- }
- catch (Exception ex)
- {
- log.Error(string.Format("Failed to merge file : {0}, with error : {1}", InFiles[i], ex.Message));
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- return OutFile;
- }
- public static void SendMail(string eMailAddress, string FileName, string templateCode)
- {
- FileInfo file = new FileInfo(FileName);
- using (SmtpClient smtp = new SmtpClient())
- {
- try
- {
- string strName = Guid.NewGuid().ToString().ToUpper().Replace("-", string.Empty);
- //if (!setMailValues(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\eMailer Templates.xml", templateCode))
- //if (!GetTemplateValues(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\eMailer Templates.xml", templateCode))
- //{
- // log.Error("A template has not been setup fo the folder " + templateCode + " or the template is incorrect");
- // return;
- //}
- #region Normal
- smtp.Port = smtpPort;
- smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //TODO: Check if this should be parameterized
- smtp.EnableSsl = ssl;
- smtp.Timeout = smtpTimeOut;
- smtp.Host = smtpHost;
- if (!string.IsNullOrEmpty(smtpPassword) & !string.IsNullOrEmpty(smtpUserName))
- {
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new NetworkCredential(smtpUserName.TrimStart().TrimEnd(), smtpPassword.TrimStart().TrimEnd());
- }
- else
- {
- smtp.UseDefaultCredentials = true;
- }
- #endregion
- //if (!string.IsNullOrEmpty(config.AppSettings.Settings["TestMail"].Value))
- if (!string.IsNullOrEmpty(serviceProperties.TestEmail))
- {
- //eMailAddress = config.AppSettings.Settings["TestMail"].Value;
- eMailAddress = serviceProperties.TestEmail;
- }
- using (MailMessage mail = new MailMessage())
- {
- string[] arrAddresses = eMailAddress.Split(';');
- if (arrAddresses.Count() != 0)
- {
- foreach (var item in arrAddresses)
- {
- if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
- {
- mail.To.Add(new MailAddress(item.ToString()));
- }
- }
- }
- else
- {
- mail.To.Add(new MailAddress(eMailAddress));
- }
- if (!string.IsNullOrEmpty(replyToAddress))
- {
- mail.ReplyToList.Add(new MailAddress(replyToAddress));
- }
- if (!string.IsNullOrEmpty(fromAddress))
- {
- //mail.Sender = new MailAddress(fromAddress);
- try
- {
- mail.From = new MailAddress(fromAddress);
- log.Info("From address : " + fromAddress);
- }
- catch (Exception ex)
- {
- log.Error("Invalid email address in From field found, " + fromAddress + "\n" + ex.Message);
- }
- }
- else if (!string.IsNullOrEmpty(smtpFrom))
- {
- log.Warn("No From Address found, using the Template Default: " + smtpFrom);
- mail.From = new MailAddress(smtpFrom);
- }
- mail.IsBodyHtml = true; //TODO make this configurable
- if (!string.IsNullOrEmpty(CC) & CC != " ")
- {
- string[] arrAddressesCC = CC.Split(';');
- if (arrAddressesCC.Count() != 0)
- {
- foreach (var item in arrAddressesCC)
- {
- if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
- {
- mail.CC.Add(new MailAddress(item.ToString()));
- }
- }
- }
- else
- {
- mail.CC.Add(new MailAddress(CC));
- }
- }
- if (!string.IsNullOrEmpty(BCC) & BCC != " ")
- {
- string[] arrAddressesBCC = BCC.Split(';');
- if (arrAddressesBCC.Count() != 0)
- {
- foreach (var item in arrAddressesBCC)
- {
- if (!string.IsNullOrEmpty(item.ToString()) & !string.IsNullOrWhiteSpace(item.ToString()))
- {
- mail.Bcc.Add(new MailAddress(item.ToString()));
- }
- }
- }
- else
- {
- mail.Bcc.Add(new MailAddress(BCC));
- }
- }
- mail.Attachments.Add(new Attachment(file.FullName));
- //mail.Subject = Subject; //TODO: Create Text Parser, where we substitude values <##>
- dicParser.Add("DocNo", DocNo);
- dicParser.Add("DocumentCategory", DocumentCategory);
- Subject = ExpressionParser(Subject ?? "", dicParser);
- mail.Subject = Subject;
- mail.Body = ExpressionParser(Body ?? "", dicParser);
- dicParser.Clear(); //TODO : resolve this better
- //if (File.Exists(Body))
- if (!string.IsNullOrEmpty(embeddedImagePath) & embeddedImagePath != " ")
- {
- if (File.Exists(embeddedImagePath))
- {
- log.Info("Embedded Image found.");
- AlternateView avHtml = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html);
- // Create a LinkedResource object for the embedded image
- LinkedResource pic1 = new LinkedResource(embeddedImagePath, MediaTypeNames.Image.Jpeg);
- pic1.ContentId = "Pic1";
- avHtml.LinkedResources.Add(pic1);
- // Add the alternate views instead of using MailMessage.Body
- mail.AlternateViews.Add(avHtml);
- }
- }
- ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; //TODO: WTF is this???
- smtp.Send(mail);
- log.Info(file.Name + " successfully sent to " + eMailAddress);
- //sbLog.Append("[" + DateTime.Now + "] " + file.Name + " successfully sent to " + eMailAddress);
- //log.Debug($"TODO DELETE, BEFORE DELETE (EMAIL) {file.FullName.Replace(file.Name, strName)}");
- //File.Delete(file.FullName.Replace(file.Name, strName));
- string To_Address = "";
- foreach (var address in mail.To)
- {
- To_Address += address.Address + ";";
- }
- AuditLog(DocNo, DocumentFolder, DocumentCategory, To_Address, mail.From.Address, "EMAIL");
- }
- }
- catch (SmtpException ex)
- {
- dicParser.Clear();
- log.Error(file.Name + " failed to send to " + eMailAddress + " with the error - " + ex.Message, ex);
- throw;
- //sbLog.Append("[" + DateTime.Now + "] " + file.Name + " failed to send to " + eMailAddress + " with the error - " + ex.Message + "-" + ex.InnerException);
- }
- catch (Exception ex)
- {
- dicParser.Clear();
- log.Error(ex.Message, ex);
- throw;
- //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);
- }
- }
- }
- public static string ExpressionParser(string inputString, Dictionary<string, string> arrValues)
- {
- string retVal = inputString;
- try
- {
- //loop through keys
- foreach (string item in arrValues.Keys)
- {
- string replaceKey = string.Concat("<#", item, "#>");
- string replaceVal = string.Empty;
- if (inputString.Contains(replaceKey))
- {
- //Retrieve Values from Keys
- arrValues.TryGetValue(item, out replaceVal);
- retVal = retVal.Replace(replaceKey, replaceVal);
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw ex;
- }
- return retVal;
- }
- public static void AddWatermarkText(string Type, string sourceFile, string outputFile, string watermarkText, BaseFont watermarkFont = null, float watermarkFontSize = 48f, BaseColor watermarkFontColor = null, float watermarkFontOpacity = 0.3f, float watermarkRotation = 45f)
- {
- iTextSharp.text.Rectangle pageSizeWithRotation = null;
- int numberOfPages = 0;
- try
- {
- PdfReader.unethicalreading = true;
- using (PdfReader pdfReader = new PdfReader(sourceFile))
- {
- PdfReader.unethicalreading = true;
- pageSizeWithRotation = pdfReader.GetPageSizeWithRotation(1);
- using (FileStream fs = new FileStream(outputFile, FileMode.Create))
- {
- using (PdfStamper pdfStamper = new PdfStamper(pdfReader, fs))
- {
- if (watermarkFont == null)
- {
- watermarkFont = BaseFont.CreateFont("Helvetica", "Cp1252", false);
- }
- if (watermarkFontColor == null)
- {
- watermarkFontColor = BaseColor.RED;
- }
- PdfGState pdfGState = new PdfGState()
- {
- FillOpacity = watermarkFontOpacity,
- StrokeOpacity = watermarkFontOpacity
- };
- numberOfPages = pdfReader.NumberOfPages;
- for (int i = 1; i <= numberOfPages; i++)
- {
- PdfContentByte overContent = pdfStamper.GetOverContent(i);
- overContent.SaveState();
- overContent.SetGState(pdfGState);
- overContent.SetColorFill(watermarkFontColor);
- overContent.BeginText();
- overContent.SetFontAndSize(watermarkFont, watermarkFontSize);
- overContent.SetTextMatrix(30f, 30f);
- overContent.ShowTextAligned(1, watermarkText, pageSizeWithRotation.Width / 2f, pageSizeWithRotation.Height / 2f, watermarkRotation);
- overContent.EndText();
- overContent.RestoreState();
- }
- pdfStamper.Writer.CloseStream = false;
- pdfStamper.FormFlattening = true;
- }
- }
- }
- }
- catch (Exception exception)
- {
- throw exception;
- }
- }
- public static void AuditLog(string Docno, string DocType, string DocCat, string To_Address, string From_Address, string Action)
- {
- try
- {
- using (StreamWriter sw = new StreamWriter(System.IO.Path.Combine(auditPath, "Auditlog_" + DateTime.Now.ToShortDateString().Replace('/', '-')) + ".psv", true))
- {
- sw.WriteLine($"{Docno}|{DocType}|{DocCat}|{To_Address}|{From_Address}|{Action}|{DateTime.Now}");
- }
- }
- catch (Exception ex)
- {
- log.Error("Error Occurred while writing the Auditing File: ", ex);
- throw;
- }
- }
- #endregion
- }
- public class LicenseModule
- {
- static log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- public bool checkLicense(string licensePath, string product)
- {
- try
- {
- log.Info(String.Format("Checking if license file exists in '{0}'", licensePath + "\\license.dvlf"));
- bool valid = false;
- if (File.Exists(licensePath + "\\license.dvlf"))
- {
- log.Info("License file found. Decrypting license file");
- DecryptFile(licensePath + "\\license.dvlf", licensePath + "\\license.tmp");
- using (StreamReader reader = new StreamReader(licensePath + "\\license.tmp"))
- {
- string mac = reader.ReadLine();
- string date = reader.ReadLine();
- string licenseProduct = reader.ReadLine();
- log.Info(String.Format("License details:\nMAC Address:{0}\nDate:{1}\nLicense Product:{2}", mac, date, licenseProduct));
- File.Delete(licensePath + "\\license.tmp");
- DateTime dt = Convert.ToDateTime(date);
- log.Info(String.Format("Validating license..."));
- if (GetMACAddress().Contains(mac) & dt > DateTime.Now & licenseProduct.ToLower() == product.ToLower())
- {
- log.Info("License is valid");
- valid = true;
- }
- else
- {
- log.Info("License is invalid");
- }
- }
- }
- return valid;
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- return false;
- }
- }
- public ArrayList GetMACAddress()
- {
- try
- {
- ArrayList addresses = new ArrayList();
- NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
- String sMacAddress = string.Empty;
- foreach (NetworkInterface adapter in nics)
- {
- IPInterfaceProperties properties = adapter.GetIPProperties();
- addresses.Add(adapter.GetPhysicalAddress().ToString());
- }
- return addresses;
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- private void EncryptFile(string inputFile, string outputFile)
- {
- try
- {
- string password = @"dvKey619"; // Your Key Here
- UnicodeEncoding UE = new UnicodeEncoding();
- byte[] key = UE.GetBytes(password);
- string cryptFile = outputFile;
- using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create))
- {
- using (RijndaelManaged RMCrypto = new RijndaelManaged())
- {
- using (CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write))
- {
- using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
- {
- int data;
- while ((data = fsIn.ReadByte()) != -1)
- {
- cs.WriteByte((byte)data);
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- }
- }
- private void DecryptFile(string inputFile, string outputFile)
- {
- try
- {
- log.Info("Setting descryption password");
- string password = @"dvKey619"; // Your Key Here
- UnicodeEncoding UE = new UnicodeEncoding();
- log.Info("Reading license bytes");
- byte[] key = UE.GetBytes(password);
- using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
- {
- using (RijndaelManaged RMCrypto = new RijndaelManaged())
- {
- log.Info("Creating crypto stream");
- using (CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read))
- {
- using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
- {
- int data;
- while ((data = cs.ReadByte()) != -1)
- {
- fsOut.WriteByte((byte)data);
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- }
- public class Config
- {
- static log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- public bool checkConfig()
- {
- try
- {
- log.Info("Checking configuration");
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- string inputPath = config.AppSettings.Settings["InputPath"].Value;
- string outputPath = config.AppSettings.Settings["OutputPath"].Value;
- string smtpHost = config.AppSettings.Settings["smtpHost"].Value;
- string smtpPort = config.AppSettings.Settings["smtpPort"].Value;
- string archive = config.AppSettings.Settings["Archive"].Value.ToLower();
- if (string.IsNullOrEmpty(inputPath) | string.IsNullOrEmpty(outputPath) | string.IsNullOrEmpty(smtpHost) | string.IsNullOrEmpty(smtpPort) | string.IsNullOrEmpty(archive))
- {
- log.Info("Configuration is invalid. Please confirm configuration properties");
- return false;
- }
- log.Info("Configuration checking complete");
- return true;
- }
- catch (Exception ex)
- {
- log.Error(ex.Message, ex);
- throw;
- }
- }
- }
- }