Client.cs 31 KB

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