Client.cs 31 KB

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