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, CoreRange? range = 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>(ICollection<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, CoreRange? range = null)
  96. where TEntity : Entity, IRemotable, IPersistent, new()
  97. {
  98. return new Client<TEntity>().Query(filter, columns, orderby, range);
  99. }
  100. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, CoreRange? range, Action<CoreTable?, Exception?> callback)
  101. where TEntity : Entity, IRemotable, IPersistent, new()
  102. {
  103. new Client<TEntity>().Query(filter, columns, orderby, range, callback);
  104. }
  105. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, Action<CoreTable?, Exception?> callback)
  106. where TEntity : Entity, IRemotable, IPersistent, new()
  107. {
  108. new Client<TEntity>().Query(filter, columns, orderby, null, callback);
  109. }
  110. public static void Save<TEntity>(TEntity entity, string auditNote)
  111. where TEntity : Entity, IRemotable, IPersistent, new()
  112. {
  113. new Client<TEntity>().Save(entity, auditNote);
  114. }
  115. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  116. where TEntity : Entity, IRemotable, IPersistent, new()
  117. {
  118. new Client<TEntity>().Save(entities, auditNote);
  119. }
  120. public static void Save<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  121. where TEntity : Entity, IRemotable, IPersistent, new()
  122. {
  123. new Client<TEntity>().Save(entity, auditNote, callback);
  124. }
  125. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote, Action<IEnumerable<TEntity>, Exception?> callback)
  126. where TEntity : Entity, IRemotable, IPersistent, new()
  127. {
  128. new Client<TEntity>().Save(entities, auditNote, callback);
  129. }
  130. public static void Delete<TEntity>(TEntity entity, string auditNote)
  131. where TEntity : Entity, IRemotable, IPersistent, new()
  132. {
  133. new Client<TEntity>().Delete(entity, auditNote);
  134. }
  135. public static void Delete<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  136. where TEntity : Entity, IRemotable, IPersistent, new()
  137. {
  138. new Client<TEntity>().Delete(entity, auditNote, callback);
  139. }
  140. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  141. where TEntity : Entity, IRemotable, IPersistent, new()
  142. {
  143. new Client<TEntity>().Delete(entities, auditNote);
  144. }
  145. public static void QueryMultiple(
  146. Action<Dictionary<string, CoreTable>?, Exception?> callback,
  147. Dictionary<string, IQueryDef> queries)
  148. {
  149. try
  150. {
  151. using var timer = new Profiler(false);
  152. CheckClient().QueryMultiple((result, e) =>
  153. {
  154. timer.Dispose(result != null ? result.Sum(x => x.Value.Rows.Count) : -1);
  155. callback?.Invoke(result, e);
  156. }, queries);
  157. }
  158. catch (RequestException e)
  159. {
  160. ClientFactory.RaiseRequestError(e);
  161. throw;
  162. }
  163. }
  164. public static QueryMultipleResults QueryMultiple(params IKeyedQueryDef[] queries) =>
  165. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  166. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, params IKeyedQueryDef[] queries) =>
  167. QueryMultiple((results, e) =>
  168. {
  169. if (results != null)
  170. {
  171. callback?.Invoke(new QueryMultipleResults(results), e);
  172. }
  173. else
  174. {
  175. callback?.Invoke(null, e);
  176. }
  177. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  178. public static QueryMultipleResults QueryMultiple(IEnumerable<IKeyedQueryDef> queries) =>
  179. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  180. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, IEnumerable<IKeyedQueryDef> queries) =>
  181. QueryMultiple((results, e) =>
  182. {
  183. if(results != null)
  184. {
  185. callback?.Invoke(new QueryMultipleResults(results), e);
  186. }
  187. else
  188. {
  189. callback?.Invoke(null, e);
  190. }
  191. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  192. public static IValidationData Validate(Guid session)
  193. {
  194. try
  195. {
  196. using (new Profiler(true))
  197. return CheckClient().Validate(session);
  198. }
  199. catch (RequestException e)
  200. {
  201. ClientFactory.RaiseRequestError(e);
  202. throw;
  203. }
  204. }
  205. public static IValidationData Validate(string pin, Guid session = default)
  206. {
  207. try
  208. {
  209. using (new Profiler(true))
  210. return CheckClient().Validate(pin, session);
  211. }
  212. catch (RequestException e)
  213. {
  214. ClientFactory.RaiseRequestError(e);
  215. throw;
  216. }
  217. }
  218. public static IValidationData Validate(string userid, string password, Guid session = default)
  219. {
  220. try
  221. {
  222. using (new Profiler(true))
  223. return CheckClient().Validate(userid, password, session);
  224. }
  225. catch (RequestException e)
  226. {
  227. ClientFactory.RaiseRequestError(e);
  228. throw;
  229. }
  230. }
  231. public static bool Check2FA(string code, Guid? session = null)
  232. {
  233. try
  234. {
  235. using (new Profiler(true))
  236. return CheckClient().Check2FA(code, session);
  237. }
  238. catch (RequestException e)
  239. {
  240. ClientFactory.RaiseRequestError(e);
  241. throw;
  242. }
  243. }
  244. public static bool Ping()
  245. {
  246. try
  247. {
  248. return CheckClient().Ping();
  249. }
  250. catch (RequestException e)
  251. {
  252. ClientFactory.RaiseRequestError(e);
  253. throw;
  254. }
  255. }
  256. public static DatabaseInfo? Info()
  257. {
  258. try
  259. {
  260. using (new Profiler(true))
  261. return CheckClient().Info();
  262. }
  263. catch (RequestException e)
  264. {
  265. ClientFactory.RaiseRequestError(e);
  266. throw;
  267. }
  268. }
  269. public static string Version()
  270. {
  271. try
  272. {
  273. using (new Profiler(true))
  274. return CheckClient().Version();
  275. }
  276. catch (RequestException e)
  277. {
  278. ClientFactory.RaiseRequestError(e);
  279. throw;
  280. }
  281. }
  282. public static string ReleaseNotes()
  283. {
  284. try
  285. {
  286. using (new Profiler(true))
  287. return CheckClient().ReleaseNotes();
  288. }
  289. catch (RequestException e)
  290. {
  291. ClientFactory.RaiseRequestError(e);
  292. throw;
  293. }
  294. }
  295. public static byte[]? Installer()
  296. {
  297. try
  298. {
  299. using (new Profiler(true))
  300. return CheckClient().Installer();
  301. }
  302. catch (RequestException e)
  303. {
  304. ClientFactory.RaiseRequestError(e);
  305. throw;
  306. }
  307. }
  308. public static Client Create(Type TEntity) =>
  309. (Activator.CreateInstance(typeof(Client<>).MakeGenericType(TEntity)) as Client)!;
  310. }
  311. public class Client<TEntity> : Client, IDisposable where TEntity : Entity, IPersistent, IRemotable, new()
  312. {
  313. private IClient<TEntity> _client;
  314. public Client()
  315. {
  316. _client = ClientFactory.CreateClient<TEntity>();
  317. }
  318. public void Dispose()
  319. {
  320. }
  321. private void CheckSupported()
  322. {
  323. if (!ClientFactory.IsSupported<TEntity>())
  324. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  325. }
  326. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  327. {
  328. try
  329. {
  330. using var timer = new Profiler<TEntity>(false);
  331. CheckSupported();
  332. var result = _client.Query(filter, columns, orderby, range);
  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 = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null)
  343. {
  344. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>, range);
  345. }
  346. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, CoreRange? range, Action<CoreTable?, Exception?>? callback)
  347. {
  348. try
  349. {
  350. var timer = new Profiler<TEntity>(false);
  351. CheckSupported();
  352. _client.Query(filter, columns, sort, range, (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, CoreRange? range = null)
  365. {
  366. try
  367. {
  368. using (var timer = new Profiler<TEntity>(false))
  369. {
  370. CheckSupported();
  371. var result = _client.Load(filter, sort, range);
  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, CoreRange? range, Action<TEntity[]?, Exception?>? callback)
  385. {
  386. try
  387. {
  388. var timer = new Profiler<TEntity>(false);
  389. CheckSupported();
  390. _client.Load(filter, sort, range,(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. }