Client.cs 32 KB

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