Client.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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>(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)
  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. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null)
  322. {
  323. try
  324. {
  325. using var timer = new Profiler<TEntity>(false);
  326. CheckSupported();
  327. var result = _client.Query(filter, columns, orderby);
  328. timer.Log(result.Rows.Count);
  329. return result;
  330. }
  331. catch(RequestException e)
  332. {
  333. ClientFactory.RaiseRequestError(e);
  334. throw;
  335. }
  336. }
  337. public override CoreTable Query(IFilter? filter, IColumns? columns, ISortOrder? sortOrder)
  338. {
  339. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>);
  340. }
  341. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, Action<CoreTable?, Exception?> callback)
  342. {
  343. try
  344. {
  345. var timer = new Profiler<TEntity>(false);
  346. CheckSupported();
  347. _client.Query(filter, columns, sort, (c, e) =>
  348. {
  349. timer.Log(c != null ? c.Rows.Count : -1);
  350. callback?.Invoke(c, e);
  351. });
  352. }
  353. catch (RequestException e)
  354. {
  355. ClientFactory.RaiseRequestError(e);
  356. throw;
  357. }
  358. }
  359. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null)
  360. {
  361. try
  362. {
  363. using (var timer = new Profiler<TEntity>(false))
  364. {
  365. CheckSupported();
  366. var result = _client.Load(filter, sort);
  367. foreach (var entity in result)
  368. entity.CommitChanges();
  369. timer.Log(result.Length);
  370. return result;
  371. }
  372. }
  373. catch (RequestException e)
  374. {
  375. ClientFactory.RaiseRequestError(e);
  376. throw;
  377. }
  378. }
  379. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, Action<TEntity[]?, Exception?> callback)
  380. {
  381. try
  382. {
  383. var timer = new Profiler<TEntity>(false);
  384. CheckSupported();
  385. _client.Load(filter, sort, (i, e) =>
  386. {
  387. timer.Dispose(i != null ? i.Length : -1);
  388. callback?.Invoke(i, e);
  389. });
  390. }
  391. catch (RequestException e)
  392. {
  393. ClientFactory.RaiseRequestError(e);
  394. throw;
  395. }
  396. }
  397. public override void Save(Entity entity, string auditNote)
  398. {
  399. try
  400. {
  401. Save((entity as TEntity)!, auditNote);
  402. }
  403. catch (RequestException e)
  404. {
  405. ClientFactory.RaiseRequestError(e);
  406. throw;
  407. }
  408. }
  409. public override void Save(IEnumerable<Entity> entities, string auditNote)
  410. {
  411. try
  412. {
  413. Save(entities.Cast<TEntity>(), auditNote);
  414. }
  415. catch (RequestException e)
  416. {
  417. ClientFactory.RaiseRequestError(e);
  418. throw;
  419. }
  420. }
  421. public void Save(TEntity entity, string auditnote)
  422. {
  423. try
  424. {
  425. using (new Profiler<TEntity>(true))
  426. {
  427. CheckSupported();
  428. entity.LastUpdate = DateTime.Now;
  429. entity.LastUpdateBy = ClientFactory.UserID;
  430. _client.Save(entity, auditnote);
  431. entity.CommitChanges();
  432. }
  433. }
  434. catch (RequestException e)
  435. {
  436. ClientFactory.RaiseRequestError(e);
  437. throw;
  438. }
  439. }
  440. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  441. {
  442. try
  443. {
  444. var timer = new Profiler<TEntity>(false);
  445. CheckSupported();
  446. _client.Save(entity, auditnote, (i, c) =>
  447. {
  448. timer.Dispose();
  449. callback?.Invoke(i, c);
  450. });
  451. }
  452. catch (RequestException e)
  453. {
  454. ClientFactory.RaiseRequestError(e);
  455. throw;
  456. }
  457. }
  458. public void Save(IEnumerable<TEntity> entities, string auditnote)
  459. {
  460. try
  461. {
  462. using var timer = new Profiler<TEntity>(false);
  463. CheckSupported();
  464. var items = entities.AsArray();
  465. if (items.Any())
  466. _client.Save(items, auditnote);
  467. timer.Log(items.Length);
  468. }
  469. catch (RequestException e)
  470. {
  471. ClientFactory.RaiseRequestError(e);
  472. throw;
  473. }
  474. }
  475. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  476. {
  477. try
  478. {
  479. var timer = new Profiler<TEntity>(false);
  480. CheckSupported();
  481. var items = entities.AsArray();
  482. if (items.Any())
  483. {
  484. _client.Save(items, auditnote, (i, e) =>
  485. {
  486. timer.Dispose(i.Count());
  487. callback?.Invoke(i, e);
  488. });
  489. }
  490. else
  491. {
  492. timer.Dispose(0);
  493. callback?.Invoke(items, null);
  494. }
  495. }
  496. catch (RequestException e)
  497. {
  498. ClientFactory.RaiseRequestError(e);
  499. throw;
  500. }
  501. }
  502. public void Delete(TEntity entity, string auditnote)
  503. {
  504. try
  505. {
  506. using (new Profiler<TEntity>(true))
  507. {
  508. CheckSupported();
  509. _client.Delete(entity, auditnote);
  510. }
  511. }
  512. catch (RequestException e)
  513. {
  514. ClientFactory.RaiseRequestError(e);
  515. throw;
  516. }
  517. }
  518. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  519. {
  520. try
  521. {
  522. var timer = new Profiler<TEntity>(true);
  523. CheckSupported();
  524. _client.Delete(entity, auditnote, (i, e) =>
  525. {
  526. timer.Dispose();
  527. callback?.Invoke(i, e);
  528. });
  529. }
  530. catch (RequestException e)
  531. {
  532. ClientFactory.RaiseRequestError(e);
  533. throw;
  534. }
  535. }
  536. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  537. {
  538. try
  539. {
  540. using var timer = new Profiler<TEntity>(false);
  541. CheckSupported();
  542. var items = entities.AsArray();
  543. _client.Delete(items, auditnote);
  544. timer.Log(items.Length);
  545. }
  546. catch (RequestException e)
  547. {
  548. ClientFactory.RaiseRequestError(e);
  549. throw;
  550. }
  551. }
  552. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  553. {
  554. try
  555. {
  556. var timer = new Profiler<TEntity>(false);
  557. CheckSupported();
  558. var items = entities.AsArray();
  559. _client.Delete(items, auditnote, (i, e) =>
  560. {
  561. timer.Dispose(i.Count);
  562. callback?.Invoke(i, e);
  563. });
  564. }
  565. catch (RequestException e)
  566. {
  567. ClientFactory.RaiseRequestError(e);
  568. throw;
  569. }
  570. }
  571. public IEnumerable<string> SupportedTypes()
  572. {
  573. try
  574. {
  575. using (new Profiler(true))
  576. return _client.SupportedTypes();
  577. }
  578. catch (RequestException e)
  579. {
  580. ClientFactory.RaiseRequestError(e);
  581. throw;
  582. }
  583. }
  584. public new DatabaseInfo Info()
  585. {
  586. try
  587. {
  588. using (new Profiler(true))
  589. return _client.Info();
  590. }
  591. catch (RequestException e)
  592. {
  593. ClientFactory.RaiseRequestError(e);
  594. throw;
  595. }
  596. }
  597. }
  598. }