Replacement for JDIS Importer
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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