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

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