Replacement for JDIS Importer
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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