Client.cs 21 KB

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