private async Task SendMessages(DispatchMessage message) { List <SubscriberByOriginationDestination> ds = new List <SubscriberByOriginationDestination>(); int matchedSubscribers = 0; matchedSubscribers = await LookForMatchedSubscribers(message, ds); var matchingSubscriberIds = from a in ds.AsEnumerable() select a.EmailAddress; Logger.Debug("All matching addresses after check: {0}", string.Join(",", matchingSubscriberIds.ToList())); if (matchedSubscribers == 0) { Logger.Info("No subscriber matched origination <{0}>, destination <{1}>, xreceiver:<{2}>", message.Originationemailaddress, message.Destinationemailaddress, message.XReceiver); await Task.Run(() => SaveUnmatchedDispatch(message)); var errorMessageBody = $"Messages on server {Environment.MachineName} could not be matched to a subscriber. <{message.Originationemailaddress}><{message.Destinationemailaddress}>|<{message.XSender}><{message.XReceiver}>."; await Task.Run(() => ConfirmUnprocessedMessage(errorMessageBody, false)); } Logger.Debug("Will send messages to each confirmed subscriber"); await Task.Run(() => SendEmailToConfirmedSubscribers(ds, message)); }
public ConsumerDispatchContext(ConsumeContext <DispatchMessage> context, string body) : base(context) { _message = context.Message; Body = body; }
public static string GetHTMLString(DispatchMessage dispatchMessage) { var sb = new StringBuilder(); sb.Append($@" <html> <head> </head> <body> <div class='header'><h1>Reporting Service</h1></div> <table align='center'> <tr> <th>Fullname</th> <th>Email</th> </tr> <tr> <td>{dispatchMessage.Fullname}</td> <td>{dispatchMessage.Email}</td> </tr> </table> </body> </html>"); return(sb.ToString()); }
/// <summary> /// 检查消息队列,运行其中的代理函数 /// </summary> /// <param name="msg"></param> private void DispatchInvoke(DispatchMessage msg) { if (msg.function != null) { msg.function(msg.param); } }
public void CreateDispatchMessage(DispatchMessage dispatchMessage) { using (var db = new LiteDatabase(CurrentDb)) { var col = db.GetCollection <DispatchMessage>("DispatchMessages"); col.Insert(dispatchMessage); } }
private static bool IsRecentDate(DispatchMessage lastDispatchMessage) { DateTime convertedDate = UtilsHelper.UtilsHelper.ParseDateTime(lastDispatchMessage.Arrivedon, new DateTime(1900, 1, 1)); int MaxTimeSpan = UtilsHelper.UtilsHelper.ParseInt(_AppSettings.MaxMessageSpan, 1); return((DateTime.UtcNow - convertedDate).TotalMinutes <= MaxTimeSpan); }
// Update is called once per frame void Update() { // 检查需要回到主线程的调用 while (dispathMessageQueue.Count > 0) { DispatchMessage msg = (DispatchMessage)dispathMessageQueue.Dequeue(); DispatchInvoke(msg); } }
public async Task Handle(Message message, CancellationToken token = default(CancellationToken)) { _logger.LogInformation($"Receiving message {message}"); var dispatchMessage = DispatchMessage.FromMessage(message); _logger.LogInformation($"Sending dispatch message {dispatchMessage}..."); await _messageBus.PublishAsync(dispatchMessage); }
/// <summary> /// 添加消息处理 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="callback"></param> public void AddMessageHand <T>(DispatchMessage callback) where T : MessageHeader, new() { if (callback == null) { return; } var t = new T(); Client.Instance.AddMessageParse(t.ID, this.UnpackMessage); _handlers.Add(t.ID, callback); _types.Add(t.ID, t); }
public async Task Post([FromBody] Message message) { try { DispatchMessage dispatchMessage = Mapper.Map <Message, DispatchMessage>(message); await Task.Run(() => _processor.ProcessMessage(dispatchMessage)); } catch (Exception ex) { Logger.Error(ex.Message); throw new Exception(ex.Message); } }
public void SendMessage(DispatchMessage message, Task whenPosted) { try { Task.Factory.StartNew(async() => { await SendMessage(IncidentMessage.FromDispatchMessage(message)); }); } catch (Exception e) { Logger.Error("Could not send a dispatch message - request did not start: {0}, {1} - {2} ", message.Subscriberid, message.Messagesubject, e); } }
public static IncidentMessage FromDispatchMessage(DispatchMessage incidentMessage) { return(new IncidentMessage { Id = incidentMessage.Id, ArrivedOn = incidentMessage.Arrivedon, Header = incidentMessage.Messageheader, Body = incidentMessage.Messagebody, DestinationEmailAddress = incidentMessage.Destinationemailaddress, OriginationEmailAddress = incidentMessage.Originationemailaddress, SubscriberId = incidentMessage.Subscriberid, Subject = incidentMessage.Messagesubject, DispatchMessageAPI = true }); }
private async Task <int> LookForMatchedSubscribers(DispatchMessage message, List <SubscriberByOriginationDestination> ds) { Logger.Debug("Checking all originations vs all destinations"); int retries = 1; int matchingAttempts = 1; int matchedSubscribers = 0; ds = default(List <SubscriberByOriginationDestination>); while (retries <= 5) { try { while (matchedSubscribers == 0 && matchingAttempts <= 3) { ds = message.XReceiver.ToLower().Contains(_AppSettings.Domain) ? await _dataAccessProcessor.GetSubscriberByOriginationDestination( string.Join(",", (object)message.Originationemailaddress, message.XSender), string.Join(",", (object)message.XReceiver, message.Destinationemailaddress)) : await _dataAccessProcessor.GetSubscriberByOriginationDestination( string.Join(",", (object)message.Originationemailaddress, message.XSender), message.Destinationemailaddress); matchedSubscribers = (ds == null) ? 0 : UtilsHelper.UtilsHelper.ParseInt(ds.Count, 0); //if (matchedSubscribers == 0 && matchingAttempts < 3) //Thread.Sleep(5000); matchingAttempts++; } Logger.Info("Number of matched subscribers for Origination <{0}> and destination <{1}> are {2}", string.Join(",", (object)message.Originationemailaddress, message.XSender), string.Join(",", (object)message.Destinationemailaddress, message.XReceiver), matchedSubscribers); return(matchedSubscribers); } catch (Exception exception) { Logger.Error("EXCEPTION: SP: GetSubscriberByOriginationDestination. RETRY #{0}", retries, exception); if ((!exception.ToString().Contains("deadlock") && !exception.ToString().Contains("query processor could not start")) || retries == 5) { throw; } //Thread.Sleep(5000); retries++; } } return(matchedSubscribers); }
public void SendMessage() { DispatchMessage dispatchMessage = new DispatchMessage { Id = 0, Arrivedon = DateTime.Now, Messageheader = "X-Sender: [email protected]|X-Receiver: [email protected]|MIME-Version: 1.0|From: [email protected]|To: [email protected]; [email protected]|Date: 21 Jul 2016 13:22:12 -0500|Subject: Unable to process file|Content-Type: text/plain; charset=us-ascii|Content-Transfer-Encoding: quoted-printable|", Messagebody = "File FromXrec.eml on server DF-1211-01 could not be processed. Error: The 'unit1' start tag on line 7 position 6 does not match the end tag of 'units'. Line 10, position 5.\r\n", Destinationemailaddress = "[email protected]; [email protected]", Originationemailaddress = "*****@*****.**", Subscriberid = 0, Messagesubject = "Unable to process file", XSender = "*****@*****.**", XReceiver = "*****@*****.**" }; _processor.ProcessMessage(dispatchMessage); }
public string Create(string guid, SynchronizedConverter converter, DispatchMessage dispatchMessage) { string result = string.Empty; converter.PhaseChanged += Converter_PhaseChanged; converter.ProgressChanged += Converter_ProgressChanged; converter.Finished += Converter_Finished; converter.Warning += Converter_Warning; converter.Error += Converter_Error; var globalSettings = new GlobalSettings { ColorMode = ColorMode.Color, Orientation = Orientation.Portrait, PaperSize = PaperKind.A4, Margins = new MarginSettings { Top = 10 }, //Out = $"{guid}.pdf", DocumentTitle = "PDF Report" }; var objectSettings = new ObjectSettings { PagesCount = true, HtmlContent = TemplateGenerator.GetHTMLString(dispatchMessage), WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = "styles.css" }, HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true }, FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" } }; var document = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings } }; byte[] pdf = converter.Convert(document); result = Convert.ToBase64String(pdf); return(result); }
private async Task <bool> ShouldIgnoreDuplicatedMessage(DispatchMessage message) { DispatchMessage lastDispatchMessage = await _dataAccessProcessor.GetLatestDispatchMessageForSubscriber(message.Subscriberid); if (lastDispatchMessage == null) { Logger.Debug("Did not find any last dispatch message"); return(false); } if (IsSameBody(message, lastDispatchMessage) && IsRecentDate(lastDispatchMessage) && IsRecentDestination(message, lastDispatchMessage)) { Logger.Debug("Ignoring duplicated message"); return(true); } return(false); }
/// <summary> /// Attempts to convert the JSON string to a DiscordDispatchMessage. A return value indicates whether the conversion succeeded. /// </summary> /// <param name="json">JSON string to attempt to parse into a DiscordDispatchMessage.</param> /// <returns>Equivalent DiscordDispatchMessage</returns> public static bool TryParseDispatchMessage(string json, out DispatchMessage msg) { try { var rawmsg = JsonConvert.DeserializeObject <Message>(json); if (rawmsg.OpCode == 0) { msg = JsonConvert.DeserializeObject <DispatchMessage>(json); return(true); } msg = null; return(false); } catch (JsonSerializationException e) { msg = null; return(false); } }
// Update is called once per frame void Update() { if (!HasInit) { return; } // 热键支持 if ((Input.GetKeyDown(KeyCode.M) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))) || inputManager.controllerInput.GetButton(XBoxControllerButton.Menu)) { OpenSystemMenu(); } // 检查需要回到主线程的调用 while (dispathMessageQueue.Count > 0) { DispatchMessage msg = (DispatchMessage)dispathMessageQueue.Dequeue(); DispatchInvoke(msg); } }
public ActionResult EditDisp(DispatchViewModel dispatchModel) { try { var regService = new RegistrationService(); var service = ServiceCreator.GetManagerService(User.Identity.Name); var dispService = ServiceCreator.GetDispatchesService(); var config = regService.FindConfiguration(User.Identity.Name); var dispId = Guid.NewGuid(); var disp = new Dispatch { Host = config.TelegramBotLocation, Id = dispId, Message = dispatchModel.Message, Name = dispatchModel.Name, AccountId = config.AccountId, Done = false }; dispService.CreateDispatch(disp); var allTables = service.GetInActiveTables(); var allChats = new List <long>(); allTables.ForEach(o => { if (!allChats.Contains(o.ChatId)) { allChats.Add(o.ChatId); } }); foreach (var chat in allChats) { var dispMes = new DispatchMessage { DispatchId = dispId, ChatId = chat, Id = Guid.NewGuid(), Send = false }; dispService.CreateDispatchMessage(dispMes); } return(Json(new { isAuthorized = true, isSuccess = true })); } catch (Exception ex) { return(Json(new { isAuthorized = true, isSuccess = false, error = ex.Message })); } }
public async Task ProcessMessage(DispatchMessage dispatchMessage) { try { Logger.Info("Removing Invalid Characters in Message"); dispatchMessage.Messagebody = RemoveInvalidChars(dispatchMessage.Messagebody); if (InvalidMessage(dispatchMessage)) { return; } Logger.Debug("Will remove comments from origination: <{0}>", dispatchMessage.Originationemailaddress); dispatchMessage.Originationemailaddress = RemoveComments(dispatchMessage.Originationemailaddress); Logger.Debug("Comments removed from origination: <{0}>", dispatchMessage.Originationemailaddress); await Task.Run(() => SendMessages(dispatchMessage)); } catch (System.Exception ex) { Logger.Error(ex); throw new Exception(ex.ToString()); } }
public ActionResult ImportTask(HttpPostedFileBase file) { try { var tasks = new TaskFile(file.InputStream).ToTask(); var db = new Context(); List <string> existTasks = new List <string>(); //IsDeviceNet为true设备网 if (GlobalData.IsDeviceNet) { foreach (var task in tasks) { var taskdb = db.DispatchMessages.SingleOrDefault(x => x.TaskNo == task.TaskNo); if (taskdb != null) { //相同编号任务编号的同一版本不能重复导入 existTasks.Add($"{taskdb.TaskNo}({taskdb.PartNo})"); continue; } taskdb = new DispatchMessage { TaskNo = task.TaskNo, PartNo = task.PartNo, BatchNo = task.BatchNo, SeqNo = task.SeqNo, Count = task.Count, FacCode = task.FacCode, WeldNo = task.WeldNo, WelderNo = task.WelderNo, StartTime = task.StartTime, EndTime = task.EndTime, exportTime = task.exportTime, importTime = task.importTime, State = false, showState = task.showState }; db.DispatchMessages.Add(taskdb); db.SaveChanges(); } } if (existTasks.Any()) { return(Json(new { succeed = true, existTasks }, "text/html")); } else { return(Json(new { succeed = true }, "text/html")); } } catch (Exception e) { Log.Error(e.StackTrace); return(Json(new { succeed = false, error = e.Message }, "text/html")); } }
public async Task <IActionResult> Post([FromBody] DispatchRequest dispatchRequest) { // non-forced-to-disposal DispatchResponse response = new DispatchResponse { IsSucceded = true, ResultId = (int)DispatchResponseEnum.Success }; // forced-to-disposal KeyVaultConnectionInfo keyVaultConnectionInfo = null; try { if (string.IsNullOrEmpty(dispatchRequest.Fullname)) { throw new BusinessException((int)DispatchResponseEnum.FailedEmptyFullname); } if (string.IsNullOrEmpty(dispatchRequest.Email)) { throw new BusinessException((int)DispatchResponseEnum.FailedEmptyFullname); } keyVaultConnectionInfo = new KeyVaultConnectionInfo() { CertificateName = ApplicationSettings.KeyVaultCertificateName, ClientId = ApplicationSettings.KeyVaultClientId, ClientSecret = ApplicationSettings.KeyVaultClientSecret, KeyVaultIdentifier = ApplicationSettings.KeyVaultIdentifier }; using (MessageQueueHelper messageQueueHelper = new MessageQueueHelper()) { DispatchMessage dispatchMessage = new DispatchMessage() { Fullname = dispatchRequest.Fullname, Email = dispatchRequest.Email }; await messageQueueHelper.QueueMessageAsync(dispatchMessage, ApplicationSettings.DispatchQueueName, keyVaultConnectionInfo); } } catch (Exception ex) { response.IsSucceded = false; if (ex is BusinessException) { response.ResultId = ((BusinessException)ex).ResultId; } else { response.ResultId = (int)DispatchResponseEnum.Failed; this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } } finally { keyVaultConnectionInfo = null; GC.Collect(); } string message = EnumDescription.GetEnumDescription((DispatchResponseEnum)response.ResultId); this.logger.LogInformation($">> Message information: {message}"); return((response.IsSucceded) ? (ActionResult) new OkObjectResult(new { message = message }) : (ActionResult) new BadRequestObjectResult(new { message = message })); }
private async Task SaveUnmatchedDispatch(DispatchMessage message) { DispatchUnmatchedMessages ds = new DispatchUnmatchedMessages(); int IDvalue = 0; ds.Arrivedon = DateTime.Now; ds.Messageheader = message.Messageheader; ds.Messagesubject = message.Messagesubject; ds.Messagebody = message.Messagebody; ds.Messagefrom = message.Originationemailaddress; ds.Messageto = message.Destinationemailaddress; char[] letters = "@abcdefghijklmnopqrstuvwxyz".ToCharArray(); char[] numbers = "0123456789".ToCharArray(); int letterPosition = -1; int numberPosition = -1; int atPosition = -1; string newDestinationsIDs = string.Empty; string destinationEmailAddress = message.Destinationemailaddress; if (message.XReceiver.ToLower().Contains(_AppSettings.Domain)) { destinationEmailAddress = string.Join(",", (object)message.Destinationemailaddress, message.XReceiver.ToLower()); } string[] destinationIDs = destinationEmailAddress.ToLower().Split(','); foreach (string s in destinationIDs) { letterPosition = s.IndexOfAny(letters); Logger.Debug("string: {0}, letterPosition: {1}", s, letterPosition); if (letterPosition > 0) { newDestinationsIDs = string.Join(",", newDestinationsIDs, s.Substring(0, letterPosition)); } else { numberPosition = s.IndexOfAny(numbers); if ((letterPosition == 0) && (numberPosition > 0)) { string newS = s.Substring(numberPosition); atPosition = newS.IndexOfAny(letters); newDestinationsIDs = string.Join(",", newDestinationsIDs, newS.Substring(0, atPosition)); Logger.Debug("string: {0}, letterPosition: {1}, numberPosition: {2}, newDestinationsIDs: {3}", s, letterPosition, numberPosition, newDestinationsIDs); } } } if (newDestinationsIDs.IndexOf(",", StringComparison.Ordinal) == 0) { newDestinationsIDs = newDestinationsIDs.Substring(1); } Logger.Debug("newDestinationsIDs, suspected subscribers: {0}", newDestinationsIDs); // clean up subscriberIDs newDestinationsIDs = Clean(newDestinationsIDs); List <SubscriberInfoBySubscriberIds> SubscriberDS = await _dataAccessProcessor.GetSubscriberInfoBySubscriberIdsInUnmatchedDispatch(newDestinationsIDs); bool sendUnmatchedDispatchMessage = false; if (SubscriberDS != null && SubscriberDS.Count > 0) { SubscriberInfoBySubscriberIds subscriberInfo = SubscriberDS.FirstOrDefault(); ds.Destsubscriberid = subscriberInfo.Id; ds.Destsubscribername = subscriberInfo.Subscribername; ds.Destsubscriberstatusid = subscriberInfo.Statusid; ds.Destsubscriberstatusname = subscriberInfo.Statusname; sendUnmatchedDispatchMessage = (subscriberInfo.Statusid == 1 || subscriberInfo.Statusid == 7); Logger.Debug("Unmatcheddispatch subscriber information. FullName: {0}, ScreenName: {1}, AgencyLogin: {2}, Status: {3}, County: {4}, State: {5}, From Header: {6}", subscriberInfo.Fullname, subscriberInfo.Subscribername, subscriberInfo.Loginname, subscriberInfo.Statusname, subscriberInfo.Mailingcountry, subscriberInfo.Mailingstate, string.Join(",", message.XSender, message.Originationemailaddress)); Logger.Debug("Send mail with unmatched dispatch subscriber information: {0}", sendUnmatchedDispatchMessage); _dispatchUnmatchedMessagesRepository.AddAsync(ds); Logger.Info("Unmatched dispatch subscriber stored in the database"); if (sendUnmatchedDispatchMessage) { SendUnmatchedDispatchMail(subscriberInfo, string.Join(",", message.XSender, message.Originationemailaddress), message.Messagebody, string.Join(",", message.XReceiver, message.Destinationemailaddress)); } } }
private static bool IsSameBody(DispatchMessage message, DispatchMessage lastDispatchMessage) { return(message.Messagebody == lastDispatchMessage.Messagebody); }
public string AddTask(string xml) { try { // TODO 此处解析XML数据并处理 string AddTask = "AddTask"; Hashtable paras = GetParametersFromXML(xml, AddTask); //检查参数是否存在 string msg = this.CheckParas("TaskNo,PartNo,BatchNo,SeqNo,Count,FacCode,WeldNo,WelderNo,StartTime,EndTime", paras); int code = 00000;//00000代表数据出错 if (msg != "") { return(GetResult(false, msg, code.ToString())); } string TaskNo = paras["TaskNo"].ToString(); string PartNo = paras["PartNo"].ToString(); string BatchNo = paras["BatchNo"].ToString(); string SeqNo = paras["SeqNo"].ToString(); string Count = paras["Count"].ToString(); string FacCode = paras["FacCode"].ToString(); string WeldNo = paras["WeldNo"].ToString(); string WelderNo = paras["WelderNo"].ToString(); string startTime = paras["StartTime"].ToString(); string endTime = paras["EndTime"].ToString(); //写入数据的日志 var dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "WcappFiles"); if (!dirInfo.Exists) { dirInfo.Create(); } var name = AppDomain.CurrentDomain.BaseDirectory + "WcappFiles/" + "DeleteTask" + new Random().Next() + ".txt"; using (var fs = new FileStream(name, FileMode.Create)) { using (var sw = new StreamWriter(fs)) { sw.Write(xml); } } DateTime StartTime = Convert.ToDateTime(startTime); DateTime EndTime = Convert.ToDateTime(endTime); //DateTime StartTime = DateTime.ParseExact(startTime, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); //DateTime EndTime= DateTime.ParseExact(endTime, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); //返回内容即文档中 输出参数描述 中 <![CDATA[ 以内的内容 var db = new Context(); // var dispatch = db.DispatchMessages.SingleOrDefault(x => x.TaskNo == TaskNo); var processes = from p in db.Processes group p by p.No into g select g.FirstOrDefault(x => x.Version == g.Max(y => y.Version)); foreach (var process in processes.ToList()) { if (process.PartNo != null) { foreach (var proceduce in process.Procedures) { if (PartNo == process.PartNo && SeqNo == proceduce.No) { if (dispatch == null) { dispatch = new DispatchMessage { TaskNo = TaskNo, PartNo = PartNo, BatchNo = BatchNo, SeqNo = SeqNo, Count = Count, FacCode = FacCode, WeldNo = WeldNo, WelderNo = WelderNo, StartTime = StartTime, EndTime = EndTime, State = false, exportTime = DateTime.Now, showState = false }; db.DispatchMessages.Add(dispatch); db.SaveChanges(); return(GetResult(true, "添加派工信息成功", "00001")); } else { return(GetResult(false, "任务单号已存在", "00000")); } } } } } dispatch.showState = true; db.SaveChanges(); return(GetResult(true, "添加派工信息成功", "00001")); } catch (Exception) { return(GetResult(false, "新增派工信息失败!", "00000")); } }
private void ProcessRequestMessage(uint type, uint length, uint associationId, bool isOneWay) { if (Client == null) { SendError(ProtocolError.CannotProcessRequestMessage); return; } // Validate the request and find the method. ServiceMessage messageType; if (!Client.ServiceAssembly.MessagesById.TryGetValue((int)type, out messageType)) { SendError(ProtocolError.InvalidMessageType); return; } // Parse the message. object message = ReadMessage( Client.ServiceAssembly.TypeModel, messageType.Type, (int)length ); // Dispatch the message. var dispatcher = Client.Instance as IProtoMessageDispatcher; if (dispatcher != null) { if (isOneWay) { dispatcher.DispatchPost(message); } else { var dispatchMessage = new DispatchMessage(dispatcher, associationId, this); dispatcher.BeginDispatch(message, dispatchMessage.BeginDispatchCallback, null); } return; } ServiceMethod method; if (!Client.Service.Methods.TryGetValue(messageType, out method)) { SendError(ProtocolError.InvalidMessageType); return; } if (method.IsOneWay != isOneWay) { SendError(method.IsOneWay ? ProtocolError.ExpectedIsOneWay : ProtocolError.ExpectedRequest); return; } // Start processing the message. var pendingRequest = new PendingRequest(message, isOneWay, associationId, method); _pendingRequests.Enqueue(pendingRequest); if (_pendingRequests.Count == 1) { #if _NET_2 || _NET_MD ThreadPool.QueueUserWorkItem(ExecuteRequests, pendingRequest); #else Task.Factory.StartNew(ExecuteRequests, pendingRequest); #endif } }
private static bool IsRecentDestination(DispatchMessage message, DispatchMessage lastDispatchMessage) { return(lastDispatchMessage.Destinationemailaddress.Contains(message.Destinationemailaddress)); }
private async Task SendEmailToConfirmedSubscribers(List <SubscriberByOriginationDestination> ds, DispatchMessage message) { foreach (var item in ds) { if (string.IsNullOrEmpty(item.Id.ToString())) { continue; } message.Subscriberid = UtilsHelper.UtilsHelper.ParseInt(item.Id, 0); Logger.Debug("Parsed subscriber id is: {0}", message.Subscriberid); if (message.Subscriberid == 0) { return; } var subsRow = _dataAccessProcessor.GetSubscriptor(message.Subscriberid); bool UseAttachment = UtilsHelper.UtilsHelper.ParseBool(subsRow.Usedispatchfromattachment, false); Logger.Debug("Origination and destination matched to subscriber: {0}", message.Subscriberid); if (UseAttachment) { Logger.Debug("Getting dispatch from attachments"); message.Messagebody = AttachmentManager.GetMessage(new MailMessage(), _AppSettings.AttachmentsPath, _AppSettings.ValidAttachmentTypes); } // fix for old iOS apps that included data detectors if (message.Messagebody.Contains("<x-apple-data-detectors")) { int iStart = message.Messagebody.ToLower().IndexOf("<x-apple-data-detectors", StringComparison.Ordinal); int iEnd = message.Messagebody.ToLower().IndexOf(">", iStart, StringComparison.Ordinal); string appleDataDetector = message.Messagebody.Substring(iStart, iEnd - iStart + 1); message.Messagebody = message.Messagebody.Replace(appleDataDetector, ""); } // Encode HTML - This prevents cross-site scripting message.Messagebody = WebUtility.HtmlDecode(message.Messagebody); Logger.Debug("Body encoded"); message.Destinationemailaddress = UtilsHelper.UtilsHelper.ParseString(item.EmailAddress); if (await ShouldIgnoreDuplicatedMessage(message)) { continue; } message = _dataAccessProcessor.SaveMessage(message); Logger.Info("Message record saved for subscriber: {0}, message id: {1}", message.Subscriberid, message.Id); _dispatchConnectorService.SendMessage(message, Task.FromResult(0)); } }
public DispatchMessage SaveMessage(DispatchMessage message) { return(_dispatchMessageRepository.AddAsync(message).Result); }
private bool InvalidMessage(DispatchMessage message) { string msgToReplace = ""; string msgToReplaceOnlyWithValidDomain = ""; //bool emptyFlag = false; for (int i = 0; i < message.Destinationemailaddress.Split(',').Count(); i++) { if (i == message.Destinationemailaddress.Split(',').Count() - 1) { msgToReplace += message.Destinationemailaddress.Split(',')[i]; if (message.Destinationemailaddress.Split(',')[i].ToLower().Contains(_AppSettings.Domain)) { msgToReplaceOnlyWithValidDomain += message.Destinationemailaddress.Split(',')[i]; } } else { msgToReplace += message.Destinationemailaddress.Split(',')[i] + ","; if (message.Destinationemailaddress.Split(',')[i].ToLower().Contains(_AppSettings.Domain)) { msgToReplaceOnlyWithValidDomain += message.Destinationemailaddress.Split(',')[i] + ","; } } } // Validating all recipient fields; from custom parser and mailbee. Logger.Debug("Comparing receiver:{0}, xreceiver:{1}, mailbee recipient:{2} with {3}", message.Destinationemailaddress, message.XReceiver, msgToReplace.ToLower(), _AppSettings.Domain); string destinationAddr = message.Destinationemailaddress ?? ""; if (!(!string.IsNullOrEmpty(msgToReplaceOnlyWithValidDomain) || CheckDestinationAddress(destinationAddr, _AppSettings.Domain) || message.XReceiver.ToLower().Contains(_AppSettings.Domain))) { //Should not be processed because it's not within domain Logger.Debug("File won't be processed. Domain: {0}, Mailbee: {1}, recipient:{2}, xreceiver:{3}", _AppSettings.Domain, msgToReplace, destinationAddr, message.XReceiver); ConfirmUnprocessedMessage(string.Format( "File won't be processed. Domain: {0}, Mailbee: {1}, recipient:{2}, xreceiver:{3}. Server: {4}", _AppSettings.Domain, msgToReplace, destinationAddr, message.XReceiver, Environment.MachineName), true); return(true); } message.Destinationemailaddress = msgToReplaceOnlyWithValidDomain; Logger.Debug("Body read"); if (string.IsNullOrEmpty(message.Originationemailaddress)) { // There is no from Logger.Error("Origination [{0}] cannot be parsed. Headers: {1}", message.Originationemailaddress, message.Messageheader); var errorMessageBody = string.Format( "Message in {0} could not be processed due to missing origination.", Environment.MachineName); ConfirmUnprocessedMessage(errorMessageBody, false); return(true); } if (string.IsNullOrEmpty(message.Destinationemailaddress) && string.IsNullOrEmpty(message.XReceiver)) { // There is from but not to nor x-receiver Logger.Error("Destination [{0}] and x-receiver [{1}] cannot be parsed. Headers: {2}", message.Destinationemailaddress, message.XReceiver, message.Messageheader); var errorMessageBody = string.Format( "Message in {0} could not be processed due to missing destination.", Environment.MachineName); ConfirmUnprocessedMessage(errorMessageBody, false); return(true); } return(false); }