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

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