Replacement for JDIS Importer
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

892 lignes
43 KiB

  1. using System.Collections.Generic;
  2. using System;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using Microsoft.Identity.Client;
  6. using Microsoft.Exchange.WebServices.Data;
  7. using System.IO;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.Reflection;
  11. /*
  12. Secret Value up-8Q~y46~JyQZjJlsAJ-zpXpglpmuPIJ1Gx3a2O
  13. Secret ID cba04a6c-a233-4646-909b-b50921edbe1c
  14. Client ID 489776b1-ee79-4b14-bc44-9f6bf47332db
  15. Object ID c7647074-edb6-4e8e-8a01-a1ed924fdae9
  16. Tenant ID 1fd06c96-d3a4-45e9-9ed7-bcecb394d277
  17. */
  18. namespace jdis_import
  19. {
  20. class Program
  21. {
  22. private static string _exeDir;
  23. private static bool _log = true;
  24. private static string _connection = "Data Source=192.168.0.7;Initial Catalog=Connexion_Brandt;User ID=mobilepmuser;Password=data4techs;TrustServerCertificate=true;";
  25. private static string _workOrderNumber = string.Empty;
  26. private static List<string> _sqlMessages = new List<string>();
  27. private static bool _newMachine = false;
  28. private static bool _quoted = false;
  29. public static string ExeDir { get { return _exeDir; } }
  30. private static Dictionary<string, string> _keys = new Dictionary<string, string>() { { "SecretV", "up-8Q~y46~JyQZjJlsAJ-zpXpglpmuPIJ1Gx3a2O" }, { "SecretID", "cba04a6c-a233-4646-909b-b50921edbe1c" }, { "ObjectId", "c7647074-edb6-4e8e-8a01-a1ed924fdae9" }, { "TenentID", "1fd06c96-d3a4-45e9-9ed7-bcecb394d277" }, { "AppID", "489776b1-ee79-4b14-bc44-9f6bf47332db" } };
  31. public static Dictionary<string, int> InspectionType;
  32. static async System.Threading.Tasks.Task Main(string[] args)
  33. {
  34. _exeDir = Environment.CurrentDirectory;
  35. SetupDirectories();
  36. List<ToDo> list = new List<ToDo>();
  37. var cca = ConfidentialClientApplicationBuilder
  38. // .Create("1dff6bdb-7009-4d2a-ae0f-9f333a4f182b")
  39. // .WithClientSecret("VOD8Q~7BI9u4ySU0saesCG87TaEtKSCya5vw6as5")
  40. // .WithTenantId("1fd06c96-d3a4-45e9-9ed7-bcecb394d277")
  41. .Create(_keys["AppID"])
  42. .WithClientSecret(_keys["SecretV"])
  43. .WithTenantId(_keys["TenentID"])
  44. .Build();
  45. var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
  46. try
  47. {
  48. var authResult = await cca.AcquireTokenForClient(ewsScopes)
  49. .ExecuteAsync();
  50. // Configure the ExchangeService with the access token
  51. var ewsClient = new ExchangeService();
  52. ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
  53. ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
  54. ewsClient.ImpersonatedUserId =
  55. new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "cmobile@prelub.com");
  56. Mailbox mb = new Mailbox("connexionmobile@rpmindustries.org");
  57. FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
  58. List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
  59. string[] filters = "Brandt Import;BRANDT IMPORT;brandt import;TEST Brandt".Split(';');
  60. foreach (string s in filters)
  61. searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s));
  62. SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
  63. ItemView view = new ItemView(100);
  64. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
  65. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
  66. view.Traversal = ItemTraversal.Shallow;
  67. FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
  68. foreach (EmailMessage msg in findResults.Items)
  69. {
  70. msg.Load();
  71. if (!msg.IsRead)
  72. {
  73. if (msg.HasAttachments)
  74. {
  75. foreach (Attachment attachment in msg.Attachments)
  76. {
  77. attachment.Load();
  78. if (attachment is FileAttachment)
  79. {
  80. ToDo todo = new ToDo();
  81. todo.Sender = msg.Sender.Address;
  82. todo.SenderName = msg.Sender.Name;
  83. todo.FileName = attachment.Name;
  84. list.Add(todo);
  85. //Download File
  86. FileAttachment fAttachment = attachment as FileAttachment;
  87. string fileAttachmentPath = Path.Combine(_exeDir, fAttachment.Name);
  88. File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
  89. msg.IsRead = true;
  90. msg.Update(ConflictResolutionMode.AlwaysOverwrite);
  91. }
  92. }
  93. }
  94. }
  95. }
  96. foreach (ToDo import in list)
  97. {
  98. //Start Importing
  99. BeginImport(import);
  100. GetInspectionTypes();
  101. ReadFile(import);
  102. }
  103. foreach (ToDo sendMsg in list)
  104. {
  105. EmailMessage msgToSend = new EmailMessage(ewsClient);
  106. string body = "JDIS File: {0} Work Order:{1} {2}";
  107. if (sendMsg.Success)
  108. {
  109. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrder, "Was Imported Successfully");
  110. }
  111. else
  112. {
  113. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrder, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
  114. msgToSend.Attachments.AddFileAttachment(Path.Combine(_exeDir, sendMsg.FileName));
  115. }
  116. msgToSend.Subject = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1);
  117. msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
  118. msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
  119. msgToSend.Body = body;
  120. msgToSend.SendAndSaveCopy();
  121. string pathToFile = Path.Combine(_exeDir, sendMsg.FileName);
  122. if (sendMsg.Success) File.Move(pathToFile, Path.Combine(_exeDir, "Success", sendMsg.FileName));
  123. else File.Move(sendMsg.FileName, Path.Combine(_exeDir, "Fail", sendMsg.FileName));
  124. }
  125. }
  126. catch (MsalException ex)
  127. {
  128. Console.WriteLine($"Error acquiring access token: {ex}");
  129. }
  130. catch (Exception ex)
  131. {
  132. Console.WriteLine($"Error: {ex}");
  133. }
  134. if (System.Diagnostics.Debugger.IsAttached)
  135. {
  136. Console.WriteLine("Hit any key to exit...");
  137. Console.ReadKey();
  138. }
  139. }
  140. public static void BeginImport(ToDo todo)
  141. {
  142. XMLData.BuildIntervalLookup();
  143. }
  144. private static void SetupDirectories()
  145. {
  146. string path = Path.Combine(_exeDir, "Success");
  147. if (!Directory.Exists(path))
  148. Directory.CreateDirectory(path);
  149. path = Path.Combine(_exeDir, "Fail");
  150. if (!Directory.Exists(path))
  151. Directory.CreateDirectory(path);
  152. path = Path.Combine(_exeDir, "Log");
  153. if (!Directory.Exists(path))
  154. Directory.CreateDirectory(path);
  155. }
  156. public static void GetInspectionTypes()
  157. {
  158. InspectionType = new Dictionary<string, int>();
  159. SqlConnection con = new SqlConnection("Data Source=192.168.0.7;Initial Catalog=Connexion_Brandt;User ID=mobilepmuser;Password=data4techs;TrustServerCertificate=true;");
  160. con.Open();
  161. SqlCommand cmd = con.CreateCommand();
  162. cmd.CommandTimeout = 0;
  163. cmd.Connection = con;
  164. cmd.CommandText = "Select ID, [Name] From InspectionType";
  165. cmd.CommandType = CommandType.Text;
  166. DataSet ds = new DataSet();
  167. SqlDataAdapter da = new SqlDataAdapter(cmd);
  168. da.Fill(ds);
  169. foreach (DataRow row in ds.Tables[0].Rows)
  170. {
  171. InspectionType.Add(row["Name"].ToString(), Convert.ToInt32(row["ID"]));
  172. }
  173. ds.Dispose();
  174. cmd.Dispose();
  175. con.Close();
  176. con.Dispose();
  177. }
  178. private static string frmtString
  179. {
  180. get
  181. {
  182. if (_quoted) return "\"{0}\"";
  183. else return "{0}";
  184. }
  185. }
  186. private static List<string> WriteFileToText(string file)
  187. {
  188. List<string> list = new List<string>();
  189. string txt = string.Empty;
  190. using (StreamReader sr = new StreamReader(file))
  191. {
  192. txt = sr.ReadToEnd().Trim();
  193. txt = txt.Replace("\r\r\r", "");
  194. txt = txt.Replace("\r\r", "");
  195. txt = txt.Replace("\r", "");
  196. sr.Close();
  197. }
  198. string[] array = txt.Trim().Split('\n');
  199. list.AddRange(array);
  200. return list;
  201. }
  202. private static DateTime DateFormatter(string d, bool hastime = true)
  203. {
  204. string month, day, year, time;
  205. DateTime dt = new DateTime();
  206. if (d.IndexOf("JAN") != -1)
  207. {
  208. month = "01";
  209. d = d.Replace("JAN", "|");
  210. day = d.Substring(0, d.IndexOf("|"));
  211. year = d.Substring(d.IndexOf("|") + 1, 4);
  212. if (hastime)
  213. time = d.Substring(d.IndexOf(":") - 3 + 2);
  214. else time = "00:00:00.000";
  215. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  216. dt = DateTime.Parse(date);
  217. }
  218. else if (d.IndexOf("FEB") != -1)
  219. {
  220. month = "02";
  221. d = d.Replace("FEB", "|");
  222. day = d.Substring(0, d.IndexOf("|"));
  223. year = d.Substring(d.IndexOf("|") + 1, 4);
  224. if (hastime)
  225. time = d.Substring(d.IndexOf(":") - 3 + 2);
  226. else time = "00:00:00.000";
  227. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  228. dt = DateTime.Parse(date);
  229. }
  230. else if (d.IndexOf("MARCH") != -1)
  231. {
  232. month = "03";
  233. d = d.Replace("MARCH", "|");
  234. day = d.Substring(0, d.IndexOf("|"));
  235. year = d.Substring(d.IndexOf("|") + 1, 4);
  236. if (hastime)
  237. time = d.Substring(d.IndexOf(":") - 3 + 2);
  238. else time = "00:00:00.000";
  239. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  240. dt = DateTime.Parse(date);
  241. }
  242. else if (d.IndexOf("MAR") != -1)
  243. {
  244. month = "03";
  245. d = d.Replace("MAR", "|");
  246. day = d.Substring(0, d.IndexOf("|"));
  247. year = d.Substring(d.IndexOf("|") + 1, 4);
  248. if (hastime)
  249. time = d.Substring(d.IndexOf(":") - 3 + 2);
  250. else time = "00:00:00.000";
  251. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  252. dt = DateTime.Parse(date);
  253. }
  254. else if (d.IndexOf("APRIL") != -1)
  255. {
  256. month = "04";
  257. d = d.Replace("APRIL", "|");
  258. day = d.Substring(0, d.IndexOf("|"));
  259. year = d.Substring(d.IndexOf("|") + 1, 4);
  260. if (hastime)
  261. time = d.Substring(d.IndexOf(":") - 3 + 2);
  262. else time = "00:00:00.000";
  263. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  264. dt = DateTime.Parse(date);
  265. }
  266. else if (d.IndexOf("APR") != -1)
  267. {
  268. month = "04";
  269. d = d.Replace("APR", "|");
  270. day = d.Substring(0, d.IndexOf("|"));
  271. year = d.Substring(d.IndexOf("|") + 1, 4);
  272. if (hastime)
  273. time = d.Substring(d.IndexOf(":") - 3 + 2);
  274. else time = "00:00:00.000";
  275. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  276. dt = DateTime.Parse(date);
  277. }
  278. else if (d.IndexOf("MAY") != -1)
  279. {
  280. month = "05";
  281. d = d.Replace("MAY", "|");
  282. day = d.Substring(0, d.IndexOf("|"));
  283. year = d.Substring(d.IndexOf("|") + 1, 4);
  284. if (hastime)
  285. time = d.Substring(d.IndexOf(":") - 3 + 2);
  286. else time = "00:00:00.000";
  287. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  288. dt = DateTime.Parse(date);
  289. }
  290. else if (d.IndexOf("JUNE") != -1)
  291. {
  292. month = "06";
  293. d = d.Replace("JUNE", "|");
  294. day = d.Substring(0, d.IndexOf("|"));
  295. year = d.Substring(d.IndexOf("|") + 1, 4);
  296. if (hastime)
  297. time = d.Substring(d.IndexOf(":") - 3 + 2);
  298. else time = "00:00:00.000";
  299. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  300. dt = DateTime.Parse(date);
  301. }
  302. else if (d.IndexOf("JUN") != -1)
  303. {
  304. month = "06";
  305. d = d.Replace("JUN", "|");
  306. day = d.Substring(0, d.IndexOf("|"));
  307. year = d.Substring(d.IndexOf("|") + 1, 4);
  308. if (hastime)
  309. time = d.Substring(d.IndexOf(":") - 3 + 2);
  310. else time = "00:00:00.000";
  311. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  312. dt = DateTime.Parse(date);
  313. }
  314. else if (d.IndexOf("JULY") != -1)
  315. {
  316. month = "07";
  317. d = d.Replace("JULY", "|");
  318. day = d.Substring(0, d.IndexOf("|"));
  319. year = d.Substring(d.IndexOf("|") + 1, 4);
  320. if (hastime)
  321. time = d.Substring(d.IndexOf(":") - 3 + 2);
  322. else time = "00:00:00.000";
  323. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  324. dt = DateTime.Parse(date);
  325. }
  326. else if (d.IndexOf("JUL") != -1)
  327. {
  328. month = "07";
  329. d = d.Replace("JUL", "|");
  330. day = d.Substring(0, d.IndexOf("|"));
  331. year = d.Substring(d.IndexOf("|") + 1, 4);
  332. if (hastime)
  333. time = d.Substring(d.IndexOf(":") - 3 + 2);
  334. else time = "00:00:00.000";
  335. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  336. dt = DateTime.Parse(date);
  337. }
  338. else if (d.IndexOf("AUG") != -1)
  339. {
  340. month = "08";
  341. d = d.Replace("AUG", "|");
  342. day = d.Substring(0, d.IndexOf("|"));
  343. year = d.Substring(d.IndexOf("|") + 1, 4);
  344. if (hastime)
  345. time = d.Substring(d.IndexOf(":") - 3 + 2);
  346. else time = "00:00:00.000";
  347. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  348. dt = DateTime.Parse(date);
  349. }
  350. else if (d.IndexOf("SEPT") != -1)
  351. {
  352. month = "09";
  353. d = d.Replace("SEPT", "|");
  354. day = d.Substring(0, d.IndexOf("|"));
  355. year = d.Substring(d.IndexOf("|") + 1, 4);
  356. if (hastime)
  357. time = d.Substring(d.IndexOf(":") - 3 + 2);
  358. else time = "00:00:00.000";
  359. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  360. dt = DateTime.Parse(date);
  361. }
  362. else if (d.IndexOf("SEP") != -1)
  363. {
  364. month = "09";
  365. d = d.Replace("SEP", "|");
  366. day = d.Substring(0, d.IndexOf("|"));
  367. year = d.Substring(d.IndexOf("|") + 1, 4);
  368. if (hastime)
  369. time = d.Substring(d.IndexOf(":") - 3 + 2);
  370. else time = "00:00:00.000";
  371. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  372. dt = DateTime.Parse(date);
  373. }
  374. else if (d.IndexOf("OCT") != -1)
  375. {
  376. month = "10";
  377. d = d.Replace("OCT", "|");
  378. day = d.Substring(0, d.IndexOf("|"));
  379. year = d.Substring(d.IndexOf("|") + 1, 4);
  380. if (hastime)
  381. time = d.Substring(d.IndexOf(":") - 3 + 2);
  382. else time = "00:00:00.000";
  383. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  384. dt = DateTime.Parse(date);
  385. }
  386. else if (d.IndexOf("0CT") != -1)
  387. {
  388. month = "10";
  389. d = d.Replace("0CT", "|");
  390. day = d.Substring(0, d.IndexOf("|"));
  391. year = d.Substring(d.IndexOf("|") + 1, 4);
  392. if (hastime)
  393. time = d.Substring(d.IndexOf(":") - 3 + 2);
  394. else time = "00:00:00.000";
  395. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  396. dt = DateTime.Parse(date);
  397. }
  398. else if (d.IndexOf("NOV") != -1)
  399. {
  400. month = "11";
  401. d = d.Replace("NOV", "|");
  402. day = d.Substring(0, d.IndexOf("|"));
  403. year = d.Substring(d.IndexOf("|") + 1, 4);
  404. if (hastime)
  405. time = d.Substring(d.IndexOf(":") - 3 + 2);
  406. else time = "00:00:00.000";
  407. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  408. dt = DateTime.Parse(date);
  409. }
  410. else
  411. {
  412. month = "12";
  413. d = d.Replace("DEC", "|");
  414. day = d.Substring(0, d.IndexOf("|"));
  415. year = d.Substring(d.IndexOf("|") + 1, 4);
  416. if (hastime)
  417. time = d.Substring(d.IndexOf(":") - 3 + 2);
  418. else time = "00:00:00.000";
  419. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  420. dt = DateTime.Parse(date);
  421. }
  422. return dt;
  423. }
  424. private static void ReadFile(ToDo todo)
  425. {
  426. string file = Path.Combine(_exeDir, todo.FileName);// todo.FileName;
  427. todo.FileName = file;
  428. Customer c = new Customer();
  429. WorkOrder wo = new WorkOrder();
  430. Equipment eq = new Equipment();
  431. List<Part> parts = new List<Part>();
  432. Console.WriteLine("Line 306: " + file);
  433. Console.WriteLine("Line 307: " + file);
  434. string filemove = string.Empty;
  435. string filetxt = string.Empty;
  436. string inspectionLevel = string.Empty;
  437. bool isSpecial = false;
  438. StringBuilder specialInstructions = new StringBuilder();
  439. int line = 1;
  440. try
  441. {
  442. List<string> filelines = WriteFileToText(file);
  443. for (int i = filelines.Count - 1; i >= 0; i--)
  444. {
  445. if (string.IsNullOrEmpty(filelines[i])) filelines.RemoveAt(i);
  446. }
  447. string[] lines = filelines.ToArray();
  448. foreach (string s in lines)
  449. {
  450. string currentline = s.Trim().Replace("'", "''");
  451. if (currentline.Contains("Page") && currentline.Substring(78).Trim() != "1")
  452. line = 18;
  453. if (currentline.Contains("Page") && currentline.Substring(78).Trim() == "1")
  454. line = 1;
  455. switch (line)
  456. {
  457. case 1:
  458. string strDate = currentline.Substring(5, currentline.IndexOf("*") - 6);
  459. strDate = strDate.Trim();
  460. strDate.Replace(" ", " ");
  461. wo.CreateDate = DateFormatter(strDate);
  462. break;
  463. case 2:
  464. string strWONum = currentline.Substring(currentline.IndexOf("Work Order") + 10, 12);
  465. strWONum = strWONum.Trim();
  466. wo.Number = strWONum;
  467. todo.WorkOrder = strWONum;
  468. _workOrderNumber = strWONum;
  469. string strSeg = currentline.Substring(currentline.IndexOf("Seg.") + 4, 25);
  470. strSeg = strSeg.Trim();
  471. wo.Segment = strSeg;
  472. string strODate = currentline.Substring(currentline.IndexOf("Opn Dt") + 6);
  473. strODate = strODate.Trim();
  474. wo.OpnDt = DateFormatter(strODate, false);
  475. break;
  476. case 5:
  477. c.Name = currentline.Substring(3, 25);
  478. c.Number = currentline.Substring(38, 10);
  479. break;
  480. case 6:
  481. c.Addr1 = currentline.Substring(3, 25);
  482. break;
  483. case 7:
  484. c.Addr2 = currentline.Substring(3, 25);
  485. break;
  486. case 8:
  487. int comma = currentline.IndexOf(",");
  488. int length = currentline.Length - 3;
  489. c.City = (comma == -1) ? "" : currentline.Substring(3, comma - 3);
  490. c.State = currentline.Substring(currentline.IndexOf(",") + 2, 2);
  491. c.Zip = currentline.Substring(comma + 5, 7);
  492. break;
  493. case 11:
  494. eq.Make = currentline.Substring(0, 8).Trim();
  495. eq.Model = currentline.Substring(8, 14).Trim();
  496. eq.SerialNumber = currentline.Substring(22, 22).Trim();
  497. eq.EquipmentNumber = currentline.Substring(42, 16).Trim();
  498. eq.MeterReading = currentline.Substring(60, 7).Trim();
  499. eq.MID = CSVObject.MachineExists(eq.SerialNumber, _connection);
  500. if (eq.MID == 0) _newMachine = true;
  501. break;
  502. default:
  503. break;
  504. }
  505. if (line > 14)
  506. {
  507. if (currentline.EndsWith(" T"))
  508. {
  509. if (currentline.Contains("PM LEVEL"))
  510. {
  511. isSpecial = false;
  512. }
  513. else if (currentline.Contains("PM INTERVAL"))
  514. {
  515. isSpecial = false;
  516. string pminterval = currentline.Substring(currentline.IndexOf(":") + 2);
  517. pminterval = pminterval.Substring(0, pminterval.IndexOf(" ")).Trim();
  518. if (XMLData.IntervalLookup.ContainsKey(pminterval)) wo.InspectionLevel = XMLData.IntervalLookup[pminterval].ToString();
  519. if (!string.IsNullOrEmpty(wo.InspectionLevel)) wo.InspectionInterval = pminterval;
  520. string strService = currentline.Substring(currentline.IndexOf(":") + 2);
  521. strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
  522. strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
  523. if (strService.IndexOf(" ") > 0)
  524. strService = strService.Substring(0, strService.IndexOf(" ")).Trim();
  525. if (InspectionType.ContainsKey(strService))
  526. wo.InspectionType = InspectionType[strService].ToString();
  527. else wo.InspectionType = InspectionType["PM"].ToString();
  528. string codeanddescriptionoriginal = currentline.Substring(currentline.IndexOf(":") + 2);
  529. codeanddescriptionoriginal = codeanddescriptionoriginal.Substring(0, codeanddescriptionoriginal.IndexOf(" T") - 3).Trim();
  530. wo.CodeAndDescriptionOriginal = codeanddescriptionoriginal;
  531. }
  532. else if (currentline.Contains("EMPID"))
  533. {
  534. isSpecial = false;
  535. string empid = currentline.Substring(currentline.IndexOf(":") + 2);
  536. empid = empid.Substring(0, empid.IndexOf(" ")).Trim();
  537. wo.TechnicianUserID = empid;
  538. }
  539. else if (currentline.Contains("PROMISE DATE"))
  540. {
  541. isSpecial = false;
  542. string promisedate = currentline.Substring(currentline.IndexOf(":") + 2);
  543. promisedate = promisedate.Substring(0, promisedate.IndexOf(" ")).Trim();
  544. wo.ScheduledStartDate = DateFormatter(promisedate, false);
  545. }
  546. else if (currentline.Contains("SPECIAL INSTRUCTIONS"))
  547. {
  548. isSpecial = true;
  549. string special = currentline.Substring(currentline.IndexOf(":") + 2);
  550. special = special.Substring(0, special.IndexOf(" T") - 1).Trim();
  551. specialInstructions.Append(special);
  552. }
  553. else
  554. {
  555. if (isSpecial)
  556. {
  557. string addspecial = currentline.Substring(0, currentline.IndexOf(" T") - 1).Trim();
  558. specialInstructions.Append(string.Format(" {0}", addspecial));
  559. }
  560. }
  561. }
  562. else
  563. {
  564. isSpecial = false;
  565. int qty = 0;
  566. if (currentline.Length > 0)
  567. {
  568. string input = currentline.Substring(0, (currentline.IndexOf(" ") == -1) ? 1 : currentline.IndexOf(" ")).Trim();
  569. if (int.TryParse(input, out qty))
  570. {
  571. if (qty < 100 && !currentline.Contains("HR"))
  572. {
  573. Part pt = new Part();
  574. string sline = currentline.Substring(19).Trim();
  575. //pt.Description = currentline.Substring(34, 14);
  576. pt.Number = sline.Substring(0, sline.IndexOf(" "));
  577. sline = sline.Substring(sline.IndexOf(" ")).Trim();
  578. pt.Description = sline.Substring(0, sline.IndexOf(" ")).Trim();
  579. pt.Qty = currentline.Substring(0, currentline.IndexOf(" ")).Trim();
  580. parts.Add(pt);
  581. }
  582. }
  583. }
  584. }
  585. }
  586. line++;
  587. }
  588. if (wo.ScheduledStartDate == DateTime.MinValue) wo.ScheduledStartDate = DateTime.Now;
  589. List<CSVObject> list = new List<CSVObject>();
  590. List<CSVObject> exceptions = new List<CSVObject>();
  591. if (parts.Count == 0)
  592. {
  593. Part p = new Part();
  594. p.Description = string.Empty;
  595. p.Qty = string.Empty;
  596. p.Number = string.Empty;
  597. parts.Add(p);
  598. }
  599. static void conn_InfoMsg(object sender, SqlInfoMessageEventArgs e)
  600. {
  601. _sqlMessages.Add(e.Message);
  602. }
  603. foreach (Part prt in parts)
  604. {
  605. CSVObject obj = new CSVObject();
  606. obj.Address = string.Format(frmtString, c.Addr1.Trim());
  607. obj.Address2 = string.Format(frmtString, c.Addr2.Trim());
  608. obj.City = string.Format(frmtString, c.City.Trim());
  609. obj.State = string.Format(frmtString, c.State.Trim());
  610. obj.CustomerName = string.Format(frmtString, c.Name.Trim());
  611. obj.CustomerNumber = string.Format(frmtString, c.Number.Trim());
  612. obj.DBSWorkOrderNumber = string.Format(frmtString, wo.Number.Trim());
  613. obj.EquipmentNumber = string.Format(frmtString, eq.EquipmentNumber.Trim());
  614. obj.Make = string.Format(frmtString, eq.Make.Trim());
  615. obj.MeterReading = string.Format(frmtString, eq.MeterReading.Trim());
  616. obj.Model = string.Format(frmtString, eq.Model.Trim());
  617. obj.PartNumber = string.Format(frmtString, prt.Number.Trim());
  618. obj.PartNumberDescription = string.Format(frmtString, prt.Description.Trim());
  619. obj.Quantity = string.Format(frmtString, prt.Qty.Trim());
  620. obj.SegmentNumber = string.Format(frmtString, wo.Segment.Trim());
  621. obj.SerialNumber = string.Format(frmtString, eq.SerialNumber.Trim());
  622. obj.ZipCode = string.Format(frmtString, c.Zip.Trim());
  623. obj.CodeAndDescription = string.Format(frmtString, wo.InspectionLevel.Trim());
  624. obj.SpecialInstructions = specialInstructions.ToString();
  625. obj.CodeAndDescriptionOriginal = string.Format(frmtString, wo.CodeAndDescriptionOriginal);
  626. obj.ContractTypeCode = string.Format(frmtString, "");
  627. obj.DateActualStart = string.Format(frmtString, wo.CreateDate);
  628. obj.FamilyCode = string.Format(frmtString, "");
  629. obj.FamilyDescription = string.Format(frmtString, "");
  630. obj.JobSiteContactName = string.Format(frmtString, "");
  631. obj.JobSiteContactPhone = string.Format(frmtString, "");
  632. obj.LastServiceDate = string.Format(frmtString, "");
  633. obj.PriorityCode = string.Format(frmtString, "");
  634. obj.ReferenceDocNumber = string.Format(frmtString, "");
  635. obj.ServiceTech = string.Format(frmtString, wo.TechnicianUserID);
  636. obj.StoreDescription = string.Format(frmtString, "");
  637. obj.Store = string.Format(frmtString, "");
  638. obj.TechName = string.Format(frmtString, "");
  639. obj.Year = string.Format(frmtString, "");
  640. obj.ScheduledStartDate = string.Format(frmtString, wo.ScheduledStartDate.ToString("yyyy-MM-dd hh:mm:ss"));
  641. obj.InspectionType = string.Format(frmtString, wo.InspectionType.ToString());
  642. obj.Validate();
  643. if (string.IsNullOrEmpty(obj.SerialNumber))
  644. {
  645. exceptions.Add(obj);
  646. //throw new ApplicationException("Serial Number is missing.");
  647. }
  648. else list.Add(obj);
  649. if (list.Count == 0)
  650. {
  651. StringBuilder sbException = new StringBuilder();
  652. foreach (CSVObject csvobj in exceptions)
  653. foreach (PropertyInfo pi in csvobj.GetType().GetProperties())
  654. {
  655. sbException.AppendLine(string.Format("{0}: {1}", pi.Name, pi.GetValue(csvobj, null)));
  656. }
  657. throw new ApplicationException(string.Format("Object Validation Error\r\n{0}", sbException.ToString()));
  658. }
  659. }
  660. filemove = Path.Combine("Success", file);// string.Format("{0}\\{1}\\{2}", _currentDir, _settings["SUCCESSDIR"], file);
  661. try
  662. {
  663. SqlConnection conn = new SqlConnection(_connection);
  664. conn.Open();
  665. string errorstr = CSVObject.WriteToDB(list, conn);
  666. conn.Close();
  667. conn.Dispose();
  668. if (!string.IsNullOrEmpty(errorstr)) throw new ApplicationException(errorstr);
  669. SqlCommand cmd = new SqlCommand("usp_DoImport", new SqlConnection(_connection));
  670. cmd.CommandTimeout = 0;
  671. SqlParameter sqlReturn = cmd.Parameters.Add("@b", SqlDbType.Int);
  672. sqlReturn.Direction = ParameterDirection.ReturnValue;
  673. cmd.Connection.Open();
  674. cmd.Connection.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMsg);
  675. cmd.Connection.FireInfoMessageEventOnUserErrors = true;
  676. cmd.CommandType = CommandType.StoredProcedure;
  677. cmd.ExecuteNonQuery();
  678. if (Convert.ToInt32(cmd.Parameters["@b"].Value) != 0)
  679. throw new Exception("Error happend in the do import");
  680. cmd.Connection.Close();
  681. cmd.Dispose();
  682. conn.Dispose();
  683. SqlCommand delcmd = new SqlCommand("Delete Results_Brandt", new SqlConnection(_connection));
  684. delcmd.CommandTimeout = 0;
  685. delcmd.Connection.Open();
  686. delcmd.CommandType = CommandType.Text;
  687. try
  688. {
  689. delcmd.ExecuteNonQuery();
  690. }
  691. catch (Exception dex)
  692. {
  693. throw new Exception(dex.Message);
  694. }
  695. delcmd.Connection.Close();
  696. delcmd.Dispose();
  697. }
  698. catch (Exception exSql)
  699. {
  700. string msg = exSql.Message;
  701. string logmsg = string.Format("Date: {0} Error: {1}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), exSql.Message);
  702. WriteToLog(logmsg);
  703. todo.Validation = exSql.Message + " " + _workOrderNumber;
  704. filemove = Path.Combine("Fail", todo.FileName);
  705. //File.Move(todo.FileName, filemove);
  706. //MailSvc.SendResponse(msg, _workOrderNumber);
  707. }
  708. Console.WriteLine("Line 584: " + filemove);
  709. if (File.Exists(filemove)) File.Delete(filemove);
  710. //File.Move(file, filemove);
  711. if (_log)
  712. {
  713. string successmsg = string.Format("Success Date: {0} File Name: {1} Work Order #: {2}{3}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), file, _workOrderNumber, "********************************");
  714. WriteToLog(successmsg);
  715. if (exceptions.Count > 0)
  716. {
  717. foreach (CSVObject csvobj in exceptions)
  718. {
  719. string csvmsg = string.Format("Null Serial# Exception Date: {0} File Name: {1} Work Order #: {2}{3}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), file, _workOrderNumber, "********************************");
  720. WriteToLog(csvmsg);
  721. }
  722. }
  723. if (_sqlMessages.Count > 0)
  724. {
  725. WriteToLog("***********************SQL Messages************************");
  726. foreach (string sqlmessg in _sqlMessages)
  727. WriteToLog(sqlmessg);
  728. WriteToLog("*********************End SQL Messages**********************");
  729. }
  730. }
  731. using (SqlConnection doublecheck = new SqlConnection(_connection))
  732. {
  733. SqlCommand cmddoublecheck = doublecheck.CreateCommand();
  734. cmddoublecheck.Connection.Open();
  735. cmddoublecheck.CommandTimeout = 0;
  736. cmddoublecheck.CommandText = string.Format("Select MAX(ID) from WorkOrder where Number = '{0}'", wo.Number);
  737. cmddoublecheck.CommandType = CommandType.Text;
  738. int rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  739. cmddoublecheck.Dispose();
  740. if (rslt > 0)
  741. {
  742. cmddoublecheck.CommandText = string.Format("Select ID from Inspection where workorderid = {0}", rslt);
  743. rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  744. if (rslt > 0)
  745. {
  746. todo.Success = true;
  747. //MailSvc.SendResponse("Work Order was imported successfully.", wo.Number);
  748. }
  749. else
  750. {
  751. //string noTemplate = string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
  752. todo.Validation = todo.Validation + "\r\n" + string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
  753. todo.Success = false;
  754. }
  755. }
  756. else
  757. {
  758. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}", wo.Number);//)
  759. }
  760. //MailSvc.SendResponse(string.Format("Failed to import work order {0}.", wo.Number), wo.Number);
  761. }
  762. //Console.ReadLine();
  763. }
  764. catch (Exception ex)
  765. {
  766. string exMesg = string.Empty;
  767. try
  768. {
  769. exMesg = string.Format("Date: {0} Error: {1}\r\nError occured in line # {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), ex.Message, line);
  770. }
  771. catch (Exception exSend)
  772. {
  773. Console.Write(exSend.Message);
  774. }
  775. WriteToLog(exMesg);
  776. filemove = Path.Combine("Fail", file);//, file);
  777. try
  778. {
  779. Console.WriteLine("Line 634: " + file);
  780. Console.WriteLine("Line 635: " + filemove);
  781. //File.Move(file, filemove);
  782. }
  783. catch (Exception moveExcept)
  784. {
  785. Console.WriteLine(moveExcept.Message);
  786. }
  787. todo.Success = false;
  788. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg);
  789. //MailSvc.SendResponse(string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg), wo.Number, filemove);
  790. }
  791. }
  792. private static void CreateLogFile(string logfile)
  793. {
  794. using (StreamWriter sw = File.CreateText(logfile))
  795. {
  796. sw.WriteLine("******************************************");
  797. sw.WriteLine("****************IMPORT LOG****************");
  798. sw.WriteLine("******************************************");
  799. }
  800. }
  801. public static void WriteToLog(string message, string sqlmessage = "")
  802. {
  803. string logfile = Path.Combine("Log", "log.log");
  804. if (!File.Exists(logfile))
  805. {
  806. CreateLogFile(logfile);
  807. }
  808. using (StreamWriter sw = File.AppendText(logfile))
  809. {
  810. sw.WriteLine(message);
  811. if (!string.IsNullOrEmpty(sqlmessage))
  812. sw.WriteLine(sqlmessage);
  813. }
  814. }
  815. }
  816. public class ToDo
  817. {
  818. private bool _success = false;
  819. public bool Success { get { return _success; } set { _success = value; } }
  820. public string Sender { get; set; }
  821. public string SenderName { get; set; }
  822. public string FileName { get; set; }
  823. public string Validation { get; set; }
  824. public string WorkOrder { get; set; }
  825. }
  826. }