Replacement for JDIS Importer
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

893 řádky
43 KiB

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