Replacement for JDIS Importer
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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