Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

195 строки
9.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Timers;
  5. using Microsoft.Identity.Client;
  6. using Microsoft.Exchange.WebServices.Data;
  7. using System.IO;
  8. using importer.ImportObjects;
  9. namespace importer
  10. {
  11. class Program
  12. {
  13. private static List<ToDo> _todos;
  14. private static string _jdislog;
  15. private static string[] _args;
  16. public static string[] Args { get { return _args; } set { _args = value; } }
  17. private static int[] TimeParts(int t)
  18. {
  19. string st = t.ToString();
  20. if (st.Length == 1) st = "0" + st;
  21. string st1 = st.Substring(0, 1);
  22. string st2 = st.Substring(1, 1);
  23. int[] ints = new int[2];
  24. ints[0] = Convert.ToInt32(st1);
  25. ints[1] = Convert.ToInt32(st2);
  26. return ints;
  27. }
  28. static async System.Threading.Tasks.Task Main(string[] args)
  29. {
  30. bool hasRun = false;
  31. _args = args;
  32. Global global = new Global(args);
  33. if (_args[0] == "brandt")
  34. {
  35. _jdislog = Path.Combine(Global.StorageDir, "jdis.log");
  36. JDISLog.Begin(_jdislog);
  37. JDISImport.BuildDefaults();
  38. for (; ; )
  39. {
  40. int minute = DateTime.Now.Minute;
  41. int[] timeParts = TimeParts(minute);
  42. if (
  43. (timeParts[0] == 0 && timeParts[1] == 0) ||
  44. (timeParts[0] == 1 && timeParts[1] == 5) ||
  45. (timeParts[0] == 3 && timeParts[1] == 0) ||
  46. (timeParts[0] == 4 && timeParts[1] == 5) ||
  47. (timeParts[0] == 0 && timeParts[1] == 5)
  48. )
  49. {
  50. if (!hasRun)
  51. {
  52. JDISLog.WriteToLog(_jdislog, string.Format("Beginning Import Procces @ {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
  53. hasRun = true;
  54. await MailService();
  55. }
  56. }
  57. else hasRun = false;
  58. }
  59. }
  60. //add more to the if statement to account for other imports
  61. }
  62. static async System.Threading.Tasks.Task MailService()
  63. {
  64. _todos = new List<ToDo>();
  65. var cca = ConfidentialClientApplicationBuilder
  66. .Create(Global.Settings.MailProperties.AppID)
  67. .WithClientSecret(Global.Settings.MailProperties.SecretV)
  68. .WithTenantId(Global.Settings.MailProperties.TenentID)
  69. .Build();
  70. var ewsScopes = new string[] { Global.Settings.MailProperties.Scope };
  71. var authResult = await cca.AcquireTokenForClient(ewsScopes)
  72. .ExecuteAsync();
  73. // Configure the ExchangeService with the access token
  74. var ewsClient = new ExchangeService();
  75. ewsClient.Url = new Uri(Global.Settings.MailProperties.Url);
  76. ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
  77. ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, Global.Settings.MailProperties.Username);
  78. Mailbox mb = new Mailbox(Global.Settings.MailProperties.Mailbox);
  79. FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
  80. List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
  81. string[] filters = Global.Settings.MailProperties.Filter.Split(';');
  82. foreach (string s in filters)
  83. searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s));
  84. SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
  85. ItemView view = new ItemView(100);
  86. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
  87. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
  88. view.Traversal = ItemTraversal.Shallow;
  89. //Console.WriteLine("Line 90: Finding emails.");
  90. try
  91. {
  92. FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
  93. List<EmailMessage> messages = new List<EmailMessage>();
  94. foreach (EmailMessage message in findResults.Items)
  95. {
  96. message.Load();
  97. if (!message.IsRead)
  98. messages.Add(message);
  99. }
  100. foreach (EmailMessage msg in messages)
  101. {
  102. if (msg.HasAttachments)
  103. {
  104. foreach (Attachment attachment in msg.Attachments)
  105. {
  106. attachment.Load();
  107. if (attachment is FileAttachment)
  108. {
  109. ToDo todo = new ToDo();
  110. todo.Sender = msg.Sender.Address;
  111. todo.SenderName = msg.Sender.Name;
  112. todo.FileName = attachment.Name;
  113. _todos.Add(todo);
  114. //Download File
  115. FileAttachment fAttachment = attachment as FileAttachment;
  116. string fileAttachmentPath = Path.Combine(Global.StorageDir, fAttachment.Name);
  117. File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
  118. msg.IsRead = true;
  119. msg.Update(ConflictResolutionMode.AlwaysOverwrite);
  120. msg.Move(WellKnownFolderName.DeletedItems);
  121. }
  122. }
  123. }
  124. }
  125. JDISImport.BeginImport(_todos);
  126. foreach (ToDo sendMsg in _todos)
  127. {
  128. EmailMessage msgToSend = new EmailMessage(ewsClient);
  129. //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()));
  130. string body = "JDIS File: {0} Work Order:{1} {2}";
  131. if (sendMsg.Success)
  132. {
  133. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, "Was Imported Successfully");
  134. }
  135. else
  136. {
  137. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
  138. msgToSend.Attachments.AddFileAttachment(Path.Combine(Global.StorageDir, sendMsg.FileName));
  139. }
  140. string fileNameOnly = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1);
  141. msgToSend.Subject = fileNameOnly;
  142. msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
  143. msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
  144. msgToSend.Body = body;
  145. msgToSend.SendAndSaveCopy();
  146. string pathToFile = Path.Combine(Global.StorageDir, sendMsg.FileName);
  147. if (sendMsg.Success)
  148. {
  149. File.Move(pathToFile, Path.Combine(Global.StorageDir, "success", sendMsg.FileName), true);
  150. 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()));
  151. }
  152. else
  153. {
  154. File.Move(sendMsg.FileName, Path.Combine(Global.StorageDir, "failure", sendMsg.FileName), true);
  155. 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()));
  156. }
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. Console.WriteLine(ex.Message);
  162. }
  163. }
  164. }
  165. public class ToDo
  166. {
  167. public string Sender { get; set; }
  168. public string SenderName { get; set; }
  169. public string FileName { get; set; }
  170. public string PathToFile { get; set; }
  171. public string WorkOrderNumber { get; set; }
  172. public bool Success { get; set; }
  173. public string Validation { get; set; }
  174. public WorkOrderImport WorkOrder { get; set; }
  175. public CustomerImport Customer { get; set; }
  176. public EquipmentImport Equipment { get; set; }
  177. public List<PartImport> Parts { get; set; }
  178. }
  179. }