Client.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Timers;
  7. using InABox.Core;
  8. namespace InABox.Clients
  9. {
  10. public enum SerializerProtocol
  11. {
  12. Rest,
  13. RPC
  14. }
  15. public class QueryResult
  16. {
  17. private CoreTable? Table;
  18. private Exception? Exception;
  19. public QueryResult(CoreTable table)
  20. {
  21. Table = table;
  22. }
  23. public QueryResult(Exception exception)
  24. {
  25. Exception = exception;
  26. }
  27. public bool GetResult([NotNullWhen(true)] out CoreTable? table, [NotNullWhen(false)] out Exception? exception)
  28. {
  29. table = Table;
  30. exception = Exception;
  31. return table != null;
  32. }
  33. public void DoWith(Action<CoreTable> dataAction, Action<Exception> exceptionAction)
  34. {
  35. if(Table != null)
  36. {
  37. dataAction(Table);
  38. }
  39. else
  40. {
  41. exceptionAction(Exception!);
  42. }
  43. }
  44. public TResult DoWith<TResult>(Func<CoreTable, TResult> dataAction, Func<Exception, TResult> exceptionAction)
  45. {
  46. if(Table != null)
  47. {
  48. return dataAction(Table);
  49. }
  50. else
  51. {
  52. return exceptionAction(Exception!);
  53. }
  54. }
  55. }
  56. public class QueryMultipleResults
  57. {
  58. private readonly Dictionary<string, CoreTable> Results;
  59. internal QueryMultipleResults(Dictionary<string, CoreTable> results)
  60. {
  61. Results = results;
  62. }
  63. public CoreTable this[string name] => Results[name];
  64. public CoreTable Get<T>() => Results[typeof(T).Name];
  65. /// <summary>
  66. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToObjects{T}"/> on the table.
  67. /// </summary>
  68. /// <typeparam name="T"></typeparam>
  69. /// <returns></returns>
  70. public IEnumerable<T> GetObjects<T>()
  71. where T: BaseObject, new()
  72. => Results[typeof(T).Name].ToObjects<T>();
  73. public CoreTable Get(string name) => Results[name];
  74. public CoreTable GetOrDefault(string name) => Results.GetValueOrDefault(name);
  75. }
  76. public abstract class Client
  77. {
  78. public abstract CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null);
  79. public abstract void Save(Entity entity, string auditNote);
  80. public abstract void Save(IEnumerable<Entity> entity, string auditNote);
  81. private static IClient CheckClient()
  82. {
  83. using (new Profiler(true))
  84. return ClientFactory.CreateClient<User>();
  85. }
  86. public static Dictionary<string, CoreTable> QueryMultiple(Dictionary<string, IQueryDef> queries)
  87. {
  88. try
  89. {
  90. using var timer = new Profiler(false);
  91. var result = CheckClient().QueryMultiple(queries);
  92. timer.Log(result.Sum(x => x.Value.Rows.Count));
  93. return result;
  94. }
  95. catch (RequestException e)
  96. {
  97. ClientFactory.RaiseRequestError(e);
  98. throw;
  99. }
  100. }
  101. private static IClient<TEntity> CheckClient<TEntity>() where TEntity : Entity, IRemotable, IPersistent, new()
  102. {
  103. return ClientFactory.CreateClient<TEntity>();
  104. }
  105. public static void EnsureColumns<TEntity>(TEntity entity, Columns<TEntity> columns)
  106. where TEntity : Entity, IRemotable, IPersistent, new()
  107. {
  108. var newColumns = new Columns<TEntity>();
  109. foreach(var column in columns)
  110. {
  111. if (!entity.HasColumn(column.Property))
  112. {
  113. newColumns.Add(column);
  114. }
  115. }
  116. if (newColumns.Any())
  117. {
  118. var row = Query(new Filter<TEntity>(x => x.ID).IsEqualTo(entity.ID), newColumns).Rows.FirstOrDefault();
  119. row?.FillObject(entity);
  120. }
  121. }
  122. public static void EnsureColumns<TEntity>(IList<TEntity> entities, Columns<TEntity> columns)
  123. where TEntity : Entity, IRemotable, IPersistent, new()
  124. {
  125. var newColumns = new Columns<TEntity>();
  126. foreach(var entity in entities)
  127. {
  128. foreach(var column in columns)
  129. {
  130. if (!entity.HasColumn(column.Property))
  131. {
  132. newColumns.Add(column);
  133. }
  134. }
  135. }
  136. if (newColumns.Any())
  137. {
  138. newColumns.Add(x => x.ID);
  139. var table = Query(new Filter<TEntity>(x => x.ID).InList(entities.Select(x => x.ID).ToArray()), newColumns);
  140. foreach(var row in table.Rows)
  141. {
  142. var id = row.Get<TEntity, Guid>(x => x.ID);
  143. var entity = entities.FirstOrDefault(x => x.ID == id);
  144. if(entity is null)
  145. {
  146. // Shouldn't happen, but just in case.
  147. continue;
  148. }
  149. row?.FillObject(entity);
  150. }
  151. }
  152. }
  153. public static CoreTable Query<TEntity>(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null)
  154. where TEntity : Entity, IRemotable, IPersistent, new()
  155. {
  156. return new Client<TEntity>().Query(filter, columns, orderby);
  157. }
  158. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, Action<CoreTable?, Exception?> callback)
  159. where TEntity : Entity, IRemotable, IPersistent, new()
  160. {
  161. new Client<TEntity>().Query(filter, columns, orderby, callback);
  162. }
  163. public static void Save<TEntity>(TEntity entity, string auditNote)
  164. where TEntity : Entity, IRemotable, IPersistent, new()
  165. {
  166. new Client<TEntity>().Save(entity, auditNote);
  167. }
  168. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  169. where TEntity : Entity, IRemotable, IPersistent, new()
  170. {
  171. new Client<TEntity>().Save(entities, auditNote);
  172. }
  173. public static void Save<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  174. where TEntity : Entity, IRemotable, IPersistent, new()
  175. {
  176. new Client<TEntity>().Save(entity, auditNote, callback);
  177. }
  178. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote, Action<IEnumerable<TEntity>, Exception?> callback)
  179. where TEntity : Entity, IRemotable, IPersistent, new()
  180. {
  181. new Client<TEntity>().Save(entities, auditNote, callback);
  182. }
  183. public static void Delete<TEntity>(TEntity entity, string auditNote)
  184. where TEntity : Entity, IRemotable, IPersistent, new()
  185. {
  186. new Client<TEntity>().Delete(entity, auditNote);
  187. }
  188. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  189. where TEntity : Entity, IRemotable, IPersistent, new()
  190. {
  191. new Client<TEntity>().Delete(entities, auditNote);
  192. }
  193. public static void QueryMultiple(
  194. Action<Dictionary<string, CoreTable>?, Exception?> callback,
  195. Dictionary<string, IQueryDef> queries)
  196. {
  197. try
  198. {
  199. using var timer = new Profiler(false);
  200. CheckClient().QueryMultiple((result, e) =>
  201. {
  202. timer.Dispose(result != null ? result.Sum(x => x.Value.Rows.Count) : -1);
  203. callback?.Invoke(result, e);
  204. }, queries);
  205. }
  206. catch (RequestException e)
  207. {
  208. ClientFactory.RaiseRequestError(e);
  209. throw;
  210. }
  211. }
  212. public static QueryMultipleResults QueryMultiple(params IKeyedQueryDef[] queries) =>
  213. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  214. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, params IKeyedQueryDef[] queries) =>
  215. QueryMultiple((results, e) =>
  216. {
  217. if (results != null)
  218. {
  219. callback?.Invoke(new QueryMultipleResults(results), e);
  220. }
  221. else
  222. {
  223. callback?.Invoke(null, e);
  224. }
  225. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  226. public static QueryMultipleResults QueryMultiple(IEnumerable<IKeyedQueryDef> queries) =>
  227. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  228. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, IEnumerable<IKeyedQueryDef> queries) =>
  229. QueryMultiple((results, e) =>
  230. {
  231. if(results != null)
  232. {
  233. callback?.Invoke(new QueryMultipleResults(results), e);
  234. }
  235. else
  236. {
  237. callback?.Invoke(null, e);
  238. }
  239. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  240. public static IValidationData Validate(Guid session)
  241. {
  242. try
  243. {
  244. using (new Profiler(true))
  245. return CheckClient().Validate(session);
  246. }
  247. catch (RequestException e)
  248. {
  249. ClientFactory.RaiseRequestError(e);
  250. throw;
  251. }
  252. }
  253. public static IValidationData Validate(string pin, Guid session = default)
  254. {
  255. try
  256. {
  257. using (new Profiler(true))
  258. return CheckClient().Validate(pin, session);
  259. }
  260. catch (RequestException e)
  261. {
  262. ClientFactory.RaiseRequestError(e);
  263. throw;
  264. }
  265. }
  266. public static IValidationData Validate(string userid, string password, Guid session = default)
  267. {
  268. try
  269. {
  270. using (new Profiler(true))
  271. return CheckClient().Validate(userid, password, session);
  272. }
  273. catch (RequestException e)
  274. {
  275. ClientFactory.RaiseRequestError(e);
  276. throw;
  277. }
  278. }
  279. public static bool Check2FA(string code, Guid? session = null)
  280. {
  281. try
  282. {
  283. using (new Profiler(true))
  284. return CheckClient().Check2FA(code, session);
  285. }
  286. catch (RequestException e)
  287. {
  288. ClientFactory.RaiseRequestError(e);
  289. throw;
  290. }
  291. }
  292. public static bool Ping()
  293. {
  294. try
  295. {
  296. using (new Profiler(true))
  297. return CheckClient().Ping();
  298. }
  299. catch (RequestException e)
  300. {
  301. ClientFactory.RaiseRequestError(e);
  302. throw;
  303. }
  304. }
  305. public static DatabaseInfo Info()
  306. {
  307. try
  308. {
  309. using (new Profiler(true))
  310. return CheckClient().Info();
  311. }
  312. catch (RequestException e)
  313. {
  314. ClientFactory.RaiseRequestError(e);
  315. throw;
  316. }
  317. }
  318. public static string Version()
  319. {
  320. try
  321. {
  322. using (new Profiler(true))
  323. return CheckClient().Version();
  324. }
  325. catch (RequestException e)
  326. {
  327. ClientFactory.RaiseRequestError(e);
  328. throw;
  329. }
  330. }
  331. public static string ReleaseNotes()
  332. {
  333. try
  334. {
  335. using (new Profiler(true))
  336. return CheckClient().ReleaseNotes();
  337. }
  338. catch (RequestException e)
  339. {
  340. ClientFactory.RaiseRequestError(e);
  341. throw;
  342. }
  343. }
  344. public static byte[]? Installer()
  345. {
  346. try
  347. {
  348. using (new Profiler(true))
  349. return CheckClient().Installer();
  350. }
  351. catch (RequestException e)
  352. {
  353. ClientFactory.RaiseRequestError(e);
  354. throw;
  355. }
  356. }
  357. public static Client Create(Type TEntity) =>
  358. (Activator.CreateInstance(typeof(Client<>).MakeGenericType(TEntity)) as Client)!;
  359. }
  360. public class Client<TEntity> : Client, IDisposable where TEntity : Entity, IPersistent, IRemotable, new()
  361. {
  362. private IClient<TEntity> _client;
  363. public Client()
  364. {
  365. _client = ClientFactory.CreateClient<TEntity>();
  366. }
  367. public void Dispose()
  368. {
  369. }
  370. private void CheckSupported()
  371. {
  372. if (!ClientFactory.IsSupported<TEntity>())
  373. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  374. }
  375. private string FilterToString(Filter<TEntity> filter)
  376. {
  377. return filter != null ? filter.AsOData() : "";
  378. }
  379. private string OrderToString(SortOrder<TEntity> order)
  380. {
  381. return order != null ? order.AsOData() : "";
  382. }
  383. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null)
  384. {
  385. try
  386. {
  387. using var timer = new Profiler<TEntity>(false);
  388. CheckSupported();
  389. var result = _client.Query(filter, columns, orderby);
  390. timer.Log(result.Rows.Count);
  391. return result;
  392. }
  393. catch(RequestException e)
  394. {
  395. ClientFactory.RaiseRequestError(e);
  396. throw;
  397. }
  398. }
  399. public override CoreTable Query(IFilter? filter, IColumns? columns, ISortOrder? sortOrder)
  400. {
  401. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>);
  402. }
  403. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, Action<CoreTable?, Exception?> callback)
  404. {
  405. try
  406. {
  407. var timer = new Profiler<TEntity>(false);
  408. CheckSupported();
  409. _client.Query(filter, columns, sort, (c, e) =>
  410. {
  411. timer.Log(c != null ? c.Rows.Count : -1);
  412. callback?.Invoke(c, e);
  413. });
  414. }
  415. catch (RequestException e)
  416. {
  417. ClientFactory.RaiseRequestError(e);
  418. throw;
  419. }
  420. }
  421. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null)
  422. {
  423. try
  424. {
  425. using (var timer = new Profiler<TEntity>(false))
  426. {
  427. CheckSupported();
  428. var result = _client.Load(filter, sort);
  429. foreach (var entity in result)
  430. entity.CommitChanges();
  431. timer.Log(result.Length);
  432. return result;
  433. }
  434. }
  435. catch (RequestException e)
  436. {
  437. ClientFactory.RaiseRequestError(e);
  438. throw;
  439. }
  440. }
  441. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, Action<TEntity[]?, Exception?> callback)
  442. {
  443. try
  444. {
  445. var timer = new Profiler<TEntity>(false);
  446. CheckSupported();
  447. _client.Load(filter, sort, (i, e) =>
  448. {
  449. timer.Dispose(i != null ? i.Length : -1);
  450. callback?.Invoke(i, e);
  451. });
  452. }
  453. catch (RequestException e)
  454. {
  455. ClientFactory.RaiseRequestError(e);
  456. throw;
  457. }
  458. }
  459. public override void Save(Entity entity, string auditNote)
  460. {
  461. try
  462. {
  463. Save((entity as TEntity)!, auditNote);
  464. }
  465. catch (RequestException e)
  466. {
  467. ClientFactory.RaiseRequestError(e);
  468. throw;
  469. }
  470. }
  471. public override void Save(IEnumerable<Entity> entities, string auditNote)
  472. {
  473. try
  474. {
  475. Save(entities.Cast<TEntity>(), auditNote);
  476. }
  477. catch (RequestException e)
  478. {
  479. ClientFactory.RaiseRequestError(e);
  480. throw;
  481. }
  482. }
  483. public void Save(TEntity entity, string auditnote)
  484. {
  485. try
  486. {
  487. using (new Profiler<TEntity>(true))
  488. {
  489. CheckSupported();
  490. entity.LastUpdate = DateTime.Now;
  491. entity.LastUpdateBy = ClientFactory.UserID;
  492. _client.Save(entity, auditnote);
  493. entity.CommitChanges();
  494. }
  495. }
  496. catch (RequestException e)
  497. {
  498. ClientFactory.RaiseRequestError(e);
  499. throw;
  500. }
  501. }
  502. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  503. {
  504. try
  505. {
  506. var timer = new Profiler<TEntity>(false);
  507. CheckSupported();
  508. _client.Save(entity, auditnote, (i, c) =>
  509. {
  510. timer.Dispose();
  511. callback?.Invoke(i, c);
  512. });
  513. }
  514. catch (RequestException e)
  515. {
  516. ClientFactory.RaiseRequestError(e);
  517. throw;
  518. }
  519. }
  520. public void Save(IEnumerable<TEntity> entities, string auditnote)
  521. {
  522. try
  523. {
  524. using var timer = new Profiler<TEntity>(false);
  525. CheckSupported();
  526. var items = entities.AsArray();
  527. if (items.Any())
  528. _client.Save(items, auditnote);
  529. timer.Log(items.Length);
  530. }
  531. catch (RequestException e)
  532. {
  533. ClientFactory.RaiseRequestError(e);
  534. throw;
  535. }
  536. }
  537. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  538. {
  539. try
  540. {
  541. var timer = new Profiler<TEntity>(false);
  542. CheckSupported();
  543. var items = entities.AsArray();
  544. if (items.Any())
  545. {
  546. _client.Save(items, auditnote, (i, e) =>
  547. {
  548. timer.Dispose(i.Count());
  549. callback?.Invoke(i, e);
  550. });
  551. }
  552. else
  553. {
  554. timer.Dispose(0);
  555. callback?.Invoke(items, null);
  556. }
  557. }
  558. catch (RequestException e)
  559. {
  560. ClientFactory.RaiseRequestError(e);
  561. throw;
  562. }
  563. }
  564. public void Delete(TEntity entity, string auditnote)
  565. {
  566. try
  567. {
  568. using (new Profiler<TEntity>(true))
  569. {
  570. CheckSupported();
  571. _client.Delete(entity, auditnote);
  572. }
  573. }
  574. catch (RequestException e)
  575. {
  576. ClientFactory.RaiseRequestError(e);
  577. throw;
  578. }
  579. }
  580. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  581. {
  582. try
  583. {
  584. var timer = new Profiler<TEntity>(true);
  585. CheckSupported();
  586. _client.Delete(entity, auditnote, (i, e) =>
  587. {
  588. timer.Dispose();
  589. callback?.Invoke(i, e);
  590. });
  591. }
  592. catch (RequestException e)
  593. {
  594. ClientFactory.RaiseRequestError(e);
  595. throw;
  596. }
  597. }
  598. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  599. {
  600. try
  601. {
  602. using var timer = new Profiler<TEntity>(false);
  603. CheckSupported();
  604. var items = entities.AsArray();
  605. _client.Delete(items, auditnote);
  606. timer.Log(items.Length);
  607. }
  608. catch (RequestException e)
  609. {
  610. ClientFactory.RaiseRequestError(e);
  611. throw;
  612. }
  613. }
  614. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  615. {
  616. try
  617. {
  618. var timer = new Profiler<TEntity>(false);
  619. CheckSupported();
  620. var items = entities.AsArray();
  621. _client.Delete(items, auditnote, (i, e) =>
  622. {
  623. timer.Dispose(i.Count);
  624. callback?.Invoke(i, e);
  625. });
  626. }
  627. catch (RequestException e)
  628. {
  629. ClientFactory.RaiseRequestError(e);
  630. throw;
  631. }
  632. }
  633. public IEnumerable<string> SupportedTypes()
  634. {
  635. try
  636. {
  637. using (new Profiler(true))
  638. return _client.SupportedTypes();
  639. }
  640. catch (RequestException e)
  641. {
  642. ClientFactory.RaiseRequestError(e);
  643. throw;
  644. }
  645. }
  646. public new DatabaseInfo Info()
  647. {
  648. try
  649. {
  650. using (new Profiler(true))
  651. return _client.Info();
  652. }
  653. catch (RequestException e)
  654. {
  655. ClientFactory.RaiseRequestError(e);
  656. throw;
  657. }
  658. }
  659. }
  660. }