using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Timers; using Microsoft.Identity.Client; using Microsoft.Exchange.WebServices.Data; using System.IO; using importer.ImportObjects; namespace importer { class Program { private static List _todos; private static string _jdislog; private static string[] _args; public static string[] Args { get { return _args; } set { _args = value; } } private static int[] TimeParts(int t) { string st = t.ToString(); if (st.Length == 1) st = "0" + st; string st1 = st.Substring(0, 1); string st2 = st.Substring(1, 1); int[] ints = new int[2]; ints[0] = Convert.ToInt32(st1); ints[1] = Convert.ToInt32(st2); return ints; } static async System.Threading.Tasks.Task Main(string[] args) { bool hasRun = false; _args = args; Global global = new Global(args); if (_args[0] == "brandt") { _jdislog = Path.Combine(Global.StorageDir, "jdis.log"); JDISLog.Begin(_jdislog); JDISImport.BuildDefaults(); for (; ; ) { int minute = DateTime.Now.Minute; int[] timeParts = TimeParts(minute); if ( (timeParts[0] == 0 && timeParts[1] == 0) || (timeParts[0] == 1 && timeParts[1] == 5) || (timeParts[0] == 3 && timeParts[1] == 0) || (timeParts[0] == 4 && timeParts[1] == 5) || (timeParts[0] == 0 && timeParts[1] == 5) ) { if (!hasRun) { JDISLog.WriteToLog(_jdislog, string.Format("Beginning Import Procces @ {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString())); hasRun = true; await MailService(); } } else hasRun = false; } } //add more to the if statement to account for other imports } static async System.Threading.Tasks.Task MailService() { _todos = new List(); var cca = ConfidentialClientApplicationBuilder .Create(Global.Settings.MailProperties.AppID) .WithClientSecret(Global.Settings.MailProperties.SecretV) .WithTenantId(Global.Settings.MailProperties.TenentID) .Build(); var ewsScopes = new string[] { Global.Settings.MailProperties.Scope }; var authResult = await cca.AcquireTokenForClient(ewsScopes) .ExecuteAsync(); // Configure the ExchangeService with the access token var ewsClient = new ExchangeService(); ewsClient.Url = new Uri(Global.Settings.MailProperties.Url); ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken); ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, Global.Settings.MailProperties.Username); Mailbox mb = new Mailbox(Global.Settings.MailProperties.Mailbox); FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb); List searchFilterCollection = new List(); string[] filters = Global.Settings.MailProperties.Filter.Split(';'); foreach (string s in filters) searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s)); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray()); ItemView view = new ItemView(100); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); view.Traversal = ItemTraversal.Shallow; //Console.WriteLine("Line 90: Finding emails."); try { FindItemsResults findResults = ewsClient.FindItems(fid, searchFilter, view); List messages = new List(); foreach (EmailMessage message in findResults.Items) { message.Load(); if (!message.IsRead) messages.Add(message); } foreach (EmailMessage msg in messages) { if (msg.HasAttachments) { foreach (Attachment attachment in msg.Attachments) { attachment.Load(); if (attachment is FileAttachment) { ToDo todo = new ToDo(); todo.Sender = msg.Sender.Address; todo.SenderName = msg.Sender.Name; todo.FileName = attachment.Name; _todos.Add(todo); //Download File FileAttachment fAttachment = attachment as FileAttachment; string fileAttachmentPath = Path.Combine(Global.StorageDir, fAttachment.Name); File.WriteAllBytes(fileAttachmentPath, fAttachment.Content); msg.IsRead = true; msg.Update(ConflictResolutionMode.AlwaysOverwrite); msg.Move(WellKnownFolderName.DeletedItems); } } } } JDISImport.BeginImport(_todos); foreach (ToDo sendMsg in _todos) { EmailMessage msgToSend = new EmailMessage(ewsClient); //JDISLog.WriteToLog(_logFile, string.Format("Sending Message to: {0}\r\nFor Work Order: {1}\r\nJDIS File: {2}", sendMsg.Sender, sendMsg.WorkOrderNumber, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim())); string body = "JDIS File: {0} Work Order:{1} {2}"; if (sendMsg.Success) { body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, "Was Imported Successfully"); } else { body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, string.Format("Had Errors while importing: {0}", sendMsg.Validation)); msgToSend.Attachments.AddFileAttachment(Path.Combine(Global.StorageDir, sendMsg.FileName)); } string fileNameOnly = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1); msgToSend.Subject = fileNameOnly; msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender)); msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com")); msgToSend.Body = body; msgToSend.SendAndSaveCopy(); string pathToFile = Path.Combine(Global.StorageDir, sendMsg.FileName); if (sendMsg.Success) { File.Move(pathToFile, Path.Combine(Global.StorageDir, "success", sendMsg.FileName), true); JDISLog.WriteToLog(_jdislog, string.Format("Work Order: {0} Successfully Imported from {1} on {2} {3}", sendMsg.WorkOrderNumber, sendMsg.FileName, DateTime.Now.ToShortTimeString(), DateTime.Now.ToLongTimeString())); } else { File.Move(sendMsg.FileName, Path.Combine(Global.StorageDir, "failure", sendMsg.FileName), true); JDISLog.WriteToLog(_jdislog, string.Format("Work Order: {0} Failed to Import from {1} on {2} {3}", sendMsg.WorkOrderNumber, sendMsg.FileName, DateTime.Now.ToShortTimeString(), DateTime.Now.ToLongTimeString())); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } public class ToDo { public string Sender { get; set; } public string SenderName { get; set; } public string FileName { get; set; } public string PathToFile { get; set; } public string WorkOrderNumber { get; set; } public bool Success { get; set; } public string Validation { get; set; } public WorkOrderImport WorkOrder { get; set; } public CustomerImport Customer { get; set; } public EquipmentImport Equipment { get; set; } public List Parts { get; set; } } }