Replacement for JDIS Importer
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Program.cs 58 KiB

3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. using System.Linq;
  13. using System.Net;
  14. /*
  15. Secret Value up-8Q~y46~JyQZjJlsAJ-zpXpglpmuPIJ1Gx3a2O
  16. Secret ID cba04a6c-a233-4646-909b-b50921edbe1c
  17. Client ID 489776b1-ee79-4b14-bc44-9f6bf47332db
  18. Object ID c7647074-edb6-4e8e-8a01-a1ed924fdae9
  19. Tenant ID 1fd06c96-d3a4-45e9-9ed7-bcecb394d277
  20. */
  21. namespace jdis_import
  22. {
  23. class Program
  24. {
  25. private static JSONSetting _settings;
  26. private static string _os, _logDir, _logFile, _successDir, _failureDir, _downloadDir;
  27. private static bool _runAPI = true;
  28. private static RESTService _rservice;
  29. private static List<User> _users;
  30. private static Priority _priority;
  31. private static Reason _reason;
  32. private static Status _status;
  33. private static List<Equipment> _machines;
  34. private static List<Customer> _customers;
  35. private static List<Make> _makes;
  36. private static List<Product> _products;
  37. private static List<Model> _models;
  38. private static List<InspectionType> _inspectionTypes;
  39. private static List<Template> _templates;
  40. private static string _exeDir;
  41. private static bool _log = true;
  42. 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;";
  43. private static string _workOrderNumber = string.Empty;
  44. private static List<string> _sqlMessages = new List<string>();
  45. private static bool _newMachine = false;
  46. private static bool _newMake = false;
  47. private static bool _newModel = false;
  48. private static bool _newCustomer = false;
  49. private static bool _quoted = false;
  50. public static string ExeDir { get { return _exeDir; } }
  51. 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" } };
  52. public static Dictionary<string, int> InspectionType;
  53. private static Customer CreateNewCustomer(CustomerImport c, ToDo todo)
  54. {
  55. Customer cust = new Customer();
  56. cust.Name = c.Name;
  57. cust.Address = c.Addr1;
  58. cust.Address2 = c.Addr2;
  59. cust.City = c.City;
  60. cust.State = c.State;
  61. cust.CreateDate = DateTime.Now;
  62. cust.CreateUserID = -1;
  63. cust.UpdateDate = DateTime.Now;
  64. cust.UpdateUserID = -1;
  65. cust.IsActive = true;
  66. cust.Number = c.Number;
  67. cust.ZipCode = c.Zip;
  68. string json = Serialize.ToJson<Customer>(cust);
  69. cust = _rservice.PostRest<Customer>(json, "customers.svc");
  70. return cust;
  71. }
  72. private static Model CreateNewModel(Product defaultP, EquipmentImport eq, ToDo todo)
  73. {
  74. Model mdl = new Model();
  75. //Find the Make and assign the default Product
  76. mdl.Name = eq.Model.Trim();
  77. mdl.IsActive = true;
  78. mdl.CreateDate = DateTime.Now;
  79. mdl.CreateUserID = -1;
  80. mdl.UpdateDate = DateTime.Now; ;
  81. mdl.UpdateUserID = -1;
  82. mdl.Product = defaultP;
  83. Make mk = (from x in _makes where x.Name.Trim() == eq.Make.Trim() select x).FirstOrDefault();
  84. if (mk == null)
  85. {
  86. //Create new Make
  87. mk.Name = eq.Make.Trim();
  88. mk.CreateDate = DateTime.Now;
  89. mk.CreateUserID = -1;
  90. mk.UpdateDate = DateTime.Now;
  91. mk.UpdateUserID = -1;
  92. mk.IsActive = true;
  93. mk.Description = eq.Make.Trim();
  94. string mkJson = Serialize.ToJson<Make>(mk);
  95. mk = _rservice.PostRest<Make>(mkJson, "makes.svc");
  96. }
  97. mdl.Make = mk;
  98. string json = Serialize.ToJson<Model>(mdl);
  99. mdl = _rservice.PostRest<Model>(json, "models.svc");
  100. return mdl;
  101. }
  102. private static Equipment CreateNewMachine(EquipmentImport eq, Model mdl, Customer cust, ToDo todo)
  103. {
  104. Equipment newMachine = new Equipment();
  105. newMachine.Model = mdl;
  106. newMachine.Make = mdl.Make;
  107. newMachine.Product = mdl.Product;
  108. newMachine.BarcodeID = null;
  109. newMachine.CreateDate = DateTime.Now;
  110. newMachine.UpdateDate = DateTime.Now;
  111. newMachine.UpateUserID = -1;
  112. newMachine.CreateUserID = -1;
  113. newMachine.Description = eq.SerialNumber;
  114. newMachine.IsActive = true;
  115. newMachine.LastServiceDate = null;
  116. newMachine.Location = null;
  117. newMachine.ManufacturerYear = "2000";
  118. newMachine.MeterReading = eq.MeterReading;
  119. newMachine.Number = eq.EquipmentNumber;
  120. newMachine.Odometer = null;
  121. newMachine.SerialNumber = eq.SerialNumber;
  122. newMachine.Customer = cust;
  123. string eqJson = Serialize.ToJson<Equipment>(newMachine);
  124. newMachine = _rservice.PostRest<Equipment>(eqJson, "Equipments.svc");
  125. return newMachine;
  126. }
  127. public static void APIPush(CustomerImport c, WorkOrderImport wo, List<PartImport> parts, EquipmentImport eq, ToDo todo)
  128. {
  129. Equipment machine = new Equipment();
  130. Model mdl = _models.Find(x => x.Name.Trim() == eq.Model.Trim());
  131. Product defaultP = _products.Find(x => x.ID == 14);
  132. //Customer cust = new Customer();
  133. Customer cust = IsNewCustomer(c.Name);
  134. if (cust == null)
  135. cust = CreateNewCustomer(c, todo);
  136. List<Equipment> equipment = IsNewMachine(eq.SerialNumber);
  137. _newMachine = equipment.Count == 0;
  138. if (_newMachine)
  139. {
  140. bool isNewModel = mdl == null;
  141. if (isNewModel)
  142. {
  143. string sModel = eq.Model.Trim().Substring(0, eq.Model.Length - 1);
  144. mdl = (from x in _models where x.Name.Contains(sModel) orderby x.ID select x).LastOrDefault();
  145. if (mdl == null)
  146. mdl = CreateNewModel(defaultP, eq, todo);
  147. else
  148. machine = CreateNewMachine(eq, mdl, cust, todo);
  149. }
  150. else
  151. {
  152. machine = CreateNewMachine(eq, mdl, cust, todo);
  153. }
  154. }
  155. else
  156. {
  157. machine = equipment.FindAll(x => x.SerialNumber == eq.SerialNumber).LastOrDefault();
  158. machine.Customer = cust;
  159. }
  160. //Find the Template
  161. Template template = _templates.Find(x => x.InspectionLevel.ID == Convert.ToInt32(wo.InspectionLevel) && x.InspectionType.ID == Convert.ToInt32(wo.InspectionType) && x.Name == eq.Model);
  162. if (template == null)
  163. {
  164. //Search by model prefix and get the last one
  165. string prefix = eq.Model.Trim();
  166. prefix = prefix.Substring(0, prefix.Length - 1);
  167. template = (from x in _templates where x.InspectionLevel.ID == Convert.ToInt32(wo.InspectionLevel) && x.InspectionType.ID == Convert.ToInt32(wo.InspectionType) && x.Name.Contains(prefix) orderby x.ID select x).LastOrDefault();
  168. if (template == null || template.ID == 0)
  169. {
  170. todo.Success = false;
  171. todo.Validation = todo.Validation + " No template for this model.";
  172. }
  173. }
  174. User user = _users.Find(x => x.Number == wo.TechnicianUserID.Trim());
  175. WorkOrder workorder = new WorkOrder();
  176. workorder.Number = wo.Number;
  177. workorder.Technician = user;
  178. workorder.Reason = _reason;
  179. workorder.Priority = _priority;
  180. workorder.Status = _status;
  181. workorder.CreateDate = DateTime.Now;
  182. workorder.CreateUserID = -1;
  183. workorder.Equipment = machine;
  184. workorder.Customer = cust;
  185. workorder.MeterReading = Convert.ToDecimal(eq.MeterReading);
  186. workorder.ScheduledStartDate = wo.OpnDt;
  187. workorder.ScheduledEndDate = wo.OpnDt.AddDays(1d);
  188. workorder.UpdateDate = DateTime.Now;
  189. workorder.UpdateUserID = -1;
  190. string woJson = Serialize.ToJson<WorkOrder>(workorder);
  191. //Console.WriteLine("WorkOrder Object");
  192. //Console.WriteLine();
  193. //Console.WriteLine(woJson);
  194. JDISLog.WriteToLog(_logFile, string.Format("Creating Work Order: {0}", workorder.Number));
  195. workorder = _rservice.PostRest<WorkOrder>(woJson, "workorders.svc");
  196. if (template == null || template.ID == 0)
  197. {
  198. todo.Validation = todo.Validation + Environment.NewLine + string.Format("Work Order {0} was created but there is no template matching model # {1}", workorder.Number, mdl.Name);
  199. todo.Success = false;
  200. }
  201. else
  202. {
  203. JDISLog.WriteToLog(_logFile, String.Format("Creating Inspections for Workorder {0}", workorder.Number));
  204. Dictionary<string, string> tps = new Dictionary<string, string>();
  205. tps.Add("create", string.Format("{0}/{1}/{2}", template.ID, workorder.ID, -1));
  206. Inspection i = _rservice.RestGet<Inspection>(true, "inspections.svc", tps);
  207. tps["create"] = string.Format("{0}/{1}/{2}", 1691, workorder.ID, -1);
  208. Inspection sta = _rservice.RestGet<Inspection>(true, "inspections.svc", tps);
  209. if (i != null && i.ID != 0)
  210. {
  211. todo.Success = true;
  212. }
  213. }
  214. }
  215. private static Customer IsNewCustomer(string name)
  216. {
  217. List<Customer> list = _customers.FindAll(x => x.Name.Trim() == name.Trim());
  218. if (list.Count > 1)
  219. return list.LastOrDefault();
  220. else if (list.Count == 1)
  221. return list[0];
  222. else return null;
  223. }
  224. private static List<Equipment> IsNewMachine(string serial)
  225. {
  226. Dictionary<string, string> ps = new Dictionary<string, string>();
  227. ps.Add("search", serial);
  228. _machines = _rservice.RestGet<Equipment>("equipments.svc", ps);
  229. return _machines;
  230. }
  231. private static void ListsAndDefaults()
  232. {
  233. _rservice = new RESTService();
  234. _rservice.BaseUrl = _settings.Prelub.ActiveService;
  235. _customers = _rservice.RestGet<Customer>("customers.svc");
  236. _makes = _rservice.RestGet<Make>("makes.svc");
  237. _products = _rservice.RestGet<Product>("products.svc");
  238. _models = _rservice.RestGet<Model>("models.svc");
  239. _inspectionTypes = _rservice.RestGet<InspectionType>("inspectionTypes.svc");
  240. _templates = _rservice.RestGet<Template>("templates.svc");
  241. _users = _rservice.RestGet<User>("users.svc");
  242. _status = new Status();
  243. _status.ID = 1;
  244. _status.Name = "Open";
  245. _priority = new Priority();
  246. _priority.ID = 3;
  247. _priority.Name = "Medium";
  248. _reason = new Reason();
  249. _reason.ID = 9;
  250. _reason.Name = "Cust. Request";
  251. _reason.IsActive = true;
  252. _reason.CreateDate = new DateTime(2013, 10, 1, 9, 23, 7);
  253. _reason.CreateUserID = -1;
  254. _reason.UpdateDate = new DateTime(2013, 10, 1, 9, 23, 7);
  255. _reason.UpdateUserID = -1;
  256. }
  257. static async System.Threading.Tasks.Task IsLocalNetwork()
  258. {
  259. var client = new System.Net.Http.HttpClient();
  260. try
  261. {
  262. var result = await client.GetAsync(_settings.Prelub.Check);
  263. _settings.Prelub.ActiveService = _settings.Prelub.LocalService;
  264. }
  265. catch
  266. {
  267. _settings.Prelub.ActiveService = _settings.Prelub.RemoteService;
  268. }
  269. }
  270. static async System.Threading.Tasks.Task Main(string[] args)
  271. {
  272. _settings = JSONMethods.GetSettings();
  273. await IsLocalNetwork();
  274. if (IsWindows()) _os = "Windows";
  275. else if (IsMacOS()) _os = "Mac";
  276. else if (IsLinux()) _os = "Linux";
  277. SetupDirectories();
  278. JDISLog.Begin(_logFile);
  279. ListsAndDefaults();
  280. //Console.WriteLine("Web APIs have loaded.");
  281. JDISLog.WriteToLog(_logFile, string.Format("Default data loaded..... {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
  282. _exeDir = Environment.CurrentDirectory;
  283. List<ToDo> list = new List<ToDo>();
  284. var cca = ConfidentialClientApplicationBuilder
  285. .Create(_keys["AppID"])
  286. .WithClientSecret(_keys["SecretV"])
  287. .WithTenantId(_keys["TenentID"])
  288. .Build();
  289. var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
  290. try
  291. {
  292. //Console.WriteLine("Connecting To Exchange.");
  293. JDISLog.WriteToLog(_logFile, string.Format("Connectiong to Exchange Server....{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
  294. var authResult = await cca.AcquireTokenForClient(ewsScopes)
  295. .ExecuteAsync();
  296. // Configure the ExchangeService with the access token
  297. var ewsClient = new ExchangeService();
  298. ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
  299. ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
  300. ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "cmobile@prelub.com");
  301. Mailbox mb = new Mailbox("connexionmobile@rpmindustries.org");
  302. FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
  303. List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
  304. string[] filters = "Brandt Import;BRANDT IMPORT;brandt import;TEST Brandt".Split(';');
  305. foreach (string s in filters)
  306. searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s));
  307. SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
  308. ItemView view = new ItemView(100);
  309. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
  310. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
  311. view.Traversal = ItemTraversal.Shallow;
  312. //Console.WriteLine("Line 90: Finding emails.");
  313. FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
  314. List<EmailMessage> messages = new List<EmailMessage>();
  315. foreach (EmailMessage message in findResults.Items)
  316. {
  317. message.Load();
  318. if (!message.IsRead)
  319. messages.Add(message);
  320. }
  321. JDISLog.WriteToLog(_logFile, string.Format("Found {0} emails", messages.Count));
  322. foreach (EmailMessage msg in findResults.Items)
  323. {
  324. msg.Load();
  325. if (!msg.IsRead)
  326. {
  327. if (msg.HasAttachments)
  328. {
  329. foreach (Attachment attachment in msg.Attachments)
  330. {
  331. attachment.Load();
  332. if (attachment is FileAttachment)
  333. {
  334. ToDo todo = new ToDo();
  335. todo.Sender = msg.Sender.Address;
  336. todo.SenderName = msg.Sender.Name;
  337. todo.FileName = attachment.Name;
  338. list.Add(todo);
  339. //Download File
  340. FileAttachment fAttachment = attachment as FileAttachment;
  341. string fileAttachmentPath = Path.Combine(_downloadDir, fAttachment.Name);
  342. File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
  343. msg.IsRead = true;
  344. msg.Update(ConflictResolutionMode.AlwaysOverwrite);
  345. }
  346. }
  347. }
  348. }
  349. }
  350. //Console.WriteLine("Beginning Import.");
  351. JDISLog.WriteToLog(_logFile, string.Format("Importing JDIS files....{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongDateString()));
  352. foreach (ToDo import in list)
  353. {
  354. BeginImport(import);
  355. GetInspectionTypes();
  356. ReadFile(import);
  357. }
  358. foreach (ToDo sendMsg in list)
  359. {
  360. EmailMessage msgToSend = new EmailMessage(ewsClient);
  361. JDISLog.WriteToLog(_logFile, string.Format("Sending Message to: {0}\r\nFor Work Order: {1}\r\nJDIS File: {2}", sendMsg.Sender, sendMsg.WorkOrderNumber, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim()));
  362. string body = "JDIS File: {0} Work Order:{1} {2}";
  363. if (sendMsg.Success)
  364. {
  365. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, "Was Imported Successfully");
  366. }
  367. else
  368. {
  369. body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
  370. msgToSend.Attachments.AddFileAttachment(Path.Combine(_downloadDir, sendMsg.FileName));
  371. }
  372. string fileNameOnly = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1);
  373. msgToSend.Subject = fileNameOnly;
  374. msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
  375. msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
  376. msgToSend.Body = body;
  377. msgToSend.SendAndSaveCopy();
  378. string pathToFile = Path.Combine(_downloadDir, sendMsg.FileName);
  379. if (sendMsg.Success) File.Move(pathToFile, Path.Combine(_successDir, fileNameOnly));
  380. else File.Move(sendMsg.FileName, Path.Combine(_failureDir, fileNameOnly));
  381. }
  382. }
  383. catch (MsalException ex)
  384. {
  385. //Console.WriteLine($"Error acquiring access token: {ex}");
  386. JDISLog.WriteToLog(_logFile, $"Error acquiring access token: {ex}");
  387. }
  388. catch (Exception ex)
  389. {
  390. //Console.WriteLine($"Error: {ex}");
  391. JDISLog.WriteToLog(_logFile, $"Error: {ex}");
  392. }
  393. if (System.Diagnostics.Debugger.IsAttached)
  394. {
  395. Console.WriteLine("Hit any key to exit...");
  396. Console.ReadKey();
  397. }
  398. }
  399. public static void BeginImport(ToDo todo)
  400. {
  401. XMLData.BuildIntervalLookup();
  402. }
  403. private static void SetupDirectories()
  404. {
  405. OS os = new OS();
  406. switch (_os)
  407. {
  408. case "Windows":
  409. os = _settings.OSs.Find(x => x.Name == "WINDOWS");
  410. _logDir = os.Log.Replace("/", "\\");
  411. _logFile = Path.Combine(os.Log.Replace("/", "\\"), "jdis.log");
  412. _successDir = os.Success.Replace("/", "\\");
  413. _failureDir = os.Fail.Replace("/", "\\");
  414. _downloadDir = os.Temp.Replace("/", "\\");
  415. break;
  416. case "Mac":
  417. os = _settings.OSs.Find(x => x.Name == "OSX");
  418. _logDir = os.Log;
  419. _logFile = Path.Combine(os.Log, "jdis.log");
  420. _successDir = os.Success;
  421. _failureDir = os.Fail;
  422. _downloadDir = os.Temp;
  423. break;
  424. case "Linux":
  425. os = _settings.OSs.Find(x => x.Name == "LINUX");
  426. _logDir = os.Log;
  427. _logFile = Path.Combine(os.Log, "jdis.log");
  428. _successDir = os.Success;
  429. _failureDir = os.Fail;
  430. _downloadDir = os.Temp;
  431. break;
  432. default:
  433. break;
  434. }
  435. if (!Directory.Exists(_logDir)) Directory.CreateDirectory(_logDir);
  436. if (!Directory.Exists(_failureDir)) Directory.CreateDirectory(_failureDir);
  437. if (!Directory.Exists(_successDir)) Directory.CreateDirectory(_successDir);
  438. //string path = Path.Combine(_exeDir, "Success");
  439. //if (!Directory.Exists(path))
  440. // Directory.CreateDirectory(path);
  441. //path = Path.Combine(_exeDir, "Fail");
  442. //if (!Directory.Exists(path))
  443. // Directory.CreateDirectory(path);
  444. //path = Path.Combine(_exeDir, "Log");
  445. //if (!Directory.Exists(path))
  446. // Directory.CreateDirectory(path);
  447. }
  448. public static void GetInspectionTypes()
  449. {
  450. List<InspectionType> list = _rservice.RestGet<InspectionType>("inspectiontypes.svc");
  451. InspectionType = new Dictionary<string, int>();
  452. foreach (InspectionType t in list)
  453. {
  454. InspectionType.Add(t.Name, t.ID);
  455. }
  456. }
  457. private static string frmtString
  458. {
  459. get
  460. {
  461. if (_quoted) return "\"{0}\"";
  462. else return "{0}";
  463. }
  464. }
  465. private static List<string> WriteFileToText(string file)
  466. {
  467. List<string> list = new List<string>();
  468. string txt = string.Empty;
  469. using (StreamReader sr = new StreamReader(file))
  470. {
  471. txt = sr.ReadToEnd().Trim();
  472. txt = txt.Replace("\r\r\r", "");
  473. txt = txt.Replace("\r\r", "");
  474. txt = txt.Replace("\r", "");
  475. sr.Close();
  476. }
  477. string[] array = txt.Trim().Split('\n');
  478. list.AddRange(array);
  479. return list;
  480. }
  481. private static DateTime DateFormatter(string d, bool hastime = true)
  482. {
  483. string month, day, year, time;
  484. DateTime dt = new DateTime();
  485. if (d.IndexOf("JAN") != -1)
  486. {
  487. month = "01";
  488. d = d.Replace("JAN", "|");
  489. day = d.Substring(0, d.IndexOf("|"));
  490. year = d.Substring(d.IndexOf("|") + 1, 4);
  491. if (hastime)
  492. time = d.Substring(d.IndexOf(":") - 3 + 2);
  493. else time = "00:00:00.000";
  494. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  495. dt = DateTime.Parse(date);
  496. }
  497. else if (d.IndexOf("FEB") != -1)
  498. {
  499. month = "02";
  500. d = d.Replace("FEB", "|");
  501. day = d.Substring(0, d.IndexOf("|"));
  502. year = d.Substring(d.IndexOf("|") + 1, 4);
  503. if (hastime)
  504. time = d.Substring(d.IndexOf(":") - 3 + 2);
  505. else time = "00:00:00.000";
  506. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  507. dt = DateTime.Parse(date);
  508. }
  509. else if (d.IndexOf("MARCH") != -1)
  510. {
  511. month = "03";
  512. d = d.Replace("MARCH", "|");
  513. day = d.Substring(0, d.IndexOf("|"));
  514. year = d.Substring(d.IndexOf("|") + 1, 4);
  515. if (hastime)
  516. time = d.Substring(d.IndexOf(":") - 3 + 2);
  517. else time = "00:00:00.000";
  518. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  519. dt = DateTime.Parse(date);
  520. }
  521. else if (d.IndexOf("MAR") != -1)
  522. {
  523. month = "03";
  524. d = d.Replace("MAR", "|");
  525. day = d.Substring(0, d.IndexOf("|"));
  526. year = d.Substring(d.IndexOf("|") + 1, 4);
  527. if (hastime)
  528. time = d.Substring(d.IndexOf(":") - 3 + 2);
  529. else time = "00:00:00.000";
  530. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  531. dt = DateTime.Parse(date);
  532. }
  533. else if (d.IndexOf("APRIL") != -1)
  534. {
  535. month = "04";
  536. d = d.Replace("APRIL", "|");
  537. day = d.Substring(0, d.IndexOf("|"));
  538. year = d.Substring(d.IndexOf("|") + 1, 4);
  539. if (hastime)
  540. time = d.Substring(d.IndexOf(":") - 3 + 2);
  541. else time = "00:00:00.000";
  542. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  543. dt = DateTime.Parse(date);
  544. }
  545. else if (d.IndexOf("APR") != -1)
  546. {
  547. month = "04";
  548. d = d.Replace("APR", "|");
  549. day = d.Substring(0, d.IndexOf("|"));
  550. year = d.Substring(d.IndexOf("|") + 1, 4);
  551. if (hastime)
  552. time = d.Substring(d.IndexOf(":") - 3 + 2);
  553. else time = "00:00:00.000";
  554. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  555. dt = DateTime.Parse(date);
  556. }
  557. else if (d.IndexOf("MAY") != -1)
  558. {
  559. month = "05";
  560. d = d.Replace("MAY", "|");
  561. day = d.Substring(0, d.IndexOf("|"));
  562. year = d.Substring(d.IndexOf("|") + 1, 4);
  563. if (hastime)
  564. time = d.Substring(d.IndexOf(":") - 3 + 2);
  565. else time = "00:00:00.000";
  566. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  567. dt = DateTime.Parse(date);
  568. }
  569. else if (d.IndexOf("JUNE") != -1)
  570. {
  571. month = "06";
  572. d = d.Replace("JUNE", "|");
  573. day = d.Substring(0, d.IndexOf("|"));
  574. year = d.Substring(d.IndexOf("|") + 1, 4);
  575. if (hastime)
  576. time = d.Substring(d.IndexOf(":") - 3 + 2);
  577. else time = "00:00:00.000";
  578. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  579. dt = DateTime.Parse(date);
  580. }
  581. else if (d.IndexOf("JUN") != -1)
  582. {
  583. month = "06";
  584. d = d.Replace("JUN", "|");
  585. day = d.Substring(0, d.IndexOf("|"));
  586. year = d.Substring(d.IndexOf("|") + 1, 4);
  587. if (hastime)
  588. time = d.Substring(d.IndexOf(":") - 3 + 2);
  589. else time = "00:00:00.000";
  590. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  591. dt = DateTime.Parse(date);
  592. }
  593. else if (d.IndexOf("JULY") != -1)
  594. {
  595. month = "07";
  596. d = d.Replace("JULY", "|");
  597. day = d.Substring(0, d.IndexOf("|"));
  598. year = d.Substring(d.IndexOf("|") + 1, 4);
  599. if (hastime)
  600. time = d.Substring(d.IndexOf(":") - 3 + 2);
  601. else time = "00:00:00.000";
  602. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  603. dt = DateTime.Parse(date);
  604. }
  605. else if (d.IndexOf("JUL") != -1)
  606. {
  607. month = "07";
  608. d = d.Replace("JUL", "|");
  609. day = d.Substring(0, d.IndexOf("|"));
  610. year = d.Substring(d.IndexOf("|") + 1, 4);
  611. if (hastime)
  612. time = d.Substring(d.IndexOf(":") - 3 + 2);
  613. else time = "00:00:00.000";
  614. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  615. dt = DateTime.Parse(date);
  616. }
  617. else if (d.IndexOf("AUG") != -1)
  618. {
  619. month = "08";
  620. d = d.Replace("AUG", "|");
  621. day = d.Substring(0, d.IndexOf("|"));
  622. year = d.Substring(d.IndexOf("|") + 1, 4);
  623. if (hastime)
  624. time = d.Substring(d.IndexOf(":") - 3 + 2);
  625. else time = "00:00:00.000";
  626. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  627. dt = DateTime.Parse(date);
  628. }
  629. else if (d.IndexOf("SEPT") != -1)
  630. {
  631. month = "09";
  632. d = d.Replace("SEPT", "|");
  633. day = d.Substring(0, d.IndexOf("|"));
  634. year = d.Substring(d.IndexOf("|") + 1, 4);
  635. if (hastime)
  636. time = d.Substring(d.IndexOf(":") - 3 + 2);
  637. else time = "00:00:00.000";
  638. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  639. dt = DateTime.Parse(date);
  640. }
  641. else if (d.IndexOf("SEP") != -1)
  642. {
  643. month = "09";
  644. d = d.Replace("SEP", "|");
  645. day = d.Substring(0, d.IndexOf("|"));
  646. year = d.Substring(d.IndexOf("|") + 1, 4);
  647. if (hastime)
  648. time = d.Substring(d.IndexOf(":") - 3 + 2);
  649. else time = "00:00:00.000";
  650. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  651. dt = DateTime.Parse(date);
  652. }
  653. else if (d.IndexOf("OCT") != -1)
  654. {
  655. month = "10";
  656. d = d.Replace("OCT", "|");
  657. day = d.Substring(0, d.IndexOf("|"));
  658. year = d.Substring(d.IndexOf("|") + 1, 4);
  659. if (hastime)
  660. time = d.Substring(d.IndexOf(":") - 3 + 2);
  661. else time = "00:00:00.000";
  662. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  663. dt = DateTime.Parse(date);
  664. }
  665. else if (d.IndexOf("0CT") != -1)
  666. {
  667. month = "10";
  668. d = d.Replace("0CT", "|");
  669. day = d.Substring(0, d.IndexOf("|"));
  670. year = d.Substring(d.IndexOf("|") + 1, 4);
  671. if (hastime)
  672. time = d.Substring(d.IndexOf(":") - 3 + 2);
  673. else time = "00:00:00.000";
  674. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  675. dt = DateTime.Parse(date);
  676. }
  677. else if (d.IndexOf("NOV") != -1)
  678. {
  679. month = "11";
  680. d = d.Replace("NOV", "|");
  681. day = d.Substring(0, d.IndexOf("|"));
  682. year = d.Substring(d.IndexOf("|") + 1, 4);
  683. if (hastime)
  684. time = d.Substring(d.IndexOf(":") - 3 + 2);
  685. else time = "00:00:00.000";
  686. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  687. dt = DateTime.Parse(date);
  688. }
  689. else
  690. {
  691. month = "12";
  692. d = d.Replace("DEC", "|");
  693. day = d.Substring(0, d.IndexOf("|"));
  694. year = d.Substring(d.IndexOf("|") + 1, 4);
  695. if (hastime)
  696. time = d.Substring(d.IndexOf(":") - 3 + 2);
  697. else time = "00:00:00.000";
  698. string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
  699. dt = DateTime.Parse(date);
  700. }
  701. return dt;
  702. }
  703. private static void ReadFile(ToDo todo)
  704. {
  705. string file = Path.Combine(_downloadDir, todo.FileName);// todo.FileName;
  706. todo.FileName = file;
  707. CustomerImport c = new CustomerImport();
  708. WorkOrderImport wo = new WorkOrderImport();
  709. EquipmentImport eq = new EquipmentImport();
  710. List<PartImport> parts = new List<PartImport>();
  711. //Console.WriteLine("Line 306: " + file);
  712. //Console.WriteLine("Line 307: " + file);
  713. string filemove = string.Empty;
  714. string filetxt = string.Empty;
  715. string inspectionLevel = string.Empty;
  716. bool isSpecial = false;
  717. StringBuilder specialInstructions = new StringBuilder();
  718. int line = 1;
  719. try
  720. {
  721. List<string> filelines = WriteFileToText(file);
  722. for (int i = filelines.Count - 1; i >= 0; i--)
  723. {
  724. if (string.IsNullOrEmpty(filelines[i])) filelines.RemoveAt(i);
  725. }
  726. string[] lines = filelines.ToArray();
  727. foreach (string s in lines)
  728. {
  729. string currentline = s.Trim().Replace("'", "''");
  730. if (currentline.Contains("Page") && currentline.Substring(78).Trim() != "1")
  731. line = 18;
  732. if (currentline.Contains("Page") && currentline.Substring(78).Trim() == "1")
  733. line = 1;
  734. switch (line)
  735. {
  736. case 1:
  737. string strDate = currentline.Substring(5, currentline.IndexOf("*") - 6);
  738. strDate = strDate.Trim();
  739. strDate.Replace(" ", " ");
  740. wo.CreateDate = DateFormatter(strDate);
  741. break;
  742. case 2:
  743. string strWONum = currentline.Substring(currentline.IndexOf("Work Order") + 10, 12);
  744. strWONum = strWONum.Trim();
  745. wo.Number = strWONum;
  746. todo.WorkOrderNumber = strWONum;
  747. _workOrderNumber = strWONum;
  748. string strSeg = currentline.Substring(currentline.IndexOf("Seg.") + 4, 25);
  749. strSeg = strSeg.Trim();
  750. wo.Segment = strSeg;
  751. string strODate = currentline.Substring(currentline.IndexOf("Opn Dt") + 6);
  752. strODate = strODate.Trim();
  753. wo.OpnDt = DateFormatter(strODate, false);
  754. break;
  755. case 5:
  756. c.Name = currentline.Substring(3, 25);
  757. c.Number = currentline.Substring(38, 10);
  758. break;
  759. case 6:
  760. c.Addr1 = currentline.Substring(3, 25);
  761. break;
  762. case 7:
  763. c.Addr2 = currentline.Substring(3, 25);
  764. break;
  765. case 8:
  766. int comma = currentline.IndexOf(",");
  767. int length = currentline.Length - 3;
  768. c.City = (comma == -1) ? "" : currentline.Substring(3, comma - 3);
  769. c.State = currentline.Substring(currentline.IndexOf(",") + 2, 2);
  770. c.Zip = currentline.Substring(comma + 5, 7);
  771. break;
  772. case 11:
  773. eq.Make = currentline.Substring(0, 8).Trim();
  774. eq.Model = currentline.Substring(8, 14).Trim();
  775. eq.SerialNumber = currentline.Substring(22, 22).Trim();
  776. eq.EquipmentNumber = currentline.Substring(42, 16).Trim();
  777. eq.MeterReading = currentline.Substring(60, 7).Trim();
  778. eq.MID = CSVObject.MachineExists(eq.SerialNumber, _connection);
  779. if (eq.MID == 0) _newMachine = true;
  780. break;
  781. default:
  782. break;
  783. }
  784. if (line > 14)
  785. {
  786. if (currentline.EndsWith(" T"))
  787. {
  788. if (currentline.Contains("PM LEVEL"))
  789. {
  790. isSpecial = false;
  791. }
  792. else if (currentline.Contains("PM INTERVAL"))
  793. {
  794. isSpecial = false;
  795. string pminterval = currentline.Substring(currentline.IndexOf(":") + 2);
  796. pminterval = pminterval.Substring(0, pminterval.IndexOf(" ")).Trim();
  797. if (XMLData.IntervalLookup.ContainsKey(pminterval)) wo.InspectionLevel = XMLData.IntervalLookup[pminterval].ToString();
  798. if (!string.IsNullOrEmpty(wo.InspectionLevel)) wo.InspectionInterval = pminterval;
  799. string strService = currentline.Substring(currentline.IndexOf(":") + 2);
  800. strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
  801. strService = strService.Substring(0, strService.IndexOf(" ") + 1).Trim();
  802. if (strService.IndexOf(" ") > 0)
  803. strService = strService.Substring(0, strService.IndexOf(" ")).Trim();
  804. if (InspectionType.ContainsKey(strService))
  805. wo.InspectionType = InspectionType[strService].ToString();
  806. else wo.InspectionType = InspectionType["PM"].ToString();
  807. string codeanddescriptionoriginal = currentline.Substring(currentline.IndexOf(":") + 2);
  808. codeanddescriptionoriginal = codeanddescriptionoriginal.Substring(0, codeanddescriptionoriginal.IndexOf(" T") - 3).Trim();
  809. wo.CodeAndDescriptionOriginal = codeanddescriptionoriginal;
  810. }
  811. else if (currentline.Contains("EMPID"))
  812. {
  813. isSpecial = false;
  814. string empid = currentline.Substring(currentline.IndexOf(":") + 2);
  815. empid = empid.Substring(0, empid.IndexOf(" ")).Trim();
  816. wo.TechnicianUserID = empid;
  817. }
  818. else if (currentline.Contains("PROMISE DATE"))
  819. {
  820. isSpecial = false;
  821. string promisedate = currentline.Substring(currentline.IndexOf(":") + 2);
  822. promisedate = promisedate.Substring(0, promisedate.IndexOf(" ")).Trim();
  823. wo.ScheduledStartDate = DateFormatter(promisedate, false);
  824. }
  825. else if (currentline.Contains("SPECIAL INSTRUCTIONS"))
  826. {
  827. isSpecial = true;
  828. string special = currentline.Substring(currentline.IndexOf(":") + 2);
  829. special = special.Substring(0, special.IndexOf(" T") - 1).Trim();
  830. specialInstructions.Append(special);
  831. }
  832. else
  833. {
  834. if (isSpecial)
  835. {
  836. string addspecial = currentline.Substring(0, currentline.IndexOf(" T") - 1).Trim();
  837. specialInstructions.Append(string.Format(" {0}", addspecial));
  838. }
  839. }
  840. }
  841. else
  842. {
  843. isSpecial = false;
  844. int qty = 0;
  845. if (currentline.Length > 0)
  846. {
  847. string input = currentline.Substring(0, (currentline.IndexOf(" ") == -1) ? 1 : currentline.IndexOf(" ")).Trim();
  848. if (int.TryParse(input, out qty))
  849. {
  850. if (qty < 100 && !currentline.Contains("HR"))
  851. {
  852. PartImport pt = new PartImport();
  853. string sline = currentline.Substring(19).Trim();
  854. //pt.Description = currentline.Substring(34, 14);
  855. pt.Number = sline.Substring(0, sline.IndexOf(" "));
  856. sline = sline.Substring(sline.IndexOf(" ")).Trim();
  857. pt.Description = sline.Substring(0, sline.IndexOf(" ")).Trim();
  858. pt.Qty = currentline.Substring(0, currentline.IndexOf(" ")).Trim();
  859. parts.Add(pt);
  860. }
  861. }
  862. }
  863. }
  864. }
  865. line++;
  866. }
  867. if (wo.ScheduledStartDate == DateTime.MinValue) wo.ScheduledStartDate = DateTime.Now;
  868. List<CSVObject> list = new List<CSVObject>();
  869. List<CSVObject> exceptions = new List<CSVObject>();
  870. if (parts.Count == 0)
  871. {
  872. PartImport p = new PartImport();
  873. p.Description = string.Empty;
  874. p.Qty = string.Empty;
  875. p.Number = string.Empty;
  876. parts.Add(p);
  877. }
  878. //Put API Integration here
  879. if (_runAPI)
  880. {
  881. APIPush(c, wo, parts, eq, todo);
  882. }
  883. else
  884. {
  885. static void conn_InfoMsg(object sender, SqlInfoMessageEventArgs e)
  886. {
  887. _sqlMessages.Add(e.Message);
  888. }
  889. foreach (PartImport prt in parts)
  890. {
  891. CSVObject obj = new CSVObject();
  892. obj.Address = string.Format(frmtString, c.Addr1.Trim());
  893. obj.Address2 = string.Format(frmtString, c.Addr2.Trim());
  894. obj.City = string.Format(frmtString, c.City.Trim());
  895. obj.State = string.Format(frmtString, c.State.Trim());
  896. obj.CustomerName = string.Format(frmtString, c.Name.Trim());
  897. obj.CustomerNumber = string.Format(frmtString, c.Number.Trim());
  898. obj.DBSWorkOrderNumber = string.Format(frmtString, wo.Number.Trim());
  899. obj.EquipmentNumber = string.Format(frmtString, eq.EquipmentNumber.Trim());
  900. obj.Make = string.Format(frmtString, eq.Make.Trim());
  901. obj.MeterReading = string.Format(frmtString, eq.MeterReading.Trim());
  902. obj.Model = string.Format(frmtString, eq.Model.Trim());
  903. obj.PartNumber = string.Format(frmtString, prt.Number.Trim());
  904. obj.PartNumberDescription = string.Format(frmtString, prt.Description.Trim());
  905. obj.Quantity = string.Format(frmtString, prt.Qty.Trim());
  906. obj.SegmentNumber = string.Format(frmtString, wo.Segment.Trim());
  907. obj.SerialNumber = string.Format(frmtString, eq.SerialNumber.Trim());
  908. obj.ZipCode = string.Format(frmtString, c.Zip.Trim());
  909. obj.CodeAndDescription = string.Format(frmtString, wo.InspectionLevel.Trim());
  910. obj.SpecialInstructions = specialInstructions.ToString();
  911. obj.CodeAndDescriptionOriginal = string.Format(frmtString, wo.CodeAndDescriptionOriginal);
  912. obj.ContractTypeCode = string.Format(frmtString, "");
  913. obj.DateActualStart = string.Format(frmtString, wo.CreateDate);
  914. obj.FamilyCode = string.Format(frmtString, "");
  915. obj.FamilyDescription = string.Format(frmtString, "");
  916. obj.JobSiteContactName = string.Format(frmtString, "");
  917. obj.JobSiteContactPhone = string.Format(frmtString, "");
  918. obj.LastServiceDate = string.Format(frmtString, "");
  919. obj.PriorityCode = string.Format(frmtString, "");
  920. obj.ReferenceDocNumber = string.Format(frmtString, "");
  921. obj.ServiceTech = string.Format(frmtString, wo.TechnicianUserID);
  922. obj.StoreDescription = string.Format(frmtString, "");
  923. obj.Store = string.Format(frmtString, "");
  924. obj.TechName = string.Format(frmtString, "");
  925. obj.Year = string.Format(frmtString, "");
  926. obj.ScheduledStartDate = string.Format(frmtString, wo.ScheduledStartDate.ToString("yyyy-MM-dd hh:mm:ss"));
  927. obj.InspectionType = string.Format(frmtString, wo.InspectionType.ToString());
  928. obj.Validate();
  929. if (string.IsNullOrEmpty(obj.SerialNumber))
  930. {
  931. exceptions.Add(obj);
  932. //throw new ApplicationException("Serial Number is missing.");
  933. }
  934. else list.Add(obj);
  935. if (list.Count == 0)
  936. {
  937. StringBuilder sbException = new StringBuilder();
  938. foreach (CSVObject csvobj in exceptions)
  939. foreach (PropertyInfo pi in csvobj.GetType().GetProperties())
  940. {
  941. sbException.AppendLine(string.Format("{0}: {1}", pi.Name, pi.GetValue(csvobj, null)));
  942. }
  943. throw new ApplicationException(string.Format("Object Validation Error\r\n{0}", sbException.ToString()));
  944. }
  945. }
  946. filemove = Path.Combine("Success", file);// string.Format("{0}\\{1}\\{2}", _currentDir, _settings["SUCCESSDIR"], file);
  947. try
  948. {
  949. SqlConnection conn = new SqlConnection(_connection);
  950. conn.Open();
  951. string errorstr = CSVObject.WriteToDB(list, conn);
  952. conn.Close();
  953. conn.Dispose();
  954. if (!string.IsNullOrEmpty(errorstr)) throw new ApplicationException(errorstr);
  955. SqlCommand cmd = new SqlCommand("usp_DoImport", new SqlConnection(_connection));
  956. cmd.CommandTimeout = 0;
  957. SqlParameter sqlReturn = cmd.Parameters.Add("@b", SqlDbType.Int);
  958. sqlReturn.Direction = ParameterDirection.ReturnValue;
  959. cmd.Connection.Open();
  960. cmd.Connection.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMsg);
  961. cmd.Connection.FireInfoMessageEventOnUserErrors = true;
  962. cmd.CommandType = CommandType.StoredProcedure;
  963. cmd.ExecuteNonQuery();
  964. if (Convert.ToInt32(cmd.Parameters["@b"].Value) != 0)
  965. throw new Exception("Error happend in the do import");
  966. cmd.Connection.Close();
  967. cmd.Dispose();
  968. conn.Dispose();
  969. SqlCommand delcmd = new SqlCommand("Delete Results_Brandt", new SqlConnection(_connection));
  970. delcmd.CommandTimeout = 0;
  971. delcmd.Connection.Open();
  972. delcmd.CommandType = CommandType.Text;
  973. try
  974. {
  975. delcmd.ExecuteNonQuery();
  976. }
  977. catch (Exception dex)
  978. {
  979. throw new Exception(dex.Message);
  980. }
  981. delcmd.Connection.Close();
  982. delcmd.Dispose();
  983. }
  984. catch (Exception exSql)
  985. {
  986. string msg = exSql.Message;
  987. string logmsg = string.Format("Date: {0} Error: {1}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), exSql.Message);
  988. WriteToLog(logmsg);
  989. todo.Validation = exSql.Message + " " + _workOrderNumber;
  990. filemove = Path.Combine("Fail", todo.FileName);
  991. //File.Move(todo.FileName, filemove);
  992. //MailSvc.SendResponse(msg, _workOrderNumber);
  993. }
  994. Console.WriteLine("Line 584: " + filemove);
  995. if (File.Exists(filemove)) File.Delete(filemove);
  996. //File.Move(file, filemove);
  997. if (_log)
  998. {
  999. 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, "********************************");
  1000. WriteToLog(successmsg);
  1001. if (exceptions.Count > 0)
  1002. {
  1003. foreach (CSVObject csvobj in exceptions)
  1004. {
  1005. 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, "********************************");
  1006. WriteToLog(csvmsg);
  1007. }
  1008. }
  1009. if (_sqlMessages.Count > 0)
  1010. {
  1011. WriteToLog("***********************SQL Messages************************");
  1012. foreach (string sqlmessg in _sqlMessages)
  1013. WriteToLog(sqlmessg);
  1014. WriteToLog("*********************End SQL Messages**********************");
  1015. }
  1016. }
  1017. using (SqlConnection doublecheck = new SqlConnection(_connection))
  1018. {
  1019. SqlCommand cmddoublecheck = doublecheck.CreateCommand();
  1020. cmddoublecheck.Connection.Open();
  1021. cmddoublecheck.CommandTimeout = 0;
  1022. cmddoublecheck.CommandText = string.Format("Select MAX(ID) from WorkOrder where Number = '{0}'", wo.Number);
  1023. cmddoublecheck.CommandType = CommandType.Text;
  1024. int rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  1025. cmddoublecheck.Dispose();
  1026. if (rslt > 0)
  1027. {
  1028. cmddoublecheck.CommandText = string.Format("Select ID from Inspection where workorderid = {0}", rslt);
  1029. rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
  1030. if (rslt > 0)
  1031. {
  1032. todo.Success = true;
  1033. //MailSvc.SendResponse("Work Order was imported successfully.", wo.Number);
  1034. }
  1035. else
  1036. {
  1037. //string noTemplate = string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
  1038. 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);
  1039. todo.Success = false;
  1040. }
  1041. }
  1042. else
  1043. {
  1044. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}", wo.Number);//)
  1045. }
  1046. //MailSvc.SendResponse(string.Format("Failed to import work order {0}.", wo.Number), wo.Number);
  1047. }
  1048. }
  1049. //Console.ReadLine();
  1050. }
  1051. catch (Exception ex)
  1052. {
  1053. string exMesg = string.Empty;
  1054. try
  1055. {
  1056. 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);
  1057. }
  1058. catch (Exception exSend)
  1059. {
  1060. Console.Write(exSend.Message);
  1061. }
  1062. WriteToLog(exMesg);
  1063. filemove = Path.Combine("Fail", file);//, file);
  1064. try
  1065. {
  1066. Console.WriteLine("Line 634: " + file);
  1067. Console.WriteLine("Line 635: " + filemove);
  1068. //File.Move(file, filemove);
  1069. }
  1070. catch (Exception moveExcept)
  1071. {
  1072. Console.WriteLine(moveExcept.Message);
  1073. }
  1074. todo.Success = false;
  1075. todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg);
  1076. //MailSvc.SendResponse(string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg), wo.Number, filemove);
  1077. }
  1078. }
  1079. private static void CreateLogFile(string logfile)
  1080. {
  1081. using (StreamWriter sw = File.CreateText(logfile))
  1082. {
  1083. sw.WriteLine("******************************************");
  1084. sw.WriteLine("****************IMPORT LOG****************");
  1085. sw.WriteLine("******************************************");
  1086. }
  1087. }
  1088. public static void WriteToLog(string message, string sqlmessage = "")
  1089. {
  1090. string logfile = Path.Combine("Log", "log.log");
  1091. if (!File.Exists(logfile))
  1092. {
  1093. CreateLogFile(logfile);
  1094. }
  1095. using (StreamWriter sw = File.AppendText(logfile))
  1096. {
  1097. sw.WriteLine(message);
  1098. if (!string.IsNullOrEmpty(sqlmessage))
  1099. sw.WriteLine(sqlmessage);
  1100. }
  1101. }
  1102. public static bool IsWindows() =>
  1103. System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
  1104. public static bool IsMacOS() =>
  1105. System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX);
  1106. public static bool IsLinux() =>
  1107. System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux);
  1108. }
  1109. public class ToDo
  1110. {
  1111. private bool _success = false;
  1112. public bool Success { get { return _success; } set { _success = value; } }
  1113. public string Sender { get; set; }
  1114. public string SenderName { get; set; }
  1115. public string FileName { get; set; }
  1116. public string Validation { get; set; }
  1117. public string WorkOrderNumber { get; set; }
  1118. }
  1119. }