private CommunicationPoolEntity GetMailContent(Mime message, int messageNumber) { CommunicationPoolEntity mail = null; if (message != null) { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Subject", message.MainEntity.Subject).Add("From", message.MainEntity.From) .Add("MessageId", message.MainEntity.MessageID).Add("MessageNumber", messageNumber).Add("SendDateTime", message.MainEntity.Date).ToInputLogString()); mail = new CommunicationPoolEntity(); mail.SenderAddress = message.MainEntity.From.Mailboxes[0] != null ? message.MainEntity.From.Mailboxes[0].EmailAddress.NullSafeTrim() : "-"; mail.Subject = message.MainEntity.Subject.RemoveExtraSpaces(); mail.Content = ApplicationHelpers.StripHtmlTags(GetMailMessage(message)); mail.PlainText = ApplicationHelpers.RemoveHtmlTags(FindPlainTextInMessage(message)); mail.MessageNumber = messageNumber; mail.SendDateTime = message.MainEntity.Date; MimeEntity[] list = message.Attachments; foreach (MimeEntity part in list) { byte[] bytes; using (var memory = new MemoryStream()) { part.DataToStream(memory); bytes = StreamDataHelpers.ReadDataToBytes(memory); } IList <object> result = StringHelpers.ConvertStringToList(part.ContentTypeString, ';'); var attachment = new AttachmentEntity(); attachment.ContentType = (string)result[0]; attachment.ByteArray = bytes; if (!string.IsNullOrWhiteSpace(part.ContentDisposition_FileName)) { attachment.Filename = part.ContentDisposition_FileName; } else { attachment.Filename = part.ContentType_Name; } mail.Attachments.Add(attachment); } Logger.Info(_logMsg.Clear().SetPrefixMsg("Mail Body").ToSuccessLogString()); } else { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Error Message", "Message is null").ToFailLogString()); } return(mail); }
private CommunicationPoolEntity GetMailContent(Mail_Message message, int messageNumber) { CommunicationPoolEntity mail = null; if (message != null) { string displayName = message.From != null ? message.From[0].DisplayName.NullSafeTrim() : "-"; string senderAddress = message.From != null ? message.From[0].Address.NullSafeTrim() : "-"; string senderName = !string.IsNullOrWhiteSpace(displayName) ? displayName : ApplicationHelpers.GetSenderAddress(senderAddress); string recvDate = message.Date == DateTime.MinValue ? "date not specified" : message.Date.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime); Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Subject", message.Subject).Add("From", senderAddress) .Add("SenderName", senderName).Add("MessageId", message.MessageID).Add("MessageNumber", messageNumber) .Add("RecvDateTime", recvDate).ToInputLogString()); mail = new CommunicationPoolEntity(); mail.SenderAddress = senderAddress; mail.SenderName = senderName; mail.Subject = ApplicationHelpers.StringLimit(message.Subject.RemoveExtraSpaces(), Constants.MaxLength.MailSubject); mail.Content = ApplicationHelpers.StripHtmlTags(GetMailMessage(message)); mail.PlainText = ApplicationHelpers.RemoveHtmlTags(GetMailMessage(message).ReplaceBreaks()); mail.MessageNumber = messageNumber; mail.RecvDateTime = message.Date; MIME_Entity[] list = message.GetAttachments(true, true); if (list != null && list.Length > 0) { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachments").Add("ListSize", list.Length).ToOutputLogString()); foreach (MIME_Entity entity in list) { try { if (entity != null) { string fileName; string dispoType; string contentId = entity.ContentID.ExtractContentID(); string contentType = entity.ContentType.TypeWithSubtype.ToLowerInvariant(); if (entity.ContentDisposition != null) { fileName = entity.ContentDisposition.Param_FileName; dispoType = entity.ContentDisposition.DispositionType; // Retrieve file name from contentType instead. if (string.IsNullOrWhiteSpace(fileName)) { fileName = entity.ContentType.Param_Name; } Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachment").Add("ContentDisposition", "NOT NULL").Add("ContentId", contentId) .Add("FileName", fileName).Add("ContentType", contentType).Add("DispositionType", dispoType).ToInputLogString()); if (entity.Body != null && entity.Body is MIME_b_SinglepartBase) { Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToInputLogString()); byte[] bytes = ((MIME_b_SinglepartBase)entity.Body).Data; if (bytes != null && bytes.Length > 0) { if ((string.IsNullOrWhiteSpace(contentId) || MIME_DispositionTypes.Attachment.Equals(dispoType)) && !string.IsNullOrWhiteSpace(fileName)) { var attachment = new AttachmentEntity(); attachment.ContentType = contentType; attachment.ByteArray = bytes; attachment.Filename = fileName; mail.Attachments.Add(attachment); } if (!string.IsNullOrWhiteSpace(contentId) && MIME_DispositionTypes.Inline.Equals(dispoType) && contentType.IsImage()) { // data:image/png;base64,{0} string base64String = ApplicationHelpers.GetBase64Image(bytes); string newImg = string.Format(CultureInfo.InvariantCulture, "data:{0};base64,{1}", contentType, base64String); string srcImg = string.Format(CultureInfo.InvariantCulture, "cid:{0}", contentId); mail.Content = mail.Content.Replace(srcImg, newImg); Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Attachment").Add("NewImg", newImg).Add("SrcImg", srcImg).ToOutputLogString()); } } Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToSuccessLogString()); } } else { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachment").Add("ContentDisposition", "NULL").Add("ContentId", contentId) .Add("ContentType", contentType).ToInputLogString()); if (entity.Body != null && entity.Body is MIME_b_SinglepartBase) { Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToInputLogString()); byte[] bytes = ((MIME_b_SinglepartBase)entity.Body).Data; if (bytes != null && bytes.Length > 0) { if (!string.IsNullOrWhiteSpace(contentId) && contentType.IsImage()) { // data:image/png;base64,{0} string base64String = ApplicationHelpers.GetBase64Image(bytes); string newImg = string.Format(CultureInfo.InvariantCulture, "data:{0};base64,{1}", contentType, base64String); string srcImg = string.Format(CultureInfo.InvariantCulture, "cid:{0}", contentId); mail.Content = mail.Content.Replace(srcImg, newImg); Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Attachment").Add("NewImg", newImg).Add("SrcImg", srcImg).ToOutputLogString()); } } Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToSuccessLogString()); } } } } catch (Exception ex) { mail.IsDeleted = false; Logger.Error("Exception occur:\n", ex); Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Error Message", ex.Message).ToFailLogString()); } } } else { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachments").Add("ListSize", "0").ToOutputLogString()); } Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Content", mail.Content).ToSuccessLogString()); } else { Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Error Message", "Mail Content is null").ToFailLogString()); } return(mail); }
private List <CommunicationPoolEntity> FetchAllMessages(string hostname, int port, bool useSsl, PoolEntity pool) { var allMessages = new List <CommunicationPoolEntity>(); _commPoolDataAccess = new CommPoolDataAccess(_context); List <ChannelEntity> channels = _commPoolDataAccess.GetActiveChannels(); // Authenticate ourselves towards the server string decryptedstring = StringCipher.Decrypt(pool.Password, Constants.PassPhrase); ConcurrentDictionary <string, Mail_Message> mailMessages = this.GetEmails(hostname, port, useSsl, pool.Email, decryptedstring); // Get the number of messages in the inbox int k = 0; int totalEmails = mailMessages != null ? mailMessages.Count : 0; if (totalEmails <= 0) { goto Outer; } //Messages are numbered in the interval: [1, messageCount] //Ergo: message numbers are 1-based. //Most servers give the latest message the highest number Task.Factory.StartNew(() => Parallel.ForEach(mailMessages, new ParallelOptions { MaxDegreeOfParallelism = WebConfig.GetTotalCountToProcess() }, kvp => { lock (sync) { try { string msgKey = kvp.Key; Logger.Info(_logMsg.Clear().SetPrefixMsg("Prepared CommuPool Object").Add("KeyPairValue (UID)", (!string.IsNullOrWhiteSpace(msgKey) ? msgKey : "NULL")).ToInputLogString()); Mail_Message message; mailMessages.TryGetValue(msgKey, out message); CommunicationPoolEntity mail = GetMailContent(message, k); mail.PoolEntity = pool; mail.UID = msgKey; string mailSubject = !string.IsNullOrWhiteSpace(mail.Subject) ? mail.Subject.Replace(" ", string.Empty) : string.Empty; Match match = Regex.Match(mailSubject, @";\s*[0-9]{1,}\s*;", RegexOptions.IgnoreCase); var emailChannel = channels.FirstOrDefault(x => Constants.ChannelCode.Email.Equals(x.Code)); if (emailChannel == null) { Logger.ErrorFormat("O:--FAILED--:--Do not configure email channel--:EmailChannelCode/{0}", Constants.ChannelCode.Email); throw new CustomException("ERROR: Do not configure email channel"); } if (match.Success && ApplicationHelpers.IsValidEmailDomain(mail.SenderAddress)) { mail.SRNo = mailSubject.ExtractSRNo(); mail.SRStatusCode = mailSubject.ExtractSRStatus(); mail.ChannelEntity = emailChannel; } else { mail.ChannelEntity = channels.FirstOrDefault(x => x.Email != null && x.Email.ToUpperInvariant() == mail.SenderAddress.ToUpperInvariant()) ?? emailChannel; #region "Get Contact Name from KKWebsite" if (mail.ChannelEntity != null && Constants.ChannelCode.KKWebSite.Equals(mail.ChannelEntity.Code)) { string s = mail.PlainText; if (!string.IsNullOrWhiteSpace(s)) { Logger.DebugFormat("I:--START--:--Get Contact Name from KKWebsite--:PlainText/{0}", s); try { IList <object> lines = StringHelpers.ConvertStringToList(s, '\n'); mail.ContactName = (lines.FirstOrDefault(x => x.ToString().Contains(Resource.Lbl_CommFirstname)) as string).ExtractDataField(Resource.Lbl_CommFirstname); mail.ContactSurname = (lines.FirstOrDefault(x => x.ToString().Contains(Resource.Lbl_CommSurname)) as string).ExtractDataField(Resource.Lbl_CommSurname); Logger.DebugFormat("I:--SUCCESS--:--Get Contact Name from KKWebsite--:Contact Name/{0}:Contact Surname/{1}", mail.ContactName, mail.ContactSurname); } catch (Exception ex) { Logger.DebugFormat("O:--FAILED--:--Get Contact Name from KKWebsite--:MainContent/{0}:Error Message/{1}", s, ex.Message); Logger.Error("Exception occur:\n", ex); } } // Clear value mail.PlainText = null; } #endregion } allMessages.Add(mail); Logger.Info(_logMsg.Clear().SetPrefixMsg("Prepared CommuPool Object").ToSuccessLogString()); } catch (Exception ex) { Logger.Info(_logMsg.Clear().SetPrefixMsg("Prepared CommuPool Object").Add("Error Message", ex.Message).ToFailLogString()); Logger.Error("Exception occur:\n", ex); } k++; } })).Wait(); // Now return the fetched messages Outer: var orderedList = allMessages.OrderBy(x => x.RecvDateTime).ToList(); return(orderedList); }
public ActionResult InitEdit(int?jobId = null) { Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Job").Add("JobId", jobId).ToInputLogString()); try { JobViewModel jobVM = null; if (TempData["jobVM"] != null) { jobVM = (JobViewModel)TempData["jobVM"]; } else { jobVM = new JobViewModel { JobId = jobId }; } if (jobVM.JobId != null) { _commPoolFacade = new CommPoolFacade(); CommunicationPoolEntity commPoolEntity = _commPoolFacade.GetJob(jobVM.JobId.Value); jobVM.Sender = commPoolEntity.SenderAddress; jobVM.Subject = commPoolEntity.Subject; jobVM.StatusDisplay = commPoolEntity.StatusDisplay; jobVM.SequenceNo = commPoolEntity.SequenceNo; jobVM.Content = commPoolEntity.Content; jobVM.CreatedDate = commPoolEntity.CreateDateDisplay; jobVM.UpdatedDate = commPoolEntity.UpdateDateDisplay; jobVM.Remark = commPoolEntity.Remark; jobVM.JobStatus = commPoolEntity.Status; if (commPoolEntity.UpdateUser != null) { jobVM.ActionBy = commPoolEntity.UpdateUser.FullName; } if (commPoolEntity.ChannelEntity != null) { jobVM.Channel = commPoolEntity.ChannelEntity.Name; } //SR if (commPoolEntity.ServiceRequest != null) { jobVM.SrNo = commPoolEntity.ServiceRequest.SrNo; jobVM.SR_Status = commPoolEntity.ServiceRequest.Status; jobVM.SrSubject = commPoolEntity.ServiceRequest.Subject; jobVM.SrRemark = commPoolEntity.ServiceRequest.Remark; jobVM.SrChannel = commPoolEntity.ServiceRequest.ChannelName; jobVM.SrMediaSource = commPoolEntity.ServiceRequest.MediaSourceName; jobVM.SrCreateDate = commPoolEntity.ServiceRequest.CreateDateDisplay; if (commPoolEntity.ServiceRequest.CreateUser != null) { jobVM.SrCreateUser = commPoolEntity.ServiceRequest.CreateUser.FullName; } if (commPoolEntity.ServiceRequest.Owner != null) { jobVM.SrOwner = commPoolEntity.ServiceRequest.Owner.FullName; } if (commPoolEntity.ServiceRequest.Delegator != null) { jobVM.SrDelegator = commPoolEntity.ServiceRequest.Delegator.FullName; } if (commPoolEntity.ServiceRequest.UpdateUser != null) { jobVM.SrUpdateUser = commPoolEntity.ServiceRequest.UpdateUser.FullName; } if (commPoolEntity.ServiceRequest.Customer != null) { //Customer jobVM.FirstNameThai = commPoolEntity.ServiceRequest.Customer.FirstNameThai; jobVM.LastNameThai = commPoolEntity.ServiceRequest.Customer.LastNameThai; jobVM.FirstNameEnglish = commPoolEntity.ServiceRequest.Customer.FirstNameEnglish; jobVM.LastNameEnglish = commPoolEntity.ServiceRequest.Customer.LastNameEnglish; } if (commPoolEntity.ServiceRequest.ProductMapping != null) { jobVM.ProductGroup = commPoolEntity.ServiceRequest.ProductMapping.ProductGroupName; jobVM.Product = commPoolEntity.ServiceRequest.ProductMapping.ProductName; jobVM.Type = commPoolEntity.ServiceRequest.ProductMapping.TypeName; jobVM.SubArea = commPoolEntity.ServiceRequest.ProductMapping.SubAreaName; } } // Attachments jobVM.Attachments = commPoolEntity.Attachments; } return(View("~/Views/Job/Edit.cshtml", jobVM)); } catch (Exception ex) { Logger.Error("Exception occur:\n", ex); Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Job").Add("Error Message", ex.Message).ToFailLogString()); return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(), this.ControllerContext.RouteData.Values["action"].ToString()))); } }
private List <CommunicationPoolEntity> FetchAllMessages(string hostname, int port, bool useSsl, PoolEntity pool, out List <string> mailMsgIds) { var allMessages = new List <CommunicationPoolEntity>(); _commPoolDataAccess = new CommPoolDataAccess(_context); List <ChannelEntity> channels = _commPoolDataAccess.GetActiveChannels(); // Authenticate ourselves towards the server string decryptedstring = StringCipher.Decrypt(pool.Password, Constants.PassPhrase); List <Mime> mailMessages = this.GetEmails(hostname, port, useSsl, pool.Email, decryptedstring, out mailMsgIds); //// Get the number of messages in the inbox //int messageCount = mailMessages != null ? mailMessages.Count : 0; //int maxRetriveMail = this.GetMaxRetrieveMail(); //int totalEmails = messageCount > maxRetriveMail ? maxRetriveMail : messageCount; int totalEmails = mailMessages != null ? mailMessages.Count : 0; if (totalEmails <= 0) { goto Outer; } //Messages are numbered in the interval: [1, messageCount] //Ergo: message numbers are 1-based. //Most servers give the latest message the highest number Task.Factory.StartNew(() => Parallel.For(0, totalEmails, new ParallelOptions { MaxDegreeOfParallelism = WebConfig.GetTotalCountToProcess() }, k => { lock (sync) { Mime message = mailMessages[k]; CommunicationPoolEntity mail = GetMailContent(message, k); mail.PoolEntity = pool; vc = new ValidationContext(mail, null, null); var validationResults = new List <ValidationResult>(); bool valid = Validator.TryValidateObject(mail, vc, validationResults, true); if (!valid) { string errorMsg = validationResults.Select(x => x.ErrorMessage).Aggregate((i, j) => i + Environment.NewLine + j); Logger.DebugFormat("I:--START--:--Validate Email Subject--:Subject/{0}:Sender:/{1}:Error Message/{2}", mail.Subject, mail.SenderAddress, errorMsg); } else { string mailSubject = mail.Subject.Replace(" ", String.Empty); Match match = Regex.Match(mailSubject, @";\s*[0-9]{1,}\s*;", RegexOptions.IgnoreCase); var emailChannel = channels.FirstOrDefault(x => Constants.ChannelCode.Email.Equals(x.Code)); if (emailChannel == null) { Logger.ErrorFormat("O:--FAILED--:--Do not configure email channel--:EmailChannelCode/{0}", Constants.ChannelCode.Email); throw new CustomException("ERROR: Do not configure email channel"); } if (!match.Success) { mail.ChannelEntity = channels.FirstOrDefault(x => x.Email == mail.SenderAddress) ?? emailChannel; #region "Get Contact Name from KKWebsite" if (Constants.ChannelCode.KKWebSite.Equals(mail.ChannelEntity.Code)) { string s = mail.PlainText; if (!string.IsNullOrWhiteSpace(s)) { Logger.Debug("I:--START--:--Get Contact Name from KKWebsite--"); try { IList <object> lines = StringHelpers.ConvertStringToList(s, '\n'); mail.ContactName = (lines.FirstOrDefault(x => x.ToString().Contains(Resource.Lbl_CommFirstname)) as string).ExtractDataField(Resource.Lbl_CommFirstname); mail.ContactSurname = (lines.FirstOrDefault(x => x.ToString().Contains(Resource.Lbl_CommSurname)) as string).ExtractDataField(Resource.Lbl_CommSurname); Logger.DebugFormat("I:--SUCCESS--:--Get Contact Name from KKWebsite--:Contact Name/{0}:Contact Surname/{1}", mail.ContactName, mail.ContactSurname); } catch (Exception ex) { Logger.DebugFormat("O:--FAILED--:--Get Contact Name from KKWebsite--:MainContent/{0}:Error Message/{1}", s, ex.Message); Logger.Error("Exception occur:\n", ex); } } // Clear value mail.PlainText = null; } #endregion } else { mail.SRNo = mailSubject.ExtractSRNo(); mail.SRStatusCode = mailSubject.ExtractSRStatus(); mail.ChannelEntity = emailChannel; } allMessages.Add(mail); } } })).Wait(); // Now return the fetched messages Outer: var orderedList = allMessages.OrderBy(x => x.SendDateTime).ToList(); return(orderedList); }