Replacement for JDIS Importer
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.

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