Client.cs 21 KB

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