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

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