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

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