Client.cs 21 KB

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