Client.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  131. where TEntity : Entity, IRemotable, IPersistent, new()
  132. {
  133. new Client<TEntity>().Delete(entity, auditNote, callback);
  134. }
  135. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  136. where TEntity : Entity, IRemotable, IPersistent, new()
  137. {
  138. new Client<TEntity>().Delete(entities, auditNote);
  139. }
  140. public static void QueryMultiple(
  141. Action<Dictionary<string, CoreTable>?, Exception?> callback,
  142. Dictionary<string, IQueryDef> queries)
  143. {
  144. try
  145. {
  146. using var timer = new Profiler(false);
  147. CheckClient().QueryMultiple((result, e) =>
  148. {
  149. timer.Dispose(result != null ? result.Sum(x => x.Value.Rows.Count) : -1);
  150. callback?.Invoke(result, e);
  151. }, queries);
  152. }
  153. catch (RequestException e)
  154. {
  155. ClientFactory.RaiseRequestError(e);
  156. throw;
  157. }
  158. }
  159. public static QueryMultipleResults QueryMultiple(params IKeyedQueryDef[] queries) =>
  160. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  161. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, params IKeyedQueryDef[] queries) =>
  162. QueryMultiple((results, e) =>
  163. {
  164. if (results != null)
  165. {
  166. callback?.Invoke(new QueryMultipleResults(results), e);
  167. }
  168. else
  169. {
  170. callback?.Invoke(null, e);
  171. }
  172. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  173. public static QueryMultipleResults QueryMultiple(IEnumerable<IKeyedQueryDef> queries) =>
  174. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  175. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, IEnumerable<IKeyedQueryDef> queries) =>
  176. QueryMultiple((results, e) =>
  177. {
  178. if(results != null)
  179. {
  180. callback?.Invoke(new QueryMultipleResults(results), e);
  181. }
  182. else
  183. {
  184. callback?.Invoke(null, e);
  185. }
  186. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  187. public static IValidationData Validate(Guid session)
  188. {
  189. try
  190. {
  191. using (new Profiler(true))
  192. return CheckClient().Validate(session);
  193. }
  194. catch (RequestException e)
  195. {
  196. ClientFactory.RaiseRequestError(e);
  197. throw;
  198. }
  199. }
  200. public static IValidationData Validate(string pin, Guid session = default)
  201. {
  202. try
  203. {
  204. using (new Profiler(true))
  205. return CheckClient().Validate(pin, session);
  206. }
  207. catch (RequestException e)
  208. {
  209. ClientFactory.RaiseRequestError(e);
  210. throw;
  211. }
  212. }
  213. public static IValidationData Validate(string userid, string password, Guid session = default)
  214. {
  215. try
  216. {
  217. using (new Profiler(true))
  218. return CheckClient().Validate(userid, password, session);
  219. }
  220. catch (RequestException e)
  221. {
  222. ClientFactory.RaiseRequestError(e);
  223. throw;
  224. }
  225. }
  226. public static bool Check2FA(string code, Guid? session = null)
  227. {
  228. try
  229. {
  230. using (new Profiler(true))
  231. return CheckClient().Check2FA(code, session);
  232. }
  233. catch (RequestException e)
  234. {
  235. ClientFactory.RaiseRequestError(e);
  236. throw;
  237. }
  238. }
  239. public static bool Ping()
  240. {
  241. try
  242. {
  243. return CheckClient().Ping();
  244. }
  245. catch (RequestException e)
  246. {
  247. ClientFactory.RaiseRequestError(e);
  248. throw;
  249. }
  250. }
  251. public static DatabaseInfo Info()
  252. {
  253. try
  254. {
  255. using (new Profiler(true))
  256. return CheckClient().Info();
  257. }
  258. catch (RequestException e)
  259. {
  260. ClientFactory.RaiseRequestError(e);
  261. throw;
  262. }
  263. }
  264. public static string Version()
  265. {
  266. try
  267. {
  268. using (new Profiler(true))
  269. return CheckClient().Version();
  270. }
  271. catch (RequestException e)
  272. {
  273. ClientFactory.RaiseRequestError(e);
  274. throw;
  275. }
  276. }
  277. public static string ReleaseNotes()
  278. {
  279. try
  280. {
  281. using (new Profiler(true))
  282. return CheckClient().ReleaseNotes();
  283. }
  284. catch (RequestException e)
  285. {
  286. ClientFactory.RaiseRequestError(e);
  287. throw;
  288. }
  289. }
  290. public static byte[]? Installer()
  291. {
  292. try
  293. {
  294. using (new Profiler(true))
  295. return CheckClient().Installer();
  296. }
  297. catch (RequestException e)
  298. {
  299. ClientFactory.RaiseRequestError(e);
  300. throw;
  301. }
  302. }
  303. public static Client Create(Type TEntity) =>
  304. (Activator.CreateInstance(typeof(Client<>).MakeGenericType(TEntity)) as Client)!;
  305. }
  306. public class Client<TEntity> : Client, IDisposable where TEntity : Entity, IPersistent, IRemotable, new()
  307. {
  308. private IClient<TEntity> _client;
  309. public Client()
  310. {
  311. _client = ClientFactory.CreateClient<TEntity>();
  312. }
  313. public void Dispose()
  314. {
  315. }
  316. private void CheckSupported()
  317. {
  318. if (!ClientFactory.IsSupported<TEntity>())
  319. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  320. }
  321. private string FilterToString(Filter<TEntity> filter)
  322. {
  323. return filter != null ? filter.AsOData() : "";
  324. }
  325. private string OrderToString(SortOrder<TEntity> order)
  326. {
  327. return order != null ? order.AsOData() : "";
  328. }
  329. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null)
  330. {
  331. try
  332. {
  333. using var timer = new Profiler<TEntity>(false);
  334. CheckSupported();
  335. var result = _client.Query(filter, columns, orderby);
  336. timer.Log(result.Rows.Count);
  337. return result;
  338. }
  339. catch(RequestException e)
  340. {
  341. ClientFactory.RaiseRequestError(e);
  342. throw;
  343. }
  344. }
  345. public override CoreTable Query(IFilter? filter, IColumns? columns, ISortOrder? sortOrder)
  346. {
  347. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>);
  348. }
  349. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, Action<CoreTable?, Exception?> callback)
  350. {
  351. try
  352. {
  353. var timer = new Profiler<TEntity>(false);
  354. CheckSupported();
  355. _client.Query(filter, columns, sort, (c, e) =>
  356. {
  357. timer.Log(c != null ? c.Rows.Count : -1);
  358. callback?.Invoke(c, e);
  359. });
  360. }
  361. catch (RequestException e)
  362. {
  363. ClientFactory.RaiseRequestError(e);
  364. throw;
  365. }
  366. }
  367. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null)
  368. {
  369. try
  370. {
  371. using (var timer = new Profiler<TEntity>(false))
  372. {
  373. CheckSupported();
  374. var result = _client.Load(filter, sort);
  375. foreach (var entity in result)
  376. entity.CommitChanges();
  377. timer.Log(result.Length);
  378. return result;
  379. }
  380. }
  381. catch (RequestException e)
  382. {
  383. ClientFactory.RaiseRequestError(e);
  384. throw;
  385. }
  386. }
  387. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, Action<TEntity[]?, Exception?> callback)
  388. {
  389. try
  390. {
  391. var timer = new Profiler<TEntity>(false);
  392. CheckSupported();
  393. _client.Load(filter, sort, (i, e) =>
  394. {
  395. timer.Dispose(i != null ? i.Length : -1);
  396. callback?.Invoke(i, e);
  397. });
  398. }
  399. catch (RequestException e)
  400. {
  401. ClientFactory.RaiseRequestError(e);
  402. throw;
  403. }
  404. }
  405. public override void Save(Entity entity, string auditNote)
  406. {
  407. try
  408. {
  409. Save((entity as TEntity)!, auditNote);
  410. }
  411. catch (RequestException e)
  412. {
  413. ClientFactory.RaiseRequestError(e);
  414. throw;
  415. }
  416. }
  417. public override void Save(IEnumerable<Entity> entities, string auditNote)
  418. {
  419. try
  420. {
  421. Save(entities.Cast<TEntity>(), auditNote);
  422. }
  423. catch (RequestException e)
  424. {
  425. ClientFactory.RaiseRequestError(e);
  426. throw;
  427. }
  428. }
  429. public void Save(TEntity entity, string auditnote)
  430. {
  431. try
  432. {
  433. using (new Profiler<TEntity>(true))
  434. {
  435. CheckSupported();
  436. entity.LastUpdate = DateTime.Now;
  437. entity.LastUpdateBy = ClientFactory.UserID;
  438. _client.Save(entity, auditnote);
  439. entity.CommitChanges();
  440. }
  441. }
  442. catch (RequestException e)
  443. {
  444. ClientFactory.RaiseRequestError(e);
  445. throw;
  446. }
  447. }
  448. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  449. {
  450. try
  451. {
  452. var timer = new Profiler<TEntity>(false);
  453. CheckSupported();
  454. _client.Save(entity, auditnote, (i, c) =>
  455. {
  456. timer.Dispose();
  457. callback?.Invoke(i, c);
  458. });
  459. }
  460. catch (RequestException e)
  461. {
  462. ClientFactory.RaiseRequestError(e);
  463. throw;
  464. }
  465. }
  466. public void Save(IEnumerable<TEntity> entities, string auditnote)
  467. {
  468. try
  469. {
  470. using var timer = new Profiler<TEntity>(false);
  471. CheckSupported();
  472. var items = entities.AsArray();
  473. if (items.Any())
  474. _client.Save(items, auditnote);
  475. timer.Log(items.Length);
  476. }
  477. catch (RequestException e)
  478. {
  479. ClientFactory.RaiseRequestError(e);
  480. throw;
  481. }
  482. }
  483. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  484. {
  485. try
  486. {
  487. var timer = new Profiler<TEntity>(false);
  488. CheckSupported();
  489. var items = entities.AsArray();
  490. if (items.Any())
  491. {
  492. _client.Save(items, auditnote, (i, e) =>
  493. {
  494. timer.Dispose(i.Count());
  495. callback?.Invoke(i, e);
  496. });
  497. }
  498. else
  499. {
  500. timer.Dispose(0);
  501. callback?.Invoke(items, null);
  502. }
  503. }
  504. catch (RequestException e)
  505. {
  506. ClientFactory.RaiseRequestError(e);
  507. throw;
  508. }
  509. }
  510. public void Delete(TEntity entity, string auditnote)
  511. {
  512. try
  513. {
  514. using (new Profiler<TEntity>(true))
  515. {
  516. CheckSupported();
  517. _client.Delete(entity, auditnote);
  518. }
  519. }
  520. catch (RequestException e)
  521. {
  522. ClientFactory.RaiseRequestError(e);
  523. throw;
  524. }
  525. }
  526. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  527. {
  528. try
  529. {
  530. var timer = new Profiler<TEntity>(true);
  531. CheckSupported();
  532. _client.Delete(entity, auditnote, (i, e) =>
  533. {
  534. timer.Dispose();
  535. callback?.Invoke(i, e);
  536. });
  537. }
  538. catch (RequestException e)
  539. {
  540. ClientFactory.RaiseRequestError(e);
  541. throw;
  542. }
  543. }
  544. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  545. {
  546. try
  547. {
  548. using var timer = new Profiler<TEntity>(false);
  549. CheckSupported();
  550. var items = entities.AsArray();
  551. _client.Delete(items, auditnote);
  552. timer.Log(items.Length);
  553. }
  554. catch (RequestException e)
  555. {
  556. ClientFactory.RaiseRequestError(e);
  557. throw;
  558. }
  559. }
  560. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  561. {
  562. try
  563. {
  564. var timer = new Profiler<TEntity>(false);
  565. CheckSupported();
  566. var items = entities.AsArray();
  567. _client.Delete(items, auditnote, (i, e) =>
  568. {
  569. timer.Dispose(i.Count);
  570. callback?.Invoke(i, e);
  571. });
  572. }
  573. catch (RequestException e)
  574. {
  575. ClientFactory.RaiseRequestError(e);
  576. throw;
  577. }
  578. }
  579. public IEnumerable<string> SupportedTypes()
  580. {
  581. try
  582. {
  583. using (new Profiler(true))
  584. return _client.SupportedTypes();
  585. }
  586. catch (RequestException e)
  587. {
  588. ClientFactory.RaiseRequestError(e);
  589. throw;
  590. }
  591. }
  592. public new DatabaseInfo Info()
  593. {
  594. try
  595. {
  596. using (new Profiler(true))
  597. return _client.Info();
  598. }
  599. catch (RequestException e)
  600. {
  601. ClientFactory.RaiseRequestError(e);
  602. throw;
  603. }
  604. }
  605. }
  606. }