Replacement for JDIS Importer
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Program.cs 44 KiB

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