Client.cs 23 KB

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