Client.cs 21 KB

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