Client.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using System.Timers;
  7. using InABox.Core;
  8. using IQueryProvider = InABox.Core.IQueryProvider;
  9. namespace InABox.Clients
  10. {
  11. public enum SerializerProtocol
  12. {
  13. Rest,
  14. RPC
  15. }
  16. public class QueryMultipleResults
  17. {
  18. private readonly Dictionary<string, CoreTable> Results;
  19. internal QueryMultipleResults(Dictionary<string, CoreTable> results)
  20. {
  21. Results = results;
  22. }
  23. public CoreTable this[string name] => Results[name];
  24. public CoreTable Get<T>() => Results[typeof(T).Name];
  25. /// <summary>
  26. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToObjects{T}"/> on the table.
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <returns></returns>
  30. public IEnumerable<T> GetObjects<T>()
  31. where T: BaseObject, new()
  32. => Results[typeof(T).Name].ToObjects<T>();
  33. /// <summary>
  34. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToArray{T}"/> on the table.
  35. /// </summary>
  36. /// <typeparam name="T"></typeparam>
  37. /// <returns></returns>
  38. public T[] GetArray<T>()
  39. where T: BaseObject, new()
  40. => Results[typeof(T).Name].ToArray<T>();
  41. /// <summary>
  42. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToList{T}"/> on the table.
  43. /// </summary>
  44. /// <typeparam name="T"></typeparam>
  45. /// <returns></returns>
  46. public List<T> GetList<T>()
  47. where T: BaseObject, new()
  48. => Results[typeof(T).Name].ToList<T>();
  49. public CoreTable Get(string name) => Results[name];
  50. public CoreTable GetOrDefault(string name) => Results.GetValueOrDefault(name);
  51. }
  52. public class ClientQueryProvider<TEntity> : IQueryProvider<TEntity>
  53. where TEntity : Entity, IRemotable, new()
  54. {
  55. #region Non-generic
  56. public CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null, CoreRange? range = null)
  57. {
  58. return new Client<TEntity>().Query(filter, columns, sort, range);
  59. }
  60. #endregion
  61. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
  62. {
  63. return Client.Query(filter, columns, sort, range);
  64. }
  65. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, CoreRange? range, Action<CoreTable?, Exception?> action)
  66. {
  67. Client.Query(filter, columns, sort, range, action);
  68. }
  69. public void Save(TEntity entity, string auditNote)
  70. {
  71. Client.Save(entity, auditNote);
  72. }
  73. public void Save(IEnumerable<TEntity> entities, string auditNote)
  74. {
  75. Client.Save(entities, auditNote);
  76. }
  77. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  78. {
  79. Client.Save(entity, auditnote, callback);
  80. }
  81. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  82. {
  83. Client.Save(entities, auditnote, callback);
  84. }
  85. public void Delete(TEntity entity, string auditNote)
  86. {
  87. Client.Delete(entity, auditNote);
  88. }
  89. public void Delete(IEnumerable<TEntity> entities, string auditNote)
  90. {
  91. Client.Delete(entities, auditNote);
  92. }
  93. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  94. {
  95. Client.Delete(entity, auditnote, callback);
  96. }
  97. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  98. {
  99. Client.Delete(entities, auditnote, callback);
  100. }
  101. }
  102. public abstract class Client
  103. {
  104. #region IQueryProvider Factory
  105. private class _Factory : IQueryProviderFactory
  106. {
  107. public IQueryProvider Create(Type T)
  108. {
  109. return (typeof(ClientQueryProvider<>).MakeGenericType(T) as IQueryProvider)!;
  110. }
  111. }
  112. public static IQueryProviderFactory Factory { get; } = new _Factory();
  113. #endregion
  114. public abstract CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null);
  115. public abstract void Save(Entity entity, string auditNote);
  116. public abstract void Save(IEnumerable<Entity> entity, string auditNote);
  117. private static IClient CheckClient()
  118. {
  119. return ClientFactory.CreateClient<User>();
  120. }
  121. public static Dictionary<string, CoreTable> QueryMultiple(Dictionary<string, IQueryDef> queries)
  122. {
  123. try
  124. {
  125. using var timer = new Profiler(false);
  126. var result = CheckClient().QueryMultiple(queries);
  127. timer.Log(result.Sum(x => x.Value.Rows.Count));
  128. return result;
  129. }
  130. catch (RequestException e)
  131. {
  132. ClientFactory.RaiseRequestError(e);
  133. throw;
  134. }
  135. }
  136. private static IClient<TEntity> CheckClient<TEntity>() where TEntity : Entity, IRemotable, new()
  137. {
  138. return ClientFactory.CreateClient<TEntity>();
  139. }
  140. public static void EnsureColumns<TEntity>(TEntity entity, Columns<TEntity> columns)
  141. where TEntity : Entity, IRemotable, new()
  142. {
  143. var newColumns = Columns.None<TEntity>()
  144. .AddRange(columns.Where(x => !entity.HasColumn(x.Property)));
  145. if (newColumns.Count > 0)
  146. {
  147. var row = Query(new Filter<TEntity>(x => x.ID).IsEqualTo(entity.ID), newColumns).Rows.FirstOrDefault();
  148. row?.FillObject(entity);
  149. }
  150. }
  151. public static void EnsureColumns<TEntity>(ICollection<TEntity> entities, Columns<TEntity> columns)
  152. where TEntity : Entity, IRemotable, new()
  153. {
  154. var newColumns = Columns.None<TEntity>()
  155. .AddRange(columns.Where(x => entities.Any(entity => !entity.HasColumn(x.Property))));
  156. if (newColumns.Count > 0)
  157. {
  158. newColumns.Add(x => x.ID);
  159. var table = Query(new Filter<TEntity>(x => x.ID).InList(entities.Select(x => x.ID).ToArray()), newColumns);
  160. foreach(var row in table.Rows)
  161. {
  162. var id = row.Get<TEntity, Guid>(x => x.ID);
  163. var entity = entities.FirstOrDefault(x => x.ID == id);
  164. if(entity is null)
  165. {
  166. // Shouldn't happen, but just in case.
  167. continue;
  168. }
  169. row?.FillObject(entity);
  170. }
  171. }
  172. }
  173. public static CoreTable Query<TEntity>(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  174. where TEntity : Entity, IRemotable, new()
  175. {
  176. return new Client<TEntity>().Query(filter, columns, orderby, range);
  177. }
  178. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, CoreRange? range, Action<CoreTable?, Exception?> callback)
  179. where TEntity : Entity, IRemotable, new()
  180. {
  181. new Client<TEntity>().Query(filter, columns, orderby, range, callback);
  182. }
  183. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, Action<CoreTable?, Exception?> callback)
  184. where TEntity : Entity, IRemotable, new()
  185. {
  186. new Client<TEntity>().Query(filter, columns, orderby, null, callback);
  187. }
  188. public static void Save<TEntity>(TEntity entity, string auditNote)
  189. where TEntity : Entity, IRemotable, new()
  190. {
  191. new Client<TEntity>().Save(entity, auditNote);
  192. }
  193. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  194. where TEntity : Entity, IRemotable, new()
  195. {
  196. new Client<TEntity>().Save(entities, auditNote);
  197. }
  198. public static void Save<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  199. where TEntity : Entity, IRemotable, new()
  200. {
  201. new Client<TEntity>().Save(entity, auditNote, callback);
  202. }
  203. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote, Action<IEnumerable<TEntity>, Exception?> callback)
  204. where TEntity : Entity, IRemotable, new()
  205. {
  206. new Client<TEntity>().Save(entities, auditNote, callback);
  207. }
  208. public static void Delete<TEntity>(TEntity entity, string auditNote)
  209. where TEntity : Entity, IRemotable, new()
  210. {
  211. new Client<TEntity>().Delete(entity, auditNote);
  212. }
  213. public static void Delete<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  214. where TEntity : Entity, IRemotable, new()
  215. {
  216. new Client<TEntity>().Delete(entity, auditNote, callback);
  217. }
  218. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  219. where TEntity : Entity, IRemotable, new()
  220. {
  221. new Client<TEntity>().Delete(entities, auditNote);
  222. }
  223. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote, Action<IList<TEntity>, Exception?> callback)
  224. where TEntity : Entity, IRemotable, new()
  225. {
  226. new Client<TEntity>().Delete(entities, auditNote, callback);
  227. }
  228. public static void QueryMultiple(
  229. Action<Dictionary<string, CoreTable>?, Exception?> callback,
  230. Dictionary<string, IQueryDef> queries)
  231. {
  232. try
  233. {
  234. using var timer = new Profiler(false);
  235. CheckClient().QueryMultiple((result, e) =>
  236. {
  237. timer.Dispose(result != null ? result.Sum(x => x.Value.Rows.Count) : -1);
  238. callback?.Invoke(result, e);
  239. }, queries);
  240. }
  241. catch (RequestException e)
  242. {
  243. ClientFactory.RaiseRequestError(e);
  244. throw;
  245. }
  246. }
  247. public static QueryMultipleResults QueryMultiple(params IKeyedQueryDef[] queries) =>
  248. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  249. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, params IKeyedQueryDef[] queries) =>
  250. QueryMultiple((results, e) =>
  251. {
  252. if (results != null)
  253. {
  254. callback?.Invoke(new QueryMultipleResults(results), e);
  255. }
  256. else
  257. {
  258. callback?.Invoke(null, e);
  259. }
  260. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  261. public static QueryMultipleResults QueryMultiple(IEnumerable<IKeyedQueryDef> queries) =>
  262. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  263. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, IEnumerable<IKeyedQueryDef> queries) =>
  264. QueryMultiple((results, e) =>
  265. {
  266. if(results != null)
  267. {
  268. callback?.Invoke(new QueryMultipleResults(results), e);
  269. }
  270. else
  271. {
  272. callback?.Invoke(null, e);
  273. }
  274. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  275. public static IValidationData Validate(Guid session)
  276. {
  277. try
  278. {
  279. using (new Profiler(true))
  280. return CheckClient().Validate(session);
  281. }
  282. catch (RequestException e)
  283. {
  284. ClientFactory.RaiseRequestError(e);
  285. throw;
  286. }
  287. }
  288. public static IValidationData Validate(string pin, Guid session = default)
  289. {
  290. try
  291. {
  292. using (new Profiler(true))
  293. return CheckClient().Validate(pin, session);
  294. }
  295. catch (RequestException e)
  296. {
  297. ClientFactory.RaiseRequestError(e);
  298. throw;
  299. }
  300. }
  301. public static IValidationData Validate(string userid, string password, Guid session = default)
  302. {
  303. try
  304. {
  305. using (new Profiler(true))
  306. return CheckClient().Validate(userid, password, session);
  307. }
  308. catch (RequestException e)
  309. {
  310. ClientFactory.RaiseRequestError(e);
  311. throw;
  312. }
  313. }
  314. public static bool Check2FA(string code, Guid? session = null)
  315. {
  316. try
  317. {
  318. using (new Profiler(true))
  319. return CheckClient().Check2FA(code, session);
  320. }
  321. catch (RequestException e)
  322. {
  323. ClientFactory.RaiseRequestError(e);
  324. throw;
  325. }
  326. }
  327. public static bool Ping()
  328. {
  329. try
  330. {
  331. return CheckClient().Ping();
  332. }
  333. catch (RequestException e)
  334. {
  335. ClientFactory.RaiseRequestError(e);
  336. throw;
  337. }
  338. }
  339. public static DatabaseInfo? Info()
  340. {
  341. try
  342. {
  343. using (new Profiler(true))
  344. return CheckClient().Info();
  345. }
  346. catch (RequestException e)
  347. {
  348. ClientFactory.RaiseRequestError(e);
  349. throw;
  350. }
  351. }
  352. public static string Version()
  353. {
  354. try
  355. {
  356. using (new Profiler(true))
  357. return CheckClient().Version();
  358. }
  359. catch (RequestException e)
  360. {
  361. ClientFactory.RaiseRequestError(e);
  362. throw;
  363. }
  364. }
  365. public static string ReleaseNotes()
  366. {
  367. try
  368. {
  369. using (new Profiler(true))
  370. return CheckClient().ReleaseNotes();
  371. }
  372. catch (RequestException e)
  373. {
  374. ClientFactory.RaiseRequestError(e);
  375. throw;
  376. }
  377. }
  378. public static byte[]? Installer()
  379. {
  380. try
  381. {
  382. using (new Profiler(true))
  383. return CheckClient().Installer();
  384. }
  385. catch (RequestException e)
  386. {
  387. ClientFactory.RaiseRequestError(e);
  388. throw;
  389. }
  390. }
  391. public static Client Create(Type TEntity) =>
  392. (Activator.CreateInstance(typeof(Client<>).MakeGenericType(TEntity)) as Client)!;
  393. }
  394. public class Client<TEntity> : Client, IDisposable where TEntity : Entity, IRemotable, new()
  395. {
  396. #region IQueryProvider
  397. public static IQueryProvider<TEntity> Provider { get; private set; } = new ClientQueryProvider<TEntity>();
  398. #endregion
  399. private IClient<TEntity> _client;
  400. public Client()
  401. {
  402. _client = ClientFactory.CreateClient<TEntity>();
  403. }
  404. public void Dispose()
  405. {
  406. }
  407. private void CheckSupported()
  408. {
  409. if (!ClientFactory.IsSupported<TEntity>())
  410. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  411. }
  412. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  413. {
  414. try
  415. {
  416. using var timer = new Profiler<TEntity>(false);
  417. CheckSupported();
  418. var result = _client.Query(filter, columns, orderby, range);
  419. timer.Log(result.Rows.Count);
  420. return result;
  421. }
  422. catch(RequestException e)
  423. {
  424. ClientFactory.RaiseRequestError(e);
  425. throw;
  426. }
  427. }
  428. public override CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null)
  429. {
  430. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>, range);
  431. }
  432. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, CoreRange? range, Action<CoreTable?, Exception?>? callback)
  433. {
  434. try
  435. {
  436. var timer = new Profiler<TEntity>(false);
  437. CheckSupported();
  438. _client.Query(filter, columns, sort, range, (c, e) =>
  439. {
  440. timer.Log(c != null ? c.Rows.Count : -1);
  441. callback?.Invoke(c, e);
  442. });
  443. }
  444. catch (RequestException e)
  445. {
  446. ClientFactory.RaiseRequestError(e);
  447. throw;
  448. }
  449. }
  450. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
  451. {
  452. try
  453. {
  454. using (var timer = new Profiler<TEntity>(false))
  455. {
  456. CheckSupported();
  457. var result = _client.Load(filter, sort, range);
  458. foreach (var entity in result)
  459. entity.CommitChanges();
  460. timer.Log(result.Length);
  461. return result;
  462. }
  463. }
  464. catch (RequestException e)
  465. {
  466. ClientFactory.RaiseRequestError(e);
  467. throw;
  468. }
  469. }
  470. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, CoreRange? range, Action<TEntity[]?, Exception?>? callback)
  471. {
  472. try
  473. {
  474. var timer = new Profiler<TEntity>(false);
  475. CheckSupported();
  476. _client.Load(filter, sort, range,(i, e) =>
  477. {
  478. timer.Dispose(i != null ? i.Length : -1);
  479. callback?.Invoke(i, e);
  480. });
  481. }
  482. catch (RequestException e)
  483. {
  484. ClientFactory.RaiseRequestError(e);
  485. throw;
  486. }
  487. }
  488. public override void Save(Entity entity, string auditNote)
  489. {
  490. try
  491. {
  492. Save((entity as TEntity)!, auditNote);
  493. }
  494. catch (RequestException e)
  495. {
  496. ClientFactory.RaiseRequestError(e);
  497. throw;
  498. }
  499. }
  500. public override void Save(IEnumerable<Entity> entities, string auditNote)
  501. {
  502. try
  503. {
  504. Save(entities.Cast<TEntity>(), auditNote);
  505. }
  506. catch (RequestException e)
  507. {
  508. ClientFactory.RaiseRequestError(e);
  509. throw;
  510. }
  511. }
  512. public void Save(TEntity entity, string auditnote)
  513. {
  514. try
  515. {
  516. using (new Profiler<TEntity>(true))
  517. {
  518. CheckSupported();
  519. entity.LastUpdate = DateTime.Now;
  520. entity.LastUpdateBy = ClientFactory.UserID;
  521. _client.Save(entity, auditnote);
  522. entity.CommitChanges();
  523. }
  524. }
  525. catch (RequestException e)
  526. {
  527. ClientFactory.RaiseRequestError(e);
  528. throw;
  529. }
  530. }
  531. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  532. {
  533. try
  534. {
  535. var timer = new Profiler<TEntity>(false);
  536. CheckSupported();
  537. _client.Save(entity, auditnote, (i, c) =>
  538. {
  539. timer.Dispose();
  540. callback?.Invoke(i, c);
  541. });
  542. }
  543. catch (RequestException e)
  544. {
  545. ClientFactory.RaiseRequestError(e);
  546. throw;
  547. }
  548. }
  549. public void Save(IEnumerable<TEntity> entities, string auditnote)
  550. {
  551. try
  552. {
  553. using var timer = new Profiler<TEntity>(false);
  554. CheckSupported();
  555. var items = entities.AsArray();
  556. if (items.Any())
  557. _client.Save(items, auditnote);
  558. timer.Log(items.Length);
  559. }
  560. catch (RequestException e)
  561. {
  562. ClientFactory.RaiseRequestError(e);
  563. throw;
  564. }
  565. }
  566. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  567. {
  568. try
  569. {
  570. var timer = new Profiler<TEntity>(false);
  571. CheckSupported();
  572. var items = entities.AsArray();
  573. if (items.Any())
  574. {
  575. _client.Save(items, auditnote, (i, e) =>
  576. {
  577. timer.Dispose(i.Count());
  578. callback?.Invoke(i, e);
  579. });
  580. }
  581. else
  582. {
  583. timer.Dispose(0);
  584. callback?.Invoke(items, null);
  585. }
  586. }
  587. catch (RequestException e)
  588. {
  589. ClientFactory.RaiseRequestError(e);
  590. throw;
  591. }
  592. }
  593. public void Delete(TEntity entity, string auditnote)
  594. {
  595. try
  596. {
  597. using (new Profiler<TEntity>(true))
  598. {
  599. CheckSupported();
  600. _client.Delete(entity, auditnote);
  601. }
  602. }
  603. catch (RequestException e)
  604. {
  605. ClientFactory.RaiseRequestError(e);
  606. throw;
  607. }
  608. }
  609. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  610. {
  611. try
  612. {
  613. var timer = new Profiler<TEntity>(true);
  614. CheckSupported();
  615. _client.Delete(entity, auditnote, (i, e) =>
  616. {
  617. timer.Dispose();
  618. callback?.Invoke(i, e);
  619. });
  620. }
  621. catch (RequestException e)
  622. {
  623. ClientFactory.RaiseRequestError(e);
  624. throw;
  625. }
  626. }
  627. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  628. {
  629. try
  630. {
  631. using var timer = new Profiler<TEntity>(false);
  632. CheckSupported();
  633. var items = entities.AsArray();
  634. _client.Delete(items, auditnote);
  635. timer.Log(items.Length);
  636. }
  637. catch (RequestException e)
  638. {
  639. ClientFactory.RaiseRequestError(e);
  640. throw;
  641. }
  642. }
  643. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  644. {
  645. try
  646. {
  647. var timer = new Profiler<TEntity>(false);
  648. CheckSupported();
  649. var items = entities.AsArray();
  650. _client.Delete(items, auditnote, (i, e) =>
  651. {
  652. timer.Dispose(i.Count);
  653. callback?.Invoke(i, e);
  654. });
  655. }
  656. catch (RequestException e)
  657. {
  658. ClientFactory.RaiseRequestError(e);
  659. throw;
  660. }
  661. }
  662. public IEnumerable<string> SupportedTypes()
  663. {
  664. try
  665. {
  666. using (new Profiler(true))
  667. return _client.SupportedTypes();
  668. }
  669. catch (RequestException e)
  670. {
  671. ClientFactory.RaiseRequestError(e);
  672. throw;
  673. }
  674. }
  675. public new DatabaseInfo Info()
  676. {
  677. try
  678. {
  679. using (new Profiler(true))
  680. return _client.Info();
  681. }
  682. catch (RequestException e)
  683. {
  684. ClientFactory.RaiseRequestError(e);
  685. throw;
  686. }
  687. }
  688. }
  689. public static class ClientExtensions
  690. {
  691. /// <summary>
  692. /// Load the properties of any <see cref="EntityLink{T}"/>s on this <typeparamref name="T"/> where the <see cref="IEntityLink.ID"/> is not <see cref="Guid.Empty"/>.
  693. /// This allows us to populate columns of transient objects, as long as they are linked by the ID. What this actually then does is query each
  694. /// linked table with the required columns.
  695. /// </summary>
  696. /// <param name="columns"></param>
  697. public static void LoadForeignProperties<T>(this IEnumerable<T> items, Columns<T> columns)
  698. where T : BaseObject, new()
  699. {
  700. // Lists of properties that we need, arranged by the entity link property which is their parent.
  701. // LinkIDProperty : (Type, Properties: [(columnName, property)], Objects)
  702. var newData = new Dictionary<IProperty, Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>>();
  703. foreach (var column in columns)
  704. {
  705. var property = DatabaseSchema.Property(typeof(T), column.Property);
  706. if (property?.GetOuterParent(x => x.IsEntityLink) is IProperty linkProperty)
  707. {
  708. var remaining = column.Property[(linkProperty.Name.Length + 1)..];
  709. if (remaining.Equals(nameof(IEntityLink.ID)))
  710. {
  711. // This guy isn't foreign, so we don't pull him.
  712. continue;
  713. }
  714. var idProperty = DatabaseSchema.Property(typeof(T), linkProperty.Name + "." + nameof(IEntityLink.ID))!;
  715. var linkType = linkProperty.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))!.GenericTypeArguments[0];
  716. if (!newData.TryGetValue(idProperty, out var data))
  717. {
  718. data = new Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>(
  719. linkType,
  720. new List<Tuple<string, IProperty>>(),
  721. new HashSet<T>());
  722. newData.Add(idProperty, data);
  723. }
  724. var any = false;
  725. foreach (var item in items)
  726. {
  727. if (!item.LoadedColumns.Contains(column.Property))
  728. {
  729. var linkID = (Guid)idProperty.Getter()(item);
  730. if (linkID != Guid.Empty)
  731. {
  732. any = true;
  733. data.Item3.Add(item);
  734. }
  735. }
  736. }
  737. if (any)
  738. {
  739. data.Item2.Add(new Tuple<string, IProperty>(remaining, property));
  740. }
  741. }
  742. }
  743. var queryDefs = new List<IKeyedQueryDef>();
  744. foreach (var (prop, data) in newData)
  745. {
  746. if (data.Item2.Count != 0)
  747. {
  748. var ids = data.Item3.Select(prop.Getter()).Cast<Guid>().ToArray();
  749. queryDefs.Add(new KeyedQueryDef(prop.Name, data.Item1,
  750. Filter.Create<Entity>(data.Item1, x => x.ID).InList(ids),
  751. Columns.None(data.Item1)
  752. .Add(data.Item2.Select(x => x.Item1))
  753. .Add<Entity>(x => x.ID)));
  754. }
  755. }
  756. var results = Client.QueryMultiple(queryDefs);
  757. foreach(var (prop, data) in newData)
  758. {
  759. var table = results.GetOrDefault(prop.Name);
  760. if(table is null)
  761. {
  762. continue;
  763. }
  764. var keyCol = table.GetColumnIndex<Entity, Guid>(x => x.ID);
  765. var dict = table.Rows.ToDictionary(x => x.Get<Guid>(keyCol));
  766. foreach (var entity in data.Item3)
  767. {
  768. var linkID = (Guid)prop.Getter()(entity);
  769. if (dict.TryGetValue(linkID, out var row))
  770. {
  771. foreach (var (name, property) in data.Item2)
  772. {
  773. if (!entity.LoadedColumns.Contains(property.Name))
  774. {
  775. property.Setter()(entity, row[name]);
  776. entity.LoadedColumns.Add(property.Name);
  777. }
  778. }
  779. }
  780. }
  781. }
  782. }
  783. }
  784. }