Client.cs 30 KB

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