LogikalClient.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.SQLite;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. using Comal.Classes;
  13. using H.Formatters;
  14. using H.Pipes;
  15. using InABox.Clients;
  16. using InABox.Configuration;
  17. using InABox.Core;
  18. using InABox.Integration.Awg;
  19. using InABox.Integration.Logikal;
  20. using InABox.Wpf;
  21. using InABox.WPF;
  22. using Newtonsoft.Json;
  23. using PRSDesktop.Integrations.Logikal;
  24. using Exception = System.Exception;
  25. using Process = System.Diagnostics.Process;
  26. namespace PRSDesktop;
  27. public class LogikalClient : IDisposable
  28. {
  29. public static LogikalClient Instance { get; } = new LogikalClient();
  30. private readonly PipeClient<LogikalMessage> _client;
  31. private ConcurrentDictionary<Guid, ManualResetEventSlim> Events = new();
  32. private ConcurrentDictionary<Guid, LogikalMessage> Responses = new();
  33. private const int DefaultRequestTimeout = 5 * 60 * 1000; // 5 minutes
  34. public LogikalSettings Settings { get; private set; }
  35. private string? _lastDriveAccessed = null;
  36. public bool Ready { get; private set; } = false;
  37. private LogikalErrorResponse NOTLOGGEDIN = new LogikalErrorResponse()
  38. {
  39. Status = LogikalStatus.NotLoggedIn,
  40. Message = "Not Logged In"
  41. };
  42. private LogikalClient()
  43. {
  44. Settings = new GlobalConfiguration<LogikalSettings>().Load();
  45. var _basedirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? "";
  46. var _logikalapp = System.IO.Path.Combine(_basedirectory, "PRSLogikal", "PRSLogikal.exe");
  47. if (!File.Exists(_logikalapp))
  48. _logikalapp = @"C:\development\prs\prs.logikal\bin\Debug\prslogikal.exe";
  49. if (!File.Exists(_logikalapp))
  50. {
  51. MessageBox.Show("Unable to locate PRS/Logikal interface!");
  52. return;
  53. }
  54. var _info = new ProcessStartInfo(_logikalapp);
  55. _info.WindowStyle = ProcessWindowStyle.Minimized;
  56. Process.Start(_info);
  57. _client = new PipeClient<LogikalMessage>("$logikal", formatter: new NewtonsoftJsonFormatter());
  58. _client.Connected += Client_Connected;
  59. _client.Disconnected += Client_Disconnected;
  60. _client.MessageReceived += Client_MessageReceived;
  61. _client.ExceptionOccurred += Client_ExceptionOccurred;
  62. _client.ConnectAsync();
  63. }
  64. public void Dispose()
  65. {
  66. _client.DisposeAsync().AsTask().Wait();
  67. }
  68. private void Client_Connected(object? sender, H.Pipes.Args.ConnectionEventArgs<LogikalMessage> e)
  69. {
  70. Logger.Send(LogType.Information, "", $"Connected to Pipe: {e.Connection.PipeName}");
  71. //Disconnected = false;
  72. // Here we will register a Licence "Hit" for the Logikal interface
  73. }
  74. private void Client_Disconnected(object? sender, H.Pipes.Args.ConnectionEventArgs<LogikalMessage> e)
  75. {
  76. Logger.Send(LogType.Information, "", $"Disconnected from Pipe: {e.Connection.PipeName}");
  77. foreach (var ev in Events)
  78. {
  79. Responses.TryAdd(ev.Key, LogikalMessage.Error("Disconnected"));
  80. ev.Value.Set();
  81. }
  82. //Disconnected = true;
  83. }
  84. private void Client_ExceptionOccurred(object? sender, H.Pipes.Args.ExceptionEventArgs e)
  85. {
  86. Logger.Send(LogType.Error, "", $"Exception occured: {e.Exception.Message}");
  87. }
  88. private static Dictionary<LogikalMethod, Type> _methods = new Dictionary<LogikalMethod, Type>()
  89. {
  90. { LogikalMethod.Connect, typeof(LogikalConnectResponse) },
  91. { LogikalMethod.Login, typeof(LogikalLoginResponse) },
  92. { LogikalMethod.Logout, typeof(LogikalLogoutResponse) },
  93. { LogikalMethod.Disconnect, typeof(LogikalDisconnectResponse) },
  94. { LogikalMethod.ProjectCentres, typeof(LogikalProjectCentresResponse<LogikalProjectCentre, LogikalProject>) },
  95. { LogikalMethod.Projects, typeof(LogikalProjectsResponse<LogikalProject>) },
  96. { LogikalMethod.Phases, typeof(LogikalPhasesResponse<LogikalPhase>) },
  97. { LogikalMethod.ElevationSummary, typeof(LogikalElevationSummaryResponse<LogikalElevationSummary>) },
  98. { LogikalMethod.ElevationDetail, typeof(LogikalElevationDetailResponse<LogikalElevationDetail,LogikalFinish,LogikalProfile,LogikalGasket,LogikalComponent, LogikalGlass, LogikalLabour>) },
  99. { LogikalMethod.BOM, typeof(LogikalBOMResponse<LogikalBOM,LogikalFinish,LogikalProfile,LogikalGasket,LogikalComponent, LogikalGlass, LogikalLabour>) },
  100. { LogikalMethod.Error, typeof(LogikalErrorResponse) },
  101. };
  102. private LogikalResponse FromMessage(LogikalMessage message)
  103. {
  104. try
  105. {
  106. LogikalResponse _result = null;
  107. if (_methods.TryGetValue(message.Method, out var _type))
  108. {
  109. _result = JsonConvert.DeserializeObject(message.Payload, _type) as LogikalResponse;
  110. if (_result != null)
  111. return _result;
  112. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Deserialize Failure: {message.Method}: {message.Payload}" };
  113. }
  114. else
  115. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Invalid Message Method: {message.Method}: {message.Payload}" };
  116. }
  117. catch (Exception e)
  118. {
  119. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = $"Exception Deserializing Response: {e.Message}\n{e.StackTrace}" };
  120. }
  121. }
  122. public LogikalResponse Send(LogikalRequest request, int timeout = DefaultRequestTimeout)
  123. {
  124. var checkfile = System.IO.Path.Combine(CoreUtils.GetPath(),"simulator.logikal");
  125. var filename = System.IO.Path.Combine(CoreUtils.GetPath(), $"{request.Method()}.logikal");
  126. if (File.Exists(checkfile) && File.Exists(filename))
  127. {
  128. var dec = Serialization.Deserialize<LogikalMessage>(File.ReadAllText(filename));
  129. if (dec != null)
  130. return FromMessage(dec);
  131. }
  132. var message = new LogikalMessage()
  133. {
  134. ID = Guid.NewGuid(),
  135. Method = request.Method(),
  136. Payload = Serialization.Serialize(request),
  137. };
  138. var ev = Queue(message.ID);
  139. _client.WriteAsync(message);
  140. var result = GetResult(message.ID, ev, timeout);
  141. if (File.Exists(checkfile))
  142. {
  143. var enc = Serialization.Serialize(result);
  144. File.WriteAllText(filename, enc);
  145. }
  146. return FromMessage(result);
  147. }
  148. public ManualResetEventSlim Queue(Guid id)
  149. {
  150. var ev = new ManualResetEventSlim();
  151. Events[id] = ev;
  152. return ev;
  153. }
  154. public LogikalMessage GetResult(Guid id, ManualResetEventSlim ev, int timeout)
  155. {
  156. if (Responses.TryRemove(id, out var result))
  157. {
  158. Events.TryRemove(id, out ev);
  159. return result;
  160. }
  161. try
  162. {
  163. if (!ev.Wait(timeout))
  164. {
  165. return LogikalMessage.Error("Timeout");
  166. }
  167. }
  168. catch (Exception e)
  169. {
  170. Console.WriteLine(e);
  171. throw;
  172. }
  173. Responses.TryRemove(id, out result);
  174. Events.TryRemove(id, out ev);
  175. return result ?? LogikalMessage.Error("Unknown");
  176. }
  177. private void Client_MessageReceived(object? sender, H.Pipes.Args.ConnectionMessageEventArgs<LogikalMessage?> e)
  178. {
  179. if (Events.TryGetValue(e.Message.ID, out var ev))
  180. {
  181. Responses[e.Message.ID] = e.Message;
  182. ev.Set();
  183. }
  184. }
  185. ~LogikalClient()
  186. {
  187. Dispose();
  188. }
  189. public LogikalResponse Initialize()
  190. {
  191. string? result = _lastDriveAccessed;
  192. var _processes = Process.GetProcesses()
  193. .Where(x=>x.ProcessName.ToLower().Equals("logikal")
  194. //&& Regex.IsMatch(x.MainModule?.FileName ?? "", @"^ofcas\\[A-Za-z]\\common\\bin\\logikal\.exe$", RegexOptions.IgnoreCase)
  195. ).ToArray();
  196. if (_processes.Length == 0)
  197. return new LogikalErrorResponse() { Status = LogikalStatus.NotRunning, Message = "Logikal is not running"};
  198. var drives = _processes
  199. .Select(x => x.MainModule?.FileName.ToLower()
  200. .Split([@"ofcas\"], StringSplitOptions.None)
  201. .LastOrDefault()?
  202. .Replace(@"\common\bin\logikal.exe", "")
  203. .ToUpper() ?? "C")
  204. .Distinct()
  205. .OrderBy(x=>x)
  206. .ToArray();
  207. if (drives.Length == 1)
  208. result = drives[0];
  209. else
  210. {
  211. Dictionary<string, string> instances = new Dictionary<string, string>();
  212. foreach (var drive in drives)
  213. instances.Add(drive, $@"{drive} Drive");
  214. DictionaryRadioEdit.Execute<string>(instances, "Select Database", null, ref result);
  215. }
  216. if (string.IsNullOrEmpty(result))
  217. return new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Cancelled by User"};
  218. if (!Equals(result, _lastDriveAccessed))
  219. {
  220. if (Ready)
  221. {
  222. Logout();
  223. Disconnect();
  224. }
  225. Ready = false;
  226. }
  227. _lastDriveAccessed = result;
  228. return new LogikalInitializeResponse() { Path = $@"{result}:\logikalstarter.exe" };
  229. }
  230. public LogikalResponse Connect(string path)
  231. {
  232. if (Ready)
  233. return new LogikalConnectResponse();
  234. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  235. Progress.ShowModal("Connecting To Logikal...", progress =>
  236. {
  237. Client.Save(new LogikalUsage(),"");
  238. try
  239. {
  240. _result = Send(new LogikalConnectRequest(path));
  241. }
  242. catch (Exception e)
  243. {
  244. _result = new LogikalErrorResponse() { Status = LogikalStatus.CannotConnect, Message = e.Message };
  245. }
  246. });
  247. return _result;
  248. }
  249. public LogikalResponse Disconnect()
  250. {
  251. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  252. Progress.ShowModal("Disconnecting From Logikal...", progress =>
  253. {
  254. try
  255. {
  256. _result = Send(new LogikalDisconnectRequest())
  257. .Success<LogikalLogoutResponse>(r => { Ready = false; });
  258. }
  259. catch (Exception e)
  260. {
  261. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  262. }
  263. });
  264. return _result;
  265. }
  266. public LogikalResponse Login()
  267. {
  268. if (Ready)
  269. return new LogikalLoginResponse();
  270. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  271. Progress.ShowModal("Logging In...", progress =>
  272. {
  273. try
  274. {
  275. _result = Send(new LogikalLoginRequest())
  276. .Success<LogikalLoginResponse>(r => { Ready = true; });
  277. }
  278. catch (Exception e)
  279. {
  280. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  281. }
  282. });
  283. return _result;
  284. }
  285. public LogikalResponse Logout()
  286. {
  287. if (!Ready)
  288. return new LogikalLogoutResponse();
  289. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  290. Progress.ShowModal("Logging Out...", progress =>
  291. {
  292. try
  293. {
  294. _result = Send(new LogikalLogoutRequest())
  295. .Success<LogikalLogoutResponse>(r => { Ready = false; });
  296. }
  297. catch (Exception e)
  298. {
  299. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  300. }
  301. });
  302. return _result;
  303. }
  304. public LogikalResponse GetProjectCentres()
  305. {
  306. if (!Ready)
  307. return NOTLOGGEDIN;
  308. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  309. Progress.ShowModal("Retrieving Project Centres...", progress =>
  310. {
  311. try
  312. {
  313. _result = Send(new LogikalProjectCentresRequest());
  314. }
  315. catch (Exception e)
  316. {
  317. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  318. }
  319. });
  320. return _result;
  321. }
  322. public LogikalResponse GetProjects(string jobnumber)
  323. {
  324. if (!Ready)
  325. return NOTLOGGEDIN;
  326. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  327. Progress.ShowModal("Retrieving Projects...", progress =>
  328. {
  329. try
  330. {
  331. _result = Send(new LogikalProjectsRequest(jobnumber));
  332. }
  333. catch (Exception e)
  334. {
  335. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  336. }
  337. });
  338. return _result;
  339. }
  340. public LogikalResponse GetProject(Guid projectid)
  341. {
  342. if (!Ready)
  343. return NOTLOGGEDIN;
  344. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  345. Progress.ShowModal("Retrieving Project...", progress =>
  346. {
  347. try
  348. {
  349. _result = Send(new LogikalProjectRequest(projectid));
  350. }
  351. catch (Exception e)
  352. {
  353. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  354. }
  355. });
  356. return _result;
  357. }
  358. public LogikalResponse GetPhases(Guid projectid)
  359. {
  360. if (!Ready)
  361. return NOTLOGGEDIN;
  362. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  363. Progress.ShowModal("Retrieving Project...", progress =>
  364. {
  365. try
  366. {
  367. _result = Send(new LogikalPhasesRequest(projectid));
  368. }
  369. catch (Exception e)
  370. {
  371. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  372. }
  373. });
  374. return _result;
  375. }
  376. public LogikalResponse GetElevationSummaries(Guid projectid, string phase)
  377. {
  378. if (!Ready)
  379. return NOTLOGGEDIN;
  380. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  381. Progress.ShowModal("Retrieving Elevations...", progress =>
  382. {
  383. try
  384. {
  385. _result = Send(new LogikalElevationSummaryRequest(projectid, phase));
  386. }
  387. catch (Exception e)
  388. {
  389. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  390. }
  391. });
  392. return _result;
  393. }
  394. public LogikalResponse GetBillOfMaterials(Guid projectid, Guid[] elevationids, bool excel, bool sqlite)
  395. {
  396. if (!Ready)
  397. return NOTLOGGEDIN;
  398. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  399. Progress.ShowModal("Retrieving Elevations...", progress =>
  400. {
  401. try
  402. {
  403. var _request = new LogikalBOMRequest(projectid, elevationids);
  404. _result = Send(_request)
  405. .Success<LogikalBOMResponse<
  406. LogikalElevationDetail,
  407. LogikalFinish,
  408. LogikalProfile,
  409. LogikalGasket,
  410. LogikalComponent,
  411. LogikalGlass,
  412. LogikalLabour>>(response =>
  413. {
  414. ExtractBOMData([response.BOM], true, excel);
  415. });
  416. }
  417. catch (Exception e)
  418. {
  419. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  420. }
  421. });
  422. return _result;
  423. }
  424. public LogikalResponse GetElevationDetails(Guid projectid, Guid[] elevationids, bool excel, bool sqlite)
  425. {
  426. if (!Ready)
  427. return NOTLOGGEDIN;
  428. LogikalResponse _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = "Unknown Error" };
  429. Progress.ShowModal("Retrieving Elevations...", progress =>
  430. {
  431. try
  432. {
  433. var _request = new LogikalElevationDetailRequest(
  434. projectid,
  435. elevationids,
  436. Settings.DrawingFormat == Comal.Classes.LogikalDrawingFormat.DXF
  437. ? InABox.Integration.Logikal.LogikalDrawingFormat.DXF
  438. : InABox.Integration.Logikal.LogikalDrawingFormat.PNG,
  439. Settings.DrawingView == Comal.Classes.LogikalDrawingView.Exterior
  440. ? InABox.Integration.Logikal.LogikalDrawingView.Exterior
  441. : InABox.Integration.Logikal.LogikalDrawingView.Interior,
  442. Settings.DrawingType == Comal.Classes.LogikalDrawingType.Explosion
  443. ? InABox.Integration.Logikal.LogikalDrawingType.Explosion
  444. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.Section
  445. ? InABox.Integration.Logikal.LogikalDrawingType.Section
  446. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.Elevation
  447. ? InABox.Integration.Logikal.LogikalDrawingType.Elevation
  448. : Settings.DrawingType == Comal.Classes.LogikalDrawingType.ElevationWithSectionLines
  449. ? InABox.Integration.Logikal.LogikalDrawingType.ElevationWithSectionLines
  450. : InABox.Integration.Logikal.LogikalDrawingType.SectionLine
  451. );
  452. _result = Send(_request)
  453. .Success<LogikalElevationDetailResponse<
  454. LogikalElevationDetail,
  455. LogikalFinish,
  456. LogikalProfile,
  457. LogikalGasket,
  458. LogikalComponent,
  459. LogikalGlass,
  460. LogikalLabour>>(response =>
  461. {
  462. ExtractBOMData(response.Elevations, false, excel);
  463. });
  464. }
  465. catch (Exception e)
  466. {
  467. _result = new LogikalErrorResponse() { Status = LogikalStatus.Error, Message = e.Message };
  468. }
  469. });
  470. return _result;
  471. }
  472. private T CheckValue<T>(object value)
  473. {
  474. if (value == null || value is DBNull || value.GetType() != typeof(T))
  475. return default(T);
  476. return (T)value;
  477. }
  478. private double GetScale(LogikalMeasurement scale)
  479. {
  480. return scale == LogikalMeasurement.Metres
  481. ? 1.0 / 1000.0
  482. : 1.0;
  483. }
  484. private void ExtractBOMData(IEnumerable<LogikalElevationDetail> elevations, bool optimised, bool includeexcel)
  485. {
  486. foreach (var elevation in elevations)
  487. {
  488. var file = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), "sqlite3");
  489. File.WriteAllBytes(file,elevation.SQLiteData);
  490. var sb = new SQLiteConnectionStringBuilder();
  491. sb.DataSource = file;
  492. using (var _connection = new SQLiteConnection(sb.ToString()))
  493. {
  494. _connection.Open();
  495. // Get Finishes
  496. using (var _data = new SQLiteCommand(_connection))
  497. {
  498. _data.CommandText = Settings.FinishSQL.Replace('\n', ' ');
  499. try
  500. {
  501. using (var _reader = _data.ExecuteReader())
  502. {
  503. DataTable _dt = new DataTable();
  504. _dt.Load(_reader);
  505. List<LogikalFinish> finishes = new List<LogikalFinish>();
  506. foreach (DataRow row in _dt.Rows)
  507. {
  508. var _finish = new LogikalFinish();
  509. _finish.Code = CheckValue<string>(row[nameof(LogikalFinish.Code)]);
  510. _finish.Description = CheckValue<string>(row[nameof(LogikalFinish.Description)]);
  511. finishes.Add(_finish);
  512. }
  513. elevation.Finishes = finishes;
  514. }
  515. }
  516. catch (Exception e)
  517. {
  518. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  519. }
  520. }
  521. // Get Profiles
  522. using (var _data = new SQLiteCommand(_connection))
  523. {
  524. _data.CommandText = optimised
  525. ? Settings.BillOfMaterialsProfileSQL.Replace('\n', ' ')
  526. : Settings.DesignProfileSQL.Replace('\n', ' ');
  527. try
  528. {
  529. using (var _reader = _data.ExecuteReader())
  530. {
  531. DataTable _dt = new DataTable();
  532. _dt.Load(_reader);
  533. List<LogikalProfile> profiles = new List<LogikalProfile>();
  534. foreach (DataRow row in _dt.Rows)
  535. {
  536. var _profile = new LogikalProfile();
  537. _profile.Code = CheckValue<string>(row[nameof(LogikalProfile.Code)]);
  538. _profile.Description = CheckValue<string>(row[nameof(LogikalProfile.Description)]);
  539. _profile.Quantity = CheckValue<Int64>(row[nameof(LogikalProfile.Quantity)]);
  540. _profile.Cost = CheckValue<double>(row[nameof(LogikalProfile.Cost)]);
  541. _profile.Finish = CheckValue<string>(row[nameof(LogikalProfile.Finish)]);
  542. _profile.Length = CheckValue<double>(row[nameof(LogikalProfile.Length)]) *
  543. GetScale(Settings.ProfileMeasurement);
  544. profiles.Add(_profile);
  545. }
  546. elevation.Profiles = profiles;
  547. }
  548. }
  549. catch (Exception e)
  550. {
  551. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  552. }
  553. }
  554. // Get Gaskets
  555. using (var _data = new SQLiteCommand(_connection))
  556. {
  557. _data.CommandText = Settings.GasketSQL.Replace('\n', ' ');
  558. try
  559. {
  560. using (var _reader = _data.ExecuteReader())
  561. {
  562. DataTable _dt = new DataTable();
  563. _dt.Load(_reader);
  564. List<LogikalGasket> gaskets = new List<LogikalGasket>();
  565. foreach (DataRow row in _dt.Rows)
  566. {
  567. var _gasket = new LogikalGasket();
  568. _gasket.Code = CheckValue<string>(row[nameof(LogikalGasket.Code)]);
  569. _gasket.Description = CheckValue<string>(row[nameof(LogikalGasket.Description)]);
  570. _gasket.Quantity = CheckValue<Int64>(row[nameof(LogikalGasket.Quantity)]);
  571. _gasket.Cost = CheckValue<double>(row[nameof(LogikalGasket.Cost)]);
  572. _gasket.Length = CheckValue<double>(row[nameof(LogikalGasket.Length)]) *
  573. GetScale(Settings.GasketMeasurement);
  574. gaskets.Add(_gasket);
  575. }
  576. elevation.Gaskets = gaskets;
  577. }
  578. }
  579. catch (Exception e)
  580. {
  581. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  582. }
  583. }
  584. // Get Components
  585. using (var _data = new SQLiteCommand(_connection))
  586. {
  587. _data.CommandText = Settings.ComponentSQL.Replace('\n', ' ');
  588. try
  589. {
  590. using (var _reader = _data.ExecuteReader())
  591. {
  592. DataTable _dt = new DataTable();
  593. _dt.Load(_reader);
  594. List<LogikalComponent> components = new List<LogikalComponent>();
  595. foreach (DataRow row in _dt.Rows)
  596. {
  597. var _component = new LogikalComponent();
  598. _component.Code = CheckValue<string>(row[nameof(LogikalComponent.Code)]);
  599. _component.Description = CheckValue<string>(row[nameof(LogikalComponent.Description)]);
  600. _component.Quantity = CheckValue<double>(row[nameof(LogikalComponent.Quantity)]);
  601. _component.Cost = CheckValue<double>(row[nameof(LogikalComponent.Cost)]);
  602. _component.PackSize = CheckValue<double>(row[nameof(LogikalComponent.PackSize)]);
  603. components.Add(_component);
  604. }
  605. elevation.Components = components;
  606. }
  607. }
  608. catch (Exception e)
  609. {
  610. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  611. }
  612. }
  613. // Get Glass
  614. using (var _data = new SQLiteCommand(_connection))
  615. {
  616. _data.CommandText = Settings.GlassSQL.Replace('\n', ' ');
  617. try
  618. {
  619. using (var _reader = _data.ExecuteReader())
  620. {
  621. DataTable _dt = new DataTable();
  622. _dt.Load(_reader);
  623. List<LogikalGlass> glass = new List<LogikalGlass>();
  624. foreach (DataRow row in _dt.Rows)
  625. {
  626. var _glassitem = new LogikalGlass();
  627. _glassitem.Code = CheckValue<string>(row[nameof(LogikalGlass.Code)]);
  628. _glassitem.Description = CheckValue<string>(row[nameof(LogikalGlass.Description)]);
  629. _glassitem.Quantity = CheckValue<Int64>(row[nameof(LogikalGlass.Quantity)]);
  630. _glassitem.Cost = CheckValue<double>(row[nameof(LogikalGlass.Cost)]);
  631. _glassitem.Height = CheckValue<double>(row[nameof(LogikalGlass.Height)]) *
  632. GetScale(Settings.GlassMeasurement);
  633. _glassitem.Width = CheckValue<double>(row[nameof(LogikalGlass.Width)]) *
  634. GetScale(Settings.GlassMeasurement);
  635. _glassitem.Treatment = CheckValue<string>(row[nameof(LogikalGlass.Treatment)]);
  636. _glassitem.Location = CheckValue<string>(row[nameof(LogikalGlass.Location)]);
  637. glass.Add(_glassitem);
  638. }
  639. elevation.Glass = glass;
  640. }
  641. }
  642. catch (Exception e)
  643. {
  644. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  645. }
  646. }
  647. // Get Labour
  648. using (var _data = new SQLiteCommand(_connection))
  649. {
  650. _data.CommandText = Settings.LabourSQL.Replace('\n', ' ');
  651. try
  652. {
  653. using (var _reader = _data.ExecuteReader())
  654. {
  655. DataTable _dt = new DataTable();
  656. _dt.Load(_reader);
  657. List<LogikalLabour> labour = new List<LogikalLabour>();
  658. foreach (DataRow row in _dt.Rows)
  659. {
  660. var _labouritem = new LogikalLabour();
  661. _labouritem.Code = CheckValue<string>(row[nameof(LogikalLabour.Code)]);
  662. _labouritem.Description = CheckValue<string>(row[nameof(LogikalLabour.Description)]);
  663. _labouritem.Quantity = CheckValue<double>(row[nameof(LogikalLabour.Quantity)]);
  664. _labouritem.Cost = CheckValue<double>(row[nameof(LogikalLabour.Cost)]);
  665. labour.Add(_labouritem);
  666. }
  667. elevation.Labour = labour;
  668. }
  669. }
  670. catch (Exception e)
  671. {
  672. throw new Exception($"Error: {e.Message}\nQuery: {_data.CommandText}\nTrace: {e.StackTrace}");
  673. }
  674. }
  675. if (includeexcel)
  676. {
  677. List<string> _tables = new List<string>();
  678. using (var _master = new SQLiteCommand(_connection))
  679. {
  680. _master.CommandText = "select * from sqlite_master where type='table'";
  681. using (var _reader = _master.ExecuteReader())
  682. {
  683. if (_reader.HasRows)
  684. {
  685. while (_reader.Read())
  686. _tables.Add(_reader.GetString(1));
  687. }
  688. }
  689. }
  690. DataSet _ds = new DataSet();
  691. foreach (var _table in _tables)
  692. {
  693. using (var _data = new SQLiteCommand(_connection))
  694. {
  695. _data.CommandText = $"select * from {_table}";
  696. using (var _reader = _data.ExecuteReader())
  697. {
  698. DataTable _dt = new DataTable(_table);
  699. _ds.Tables.Add(_dt);
  700. _dt.Load(_reader);
  701. }
  702. }
  703. }
  704. var excelApp = OfficeOpenXML.GetInstance();
  705. using (var _buffer = excelApp.GetExcelStream(_ds, false))
  706. elevation.ExcelData = _buffer.GetBuffer();
  707. _connection.Close();
  708. File.Delete(file);
  709. }
  710. }
  711. File.Delete(file);
  712. }
  713. }
  714. }