You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 rivejä
9.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Data;
  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. if (_args[0] == "foley")
  61. {
  62. _jdislog = Path.Combine(Global.StorageDir, "foley.log");
  63. JDISLog.Begin(_jdislog);
  64. DataTable data = PDAImport.ReadFile();
  65. //Get Distinct Work Orders;
  66. List<string> list = PDAImport.DistinctWorkOrders(data);
  67. if (list.Count > 0)
  68. {
  69. PDAImport.BuildDefaults();
  70. }
  71. }
  72. //add more to the if statement to account for other imports
  73. }
  74. static async System.Threading.Tasks.Task MailService()
  75. {
  76. _todos = new List<ToDo>();
  77. var cca = ConfidentialClientApplicationBuilder
  78. .Create(Global.Settings.MailProperties.AppID)
  79. .WithClientSecret(Global.Settings.MailProperties.SecretV)
  80. .WithTenantId(Global.Settings.MailProperties.TenentID)
  81. .Build();
  82. var ewsScopes = new string[] { Global.Settings.MailProperties.Scope };
  83. var authResult = await cca.AcquireTokenForClient(ewsScopes)
  84. .ExecuteAsync();
  85. // Configure the ExchangeService with the access token
  86. var ewsClient = new ExchangeService();
  87. ewsClient.Url = new Uri(Global.Settings.MailProperties.Url);
  88. ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
  89. ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, Global.Settings.MailProperties.Username);
  90. Mailbox mb = new Mailbox(Global.Settings.MailProperties.Mailbox);
  91. FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
  92. List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
  93. string[] filters = Global.Settings.MailProperties.Filter.Split(';');
  94. foreach (string s in filters)
  95. searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s));
  96. SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
  97. ItemView view = new ItemView(100);
  98. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
  99. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
  100. view.Traversal = ItemTraversal.Shallow;
  101. //Console.WriteLine("Line 90: Finding emails.");
  102. try
  103. {
  104. FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
  105. List<EmailMessage> messages = new List<EmailMessage>();
  106. foreach (EmailMessage message in findResults.Items)
  107. {
  108. message.Load();
  109. if (!message.IsRead)
  110. messages.Add(message);
  111. }
  112. foreach (EmailMessage msg in messages)
  113. {
  114. if (msg.HasAttachments)
  115. {
  116. foreach (Attachment attachment in msg.Attachments)
  117. {
  118. attachment.Load();
  119. if (attachment is FileAttachment)
  120. {
  121. ToDo todo = new ToDo();
  122. todo.Sender = msg.Sender.Address;
  123. todo.SenderName = msg.Sender.Name;
  124. todo.FileName = attachment.Name;
  125. _todos.Add(todo);
  126. //Download File
  127. FileAttachment fAttachment = attachment as FileAttachment;
  128. string fileAttachmentPath = Path.Combine(Global.StorageDir, fAttachment.Name);
  129. File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
  130. msg.IsRead = true;
  131. msg.Update(ConflictResolutionMode.AlwaysOverwrite);
  132. msg.Move(WellKnownFolderName.DeletedItems);
  133. }
  134. }
  135. }
  136. }
  137. JDISImport.BeginImport(_todos);
  138. foreach (ToDo sendMsg in _todos)
  139. {
  140. EmailMessage msgToSend = new EmailMessage(ewsClient);
  141. //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()));
  142. string body = "JDIS File: {0} Work Order:{1} {2}";
  143. if (sendMsg.Success)
  144. {
  145. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, "Was Imported Successfully");
  146. }
  147. else
  148. {
  149. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
  150. msgToSend.Attachments.AddFileAttachment(Path.Combine(Global.StorageDir, sendMsg.FileName));
  151. }
  152. string fileNameOnly = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1);
  153. msgToSend.Subject = fileNameOnly;
  154. msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
  155. msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
  156. msgToSend.Body = body;
  157. msgToSend.SendAndSaveCopy();
  158. string pathToFile = Path.Combine(Global.StorageDir, sendMsg.FileName);
  159. if (sendMsg.Success)
  160. {
  161. File.Move(pathToFile, Path.Combine(Global.StorageDir, "success", sendMsg.FileName), true);
  162. 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()));
  163. }
  164. else
  165. {
  166. File.Move(sendMsg.FileName, Path.Combine(Global.StorageDir, "failure", sendMsg.FileName), true);
  167. 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()));
  168. }
  169. }
  170. }
  171. catch (Exception ex)
  172. {
  173. Console.WriteLine(ex.Message);
  174. }
  175. }
  176. }
  177. public class ToDo
  178. {
  179. public string Sender { get; set; }
  180. public string SenderName { get; set; }
  181. public string FileName { get; set; }
  182. public string PathToFile { get; set; }
  183. public string WorkOrderNumber { get; set; }
  184. public bool Success { get; set; }
  185. public string Validation { get; set; }
  186. public WorkOrderImport WorkOrder { get; set; }
  187. public CustomerImport Customer { get; set; }
  188. public EquipmentImport Equipment { get; set; }
  189. public List<PartImport> Parts { get; set; }
  190. }
  191. }