Client.cs 32 KB

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