Replacement for JDIS Importer
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

876 Zeilen
42 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=192.168.0.7;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} Work Order:{1} {2}";
  101. if (sendMsg.Success)
  102. {
  103. body = string.Format(body, sendMsg.FileName, sendMsg.WorkOrder, "Was Imported Successfully");
  104. }
  105. else
  106. {
  107. body = string.Format(body, sendMsg.FileName, sendMsg.WorkOrder, 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. todo.WorkOrder = strWONum;
  455. _workOrderNumber = strWONum;
  456. string strSeg = currentline.Substring(currentline.IndexOf("Seg.") + 4, 25);
  457. strSeg = strSeg.Trim();
  458. wo.Segment = strSeg;
  459. string strODate = currentline.Substring(currentline.IndexOf("Opn Dt") + 6);
  460. strODate = strODate.Trim();
  461. wo.OpnDt = DateFormatter(strODate, false);
  462. break;
  463. case 5:
  464. c.Name = currentline.Substring(3, 25);
  465. c.Number = currentline.Substring(38, 10);
  466. break;
  467. case 6:
  468. c.Addr1 = currentline.Substring(3, 25);
  469. break;
  470. case 7:
  471. c.Addr2 = currentline.Substring(3, 25);
  472. break;
  473. case 8:
  474. int comma = currentline.IndexOf(",");
  475. int length = currentline.Length - 3;
  476. c.City = (comma == -1) ? "" : currentline.Substring(3, comma - 3);
  477. c.State = currentline.Substring(currentline.IndexOf(",") + 2, 2);
  478. c.Zip = currentline.Substring(comma + 5, 7);
  479. break;
  480. case 11:
  481. eq.Make = currentline.Substring(0, 8).Trim();
  482. eq.Model = currentline.Substring(8, 14).Trim();
  483. eq.SerialNumber = currentline.Substring(22, 22).Trim();
  484. eq.EquipmentNumber = currentline.Substring(42, 16).Trim();
  485. eq.MeterReading = currentline.Substring(60, 7).Trim();
  486. eq.MID = CSVObject.MachineExists(eq.SerialNumber, _connection);
  487. if (eq.MID == 0) _newMachine = true;
  488. break;
  489. default:
  490. break;
  491. }
  492. if (line > 14)
  493. {
  494. if (currentline.EndsWith(" T"))
  495. {
  496. if (currentline.Contains("PM LEVEL"))
  497. {
  498. isSpecial = false;
  499. }
  500. else if (currentline.Contains("PM INTERVAL"))
  501. {
  502. isSpecial = false;
  503. string pminterval = currentline.Substring(currentline.IndexOf(":") + 2);
  504. pminterval = pminterval.Substring(0, pminterval.IndexOf(" ")).Trim();
  505. if (XMLData.IntervalLookup.ContainsKey(pminterval)) wo.InspectionLevel = XMLData.IntervalLookup[pminterval].ToString();
  506. if (!string.IsNullOrEmpty(wo.InspectionLevel)) wo.InspectionInterval = pminterval;
  507. string strService = currentline.Substring(currentline.IndexOf(":") + 2);
  508. strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
  509. strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
  510. if (strService.IndexOf(" ") > 0)
  511. strService = strService.Substring(0, strService.IndexOf(" ")).Trim();
  512. if (InspectionType.ContainsKey(strService))
  513. wo.InspectionType = InspectionType[strService].ToString();
  514. else wo.InspectionType = InspectionType["PM"].ToString();
  515. string codeanddescriptionoriginal = currentline.Substring(currentline.IndexOf(":") + 2);
  516. codeanddescriptionoriginal = codeanddescriptionoriginal.Substring(0, codeanddescriptionoriginal.IndexOf(" T") - 3).Trim();
  517. wo.CodeAndDescriptionOriginal = codeanddescriptionoriginal;
  518. }
  519. else if (currentline.Contains("EMPID"))
  520. {
  521. isSpecial = false;
  522. string empid = currentline.Substring(currentline.IndexOf(":") + 2);
  523. empid = empid.Substring(0, empid.IndexOf(" ")).Trim();
  524. wo.TechnicianUserID = empid;
  525. }
  526. else if (currentline.Contains("PROMISE DATE"))
  527. {
  528. isSpecial = false;
  529. string promisedate = currentline.Substring(currentline.IndexOf(":") + 2);
  530. promisedate = promisedate.Substring(0, promisedate.IndexOf(" ")).Trim();
  531. wo.ScheduledStartDate = DateFormatter(promisedate, false);
  532. }
  533. else if (currentline.Contains("SPECIAL INSTRUCTIONS"))
  534. {
  535. isSpecial = true;
  536. string special = currentline.Substring(currentline.IndexOf(":") + 2);
  537. special = special.Substring(0, special.IndexOf(" T") - 1).Trim();
  538. specialInstructions.Append(special);
  539. }
  540. else
  541. {
  542. if (isSpecial)
  543. {
  544. string addspecial = currentline.Substring(0, currentline.IndexOf(" T") - 1).Trim();
  545. specialInstructions.Append(string.Format(" {0}", addspecial));
  546. }
  547. }
  548. }
  549. else
  550. {
  551. isSpecial = false;
  552. int qty = 0;
  553. if (currentline.Length > 0)
  554. {
  555. string input = currentline.Substring(0, (currentline.IndexOf(" ") == -1) ? 1 : currentline.IndexOf(" ")).Trim();
  556. if (int.TryParse(input, out qty))
  557. {
  558. if (qty < 100 && !currentline.Contains("HR"))
  559. {
  560. Part pt = new Part();
  561. string sline = currentline.Substring(19).Trim();
  562. //pt.Description = currentline.Substring(34, 14);
  563. pt.Number = sline.Substring(0, sline.IndexOf(" "));
  564. sline = sline.Substring(sline.IndexOf(" ")).Trim();
  565. pt.Description = sline.Substring(0, sline.IndexOf(" ")).Trim();
  566. pt.Qty = currentline.Substring(0, currentline.IndexOf(" ")).Trim();
  567. parts.Add(pt);
  568. }
  569. }
  570. }
  571. }
  572. }
  573. line++;
  574. }
  575. if (wo.ScheduledStartDate == DateTime.MinValue) wo.ScheduledStartDate = DateTime.Now;
  576. List<CSVObject> list = new List<CSVObject>();
  577. List<CSVObject> exceptions = new List<CSVObject>();
  578. if (parts.Count == 0)
  579. {
  580. Part p = new Part();
  581. p.Description = string.Empty;
  582. p.Qty = string.Empty;
  583. p.Number = string.Empty;
  584. parts.Add(p);
  585. }
  586. static void conn_InfoMsg(object sender, SqlInfoMessageEventArgs e)
  587. {
  588. _sqlMessages.Add(e.Message);
  589. }
  590. foreach (Part prt in parts)
  591. {
  592. CSVObject obj = new CSVObject();
  593. obj.Address = string.Format(frmtString, c.Addr1.Trim());
  594. obj.Address2 = string.Format(frmtString, c.Addr2.Trim());
  595. obj.City = string.Format(frmtString, c.City.Trim());
  596. obj.State = string.Format(frmtString, c.State.Trim());
  597. obj.CustomerName = string.Format(frmtString, c.Name.Trim());
  598. obj.CustomerNumber = string.Format(frmtString, c.Number.Trim());
  599. obj.DBSWorkOrderNumber = string.Format(frmtString, wo.Number.Trim());
  600. obj.EquipmentNumber = string.Format(frmtString, eq.EquipmentNumber.Trim());
  601. obj.Make = string.Format(frmtString, eq.Make.Trim());
  602. obj.MeterReading = string.Format(frmtString, eq.MeterReading.Trim());
  603. obj.Model = string.Format(frmtString, eq.Model.Trim());
  604. obj.PartNumber = string.Format(frmtString, prt.Number.Trim());
  605. obj.PartNumberDescription = string.Format(frmtString, prt.Description.Trim());
  606. obj.Quantity = string.Format(frmtString, prt.Qty.Trim());
  607. obj.SegmentNumber = string.Format(frmtString, wo.Segment.Trim());
  608. obj.SerialNumber = string.Format(frmtString, eq.SerialNumber.Trim());
  609. obj.ZipCode = string.Format(frmtString, c.Zip.Trim());
  610. obj.CodeAndDescription = string.Format(frmtString, wo.InspectionLevel.Trim());
  611. obj.SpecialInstructions = specialInstructions.ToString();
  612. obj.CodeAndDescriptionOriginal = string.Format(frmtString, wo.CodeAndDescriptionOriginal);
  613. obj.ContractTypeCode = string.Format(frmtString, "");
  614. obj.DateActualStart = string.Format(frmtString, wo.CreateDate);
  615. obj.FamilyCode = string.Format(frmtString, "");
  616. obj.FamilyDescription = string.Format(frmtString, "");
  617. obj.JobSiteContactName = string.Format(frmtString, "");
  618. obj.JobSiteContactPhone = string.Format(frmtString, "");
  619. obj.LastServiceDate = string.Format(frmtString, "");
  620. obj.PriorityCode = string.Format(frmtString, "");
  621. obj.ReferenceDocNumber = string.Format(frmtString, "");
  622. obj.ServiceTech = string.Format(frmtString, wo.TechnicianUserID);
  623. obj.StoreDescription = string.Format(frmtString, "");
  624. obj.Store = string.Format(frmtString, "");
  625. obj.TechName = string.Format(frmtString, "");
  626. obj.Year = string.Format(frmtString, "");
  627. obj.ScheduledStartDate = string.Format(frmtString, wo.ScheduledStartDate.ToString("yyyy-MM-dd hh:mm:ss"));
  628. obj.InspectionType = string.Format(frmtString, wo.InspectionType.ToString());
  629. obj.Validate();
  630. if (string.IsNullOrEmpty(obj.SerialNumber))
  631. {
  632. exceptions.Add(obj);
  633. //throw new ApplicationException("Serial Number is missing.");
  634. }
  635. else list.Add(obj);
  636. if (list.Count == 0)
  637. {
  638. StringBuilder sbException = new StringBuilder();
  639. foreach (CSVObject csvobj in exceptions)
  640. foreach (PropertyInfo pi in csvobj.GetType().GetProperties())
  641. {
  642. sbException.AppendLine(string.Format("{0}: {1}", pi.Name, pi.GetValue(csvobj, null)));
  643. }
  644. throw new ApplicationException(string.Format("Object Validation Error\r\n{0}", sbException.ToString()));
  645. }
  646. }
  647. filemove = Path.Combine("Success", file);// string.Format("{0}\\{1}\\{2}", _currentDir, _settings["SUCCESSDIR"], file);
  648. try
  649. {
  650. SqlConnection conn = new SqlConnection(_connection);
  651. conn.Open();
  652. string errorstr = CSVObject.WriteToDB(list, conn);
  653. conn.Close();
  654. conn.Dispose();
  655. if (!string.IsNullOrEmpty(errorstr)) throw new ApplicationException(errorstr);
  656. SqlCommand cmd = new SqlCommand("usp_DoImport", new SqlConnection(_connection));
  657. cmd.CommandTimeout = 0;
  658. SqlParameter sqlReturn = cmd.Parameters.Add("@b", SqlDbType.Int);
  659. sqlReturn.Direction = ParameterDirection.ReturnValue;
  660. cmd.Connection.Open();
  661. cmd.Connection.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMsg);
  662. cmd.Connection.FireInfoMessageEventOnUserErrors = true;
  663. cmd.CommandType = CommandType.StoredProcedure;
  664. cmd.ExecuteNonQuery();
  665. if (Convert.ToInt32(cmd.Parameters["@b"].Value) != 0)
  666. throw new Exception("Error happend in the do import");
  667. cmd.Connection.Close();
  668. cmd.Dispose();
  669. conn.Dispose();
  670. SqlCommand delcmd = new SqlCommand("Delete Results_Brandt", new SqlConnection(_connection));
  671. delcmd.CommandTimeout = 0;
  672. delcmd.Connection.Open();
  673. delcmd.CommandType = CommandType.Text;
  674. try
  675. {
  676. delcmd.ExecuteNonQuery();
  677. }
  678. catch (Exception dex)
  679. {
  680. throw new Exception(dex.Message);
  681. }
  682. delcmd.Connection.Close();
  683. delcmd.Dispose();
  684. }
  685. catch (Exception exSql)
  686. {
  687. string msg = exSql.Message;
  688. string logmsg = string.Format("Date: {0} Error: {1}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), exSql.Message);
  689. WriteToLog(logmsg);
  690. todo.Validation = exSql.Message + " " + _workOrderNumber;
  691. filemove = Path.Combine("Fail", todo.FileName);
  692. File.Move(todo.FileName, filemove);
  693. //MailSvc.SendResponse(msg, _workOrderNumber);
  694. }
  695. Console.WriteLine("Line 584: " + filemove);
  696. if (File.Exists(filemove)) File.Delete(filemove);
  697. File.Move(file, filemove);
  698. if (_log)
  699. {
  700. 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, "********************************");
  701. WriteToLog(successmsg);
  702. if (exceptions.Count > 0)
  703. {
  704. foreach (CSVObject csvobj in exceptions)
  705. {
  706. 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, "********************************");
  707. WriteToLog(csvmsg);
  708. }
  709. }
  710. if (_sqlMessages.Count > 0)
  711. {
  712. WriteToLog("***********************SQL Messages************************");
  713. foreach (string sqlmessg in _sqlMessages)
  714. WriteToLog(sqlmessg);
  715. WriteToLog("*********************End SQL Messages**********************");
  716. }
  717. }
  718. using (SqlConnection doublecheck = new SqlConnection(_connection))
  719. {
  720. SqlCommand cmddoublecheck = doublecheck.CreateCommand();
  721. cmddoublecheck.Connection.Open();
  722. cmddoublecheck.CommandTimeout = 0;
  723. cmddoublecheck.CommandText = string.Format("Select MAX(ID) from WorkOrder where Number = '{0}'", wo.Number);
  724. cmddoublecheck.CommandType = CommandType.Text;
  725. int rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  726. cmddoublecheck.Dispose();
  727. if (rslt > 0)
  728. {
  729. cmddoublecheck.CommandText = string.Format("Select ID from Inspection where workorderid = {0}", rslt);
  730. rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  731. if (rslt > 0)
  732. {
  733. todo.Success = true;
  734. //MailSvc.SendResponse("Work Order was imported successfully.", wo.Number);
  735. }
  736. else
  737. {
  738. //string noTemplate = string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
  739. 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);
  740. todo.Success = false;
  741. }
  742. }
  743. else
  744. {
  745. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}", wo.Number);//)
  746. }
  747. //MailSvc.SendResponse(string.Format("Failed to import work order {0}.", wo.Number), wo.Number);
  748. }
  749. //Console.ReadLine();
  750. }
  751. catch (Exception ex)
  752. {
  753. string exMesg = string.Empty;
  754. try
  755. {
  756. 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);
  757. }
  758. catch (Exception exSend)
  759. {
  760. Console.Write(exSend.Message);
  761. }
  762. WriteToLog(exMesg);
  763. filemove = Path.Combine("Fail", file);//, file);
  764. try
  765. {
  766. Console.WriteLine("Line 634: " + file);
  767. Console.WriteLine("Line 635: " + filemove);
  768. File.Move(file, filemove);
  769. }
  770. catch (Exception moveExcept)
  771. {
  772. Console.WriteLine(moveExcept.Message);
  773. }
  774. todo.Success = false;
  775. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg);
  776. //MailSvc.SendResponse(string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg), wo.Number, filemove);
  777. }
  778. }
  779. private static void CreateLogFile(string logfile)
  780. {
  781. using (StreamWriter sw = File.CreateText(logfile))
  782. {
  783. sw.WriteLine("******************************************");
  784. sw.WriteLine("****************IMPORT LOG****************");
  785. sw.WriteLine("******************************************");
  786. }
  787. }
  788. public static void WriteToLog(string message, string sqlmessage = "")
  789. {
  790. string logfile = Path.Combine("Log", "log.log");
  791. if (!File.Exists(logfile))
  792. {
  793. CreateLogFile(logfile);
  794. }
  795. using (StreamWriter sw = File.AppendText(logfile))
  796. {
  797. sw.WriteLine(message);
  798. if (!string.IsNullOrEmpty(sqlmessage))
  799. sw.WriteLine(sqlmessage);
  800. }
  801. }
  802. }
  803. public class ToDo
  804. {
  805. private bool _success = false;
  806. public bool Success { get { return _success; } set { _success = value; } }
  807. public string Sender { get; set; }
  808. public string SenderName { get; set; }
  809. public string FileName { get; set; }
  810. public string Validation { get; set; }
  811. public string WorkOrder { get; set; }
  812. }
  813. }