Client.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. private void CheckSupported()
  470. {
  471. if (!ClientFactory.IsSupported<TEntity>())
  472. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  473. }
  474. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  475. {
  476. try
  477. {
  478. using var timer = new Profiler<TEntity>(false);
  479. CheckSupported();
  480. if (columns != null)
  481. {
  482. var nonpersistent = columns.Where(x => !x.PropertyDefinition.IsPersistable).ToArray();
  483. foreach (var column in nonpersistent)
  484. columns.Remove(column.Property);
  485. }
  486. var result = _client.Query(filter, columns, orderby, range);
  487. timer.Log(result.Rows.Count);
  488. return result;
  489. }
  490. catch(RequestException e)
  491. {
  492. ClientFactory.RaiseRequestError(e);
  493. throw;
  494. }
  495. }
  496. public override CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null)
  497. {
  498. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>, range);
  499. }
  500. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, CoreRange? range, Action<CoreTable?, Exception?>? callback)
  501. {
  502. try
  503. {
  504. var timer = new Profiler<TEntity>(false);
  505. CheckSupported();
  506. _client.Query(filter, columns, sort, range, (c, e) =>
  507. {
  508. timer.Log(c != null ? c.Rows.Count : -1);
  509. callback?.Invoke(c, e);
  510. });
  511. }
  512. catch (RequestException e)
  513. {
  514. ClientFactory.RaiseRequestError(e);
  515. throw;
  516. }
  517. }
  518. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
  519. {
  520. try
  521. {
  522. using (var timer = new Profiler<TEntity>(false))
  523. {
  524. CheckSupported();
  525. var result = _client.Load(filter, sort, range);
  526. foreach (var entity in result)
  527. entity.CommitChanges();
  528. timer.Log(result.Length);
  529. return result;
  530. }
  531. }
  532. catch (RequestException e)
  533. {
  534. ClientFactory.RaiseRequestError(e);
  535. throw;
  536. }
  537. }
  538. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, CoreRange? range, Action<TEntity[]?, Exception?>? callback)
  539. {
  540. try
  541. {
  542. var timer = new Profiler<TEntity>(false);
  543. CheckSupported();
  544. _client.Load(filter, sort, range,(i, e) =>
  545. {
  546. timer.Dispose(i != null ? i.Length : -1);
  547. callback?.Invoke(i, e);
  548. });
  549. }
  550. catch (RequestException e)
  551. {
  552. ClientFactory.RaiseRequestError(e);
  553. throw;
  554. }
  555. }
  556. public override void Save(Entity entity, string auditNote)
  557. {
  558. try
  559. {
  560. Save((entity as TEntity)!, auditNote);
  561. }
  562. catch (RequestException e)
  563. {
  564. ClientFactory.RaiseRequestError(e);
  565. throw;
  566. }
  567. }
  568. public override void Save(IEnumerable<Entity> entities, string auditNote)
  569. {
  570. try
  571. {
  572. Save(entities.Cast<TEntity>(), auditNote);
  573. }
  574. catch (RequestException e)
  575. {
  576. ClientFactory.RaiseRequestError(e);
  577. throw;
  578. }
  579. }
  580. public void Save(TEntity entity, string auditnote)
  581. {
  582. try
  583. {
  584. using (new Profiler<TEntity>(true))
  585. {
  586. CheckSupported();
  587. entity.LastUpdate = DateTime.Now;
  588. entity.LastUpdateBy = ClientFactory.UserID;
  589. _client.Save(entity, auditnote);
  590. entity.CommitChanges();
  591. }
  592. }
  593. catch (RequestException e)
  594. {
  595. ClientFactory.RaiseRequestError(e);
  596. throw;
  597. }
  598. }
  599. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  600. {
  601. try
  602. {
  603. var timer = new Profiler<TEntity>(false);
  604. CheckSupported();
  605. _client.Save(entity, auditnote, (i, c) =>
  606. {
  607. timer.Dispose();
  608. callback?.Invoke(i, c);
  609. });
  610. }
  611. catch (RequestException e)
  612. {
  613. ClientFactory.RaiseRequestError(e);
  614. throw;
  615. }
  616. }
  617. public void Save(IEnumerable<TEntity> entities, string auditnote)
  618. {
  619. try
  620. {
  621. using var timer = new Profiler<TEntity>(false);
  622. CheckSupported();
  623. var items = entities.AsArray();
  624. if (items.Any())
  625. _client.Save(items, auditnote);
  626. timer.Log(items.Length);
  627. }
  628. catch (RequestException e)
  629. {
  630. ClientFactory.RaiseRequestError(e);
  631. throw;
  632. }
  633. }
  634. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  635. {
  636. try
  637. {
  638. var timer = new Profiler<TEntity>(false);
  639. CheckSupported();
  640. var items = entities.AsArray();
  641. if (items.Any())
  642. {
  643. _client.Save(items, auditnote, (i, e) =>
  644. {
  645. timer.Dispose(i.Count());
  646. callback?.Invoke(i, e);
  647. });
  648. }
  649. else
  650. {
  651. timer.Dispose(0);
  652. callback?.Invoke(items, null);
  653. }
  654. }
  655. catch (RequestException e)
  656. {
  657. ClientFactory.RaiseRequestError(e);
  658. throw;
  659. }
  660. }
  661. public void Delete(TEntity entity, string auditnote)
  662. {
  663. try
  664. {
  665. using (new Profiler<TEntity>(true))
  666. {
  667. CheckSupported();
  668. _client.Delete(entity, auditnote);
  669. }
  670. }
  671. catch (RequestException e)
  672. {
  673. ClientFactory.RaiseRequestError(e);
  674. throw;
  675. }
  676. }
  677. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  678. {
  679. try
  680. {
  681. var timer = new Profiler<TEntity>(true);
  682. CheckSupported();
  683. _client.Delete(entity, auditnote, (i, e) =>
  684. {
  685. timer.Dispose();
  686. callback?.Invoke(i, e);
  687. });
  688. }
  689. catch (RequestException e)
  690. {
  691. ClientFactory.RaiseRequestError(e);
  692. throw;
  693. }
  694. }
  695. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  696. {
  697. try
  698. {
  699. using var timer = new Profiler<TEntity>(false);
  700. CheckSupported();
  701. var items = entities.AsArray();
  702. _client.Delete(items, auditnote);
  703. timer.Log(items.Length);
  704. }
  705. catch (RequestException e)
  706. {
  707. ClientFactory.RaiseRequestError(e);
  708. throw;
  709. }
  710. }
  711. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  712. {
  713. try
  714. {
  715. var timer = new Profiler<TEntity>(false);
  716. CheckSupported();
  717. var items = entities.AsArray();
  718. _client.Delete(items, auditnote, (i, e) =>
  719. {
  720. timer.Dispose(i.Count);
  721. callback?.Invoke(i, e);
  722. });
  723. }
  724. catch (RequestException e)
  725. {
  726. ClientFactory.RaiseRequestError(e);
  727. throw;
  728. }
  729. }
  730. public IEnumerable<string> SupportedTypes()
  731. {
  732. try
  733. {
  734. using (new Profiler(true))
  735. return _client.SupportedTypes();
  736. }
  737. catch (RequestException e)
  738. {
  739. ClientFactory.RaiseRequestError(e);
  740. throw;
  741. }
  742. }
  743. public new DatabaseInfo Info()
  744. {
  745. try
  746. {
  747. using (new Profiler(true))
  748. return _client.Info();
  749. }
  750. catch (RequestException e)
  751. {
  752. ClientFactory.RaiseRequestError(e);
  753. throw;
  754. }
  755. }
  756. }
  757. public static class ClientExtensions
  758. {
  759. /// <summary>
  760. /// 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"/>.
  761. /// 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
  762. /// linked table with the required columns.
  763. /// </summary>
  764. /// <param name="columns"></param>
  765. public static void LoadForeignProperties<T>(this IEnumerable<T> items, Columns<T> columns)
  766. where T : BaseObject, new()
  767. {
  768. // Lists of properties that we need, arranged by the entity link property which is their parent.
  769. // LinkIDProperty : (Type, Properties: [(columnName, property)], Objects)
  770. var newData = new Dictionary<IProperty, Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>>();
  771. foreach (var column in columns)
  772. {
  773. var property = DatabaseSchema.Property(typeof(T), column.Property);
  774. if (property?.GetOuterParent(x => x.IsEntityLink) is IProperty linkProperty)
  775. {
  776. var remaining = column.Property[(linkProperty.Name.Length + 1)..];
  777. if (remaining.Equals(nameof(IEntityLink.ID)))
  778. {
  779. // This guy isn't foreign, so we don't pull him.
  780. continue;
  781. }
  782. var idProperty = DatabaseSchema.Property(typeof(T), linkProperty.Name + "." + nameof(IEntityLink.ID))!;
  783. var linkType = linkProperty.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))!.GenericTypeArguments[0];
  784. if (!newData.TryGetValue(idProperty, out var data))
  785. {
  786. data = new Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>(
  787. linkType,
  788. new List<Tuple<string, IProperty>>(),
  789. new HashSet<T>());
  790. newData.Add(idProperty, data);
  791. }
  792. var any = false;
  793. foreach (var item in items)
  794. {
  795. if (!item.LoadedColumns.Contains(column.Property))
  796. {
  797. var linkID = (Guid)idProperty.Getter()(item);
  798. if (linkID != Guid.Empty)
  799. {
  800. any = true;
  801. data.Item3.Add(item);
  802. }
  803. }
  804. }
  805. if (any)
  806. {
  807. data.Item2.Add(new Tuple<string, IProperty>(remaining, property));
  808. }
  809. }
  810. }
  811. var queryDefs = new List<IKeyedQueryDef>();
  812. foreach (var (prop, data) in newData)
  813. {
  814. if (data.Item2.Count != 0)
  815. {
  816. var ids = data.Item3.Select(prop.Getter()).Cast<Guid>().ToArray();
  817. queryDefs.Add(new KeyedQueryDef(prop.Name, data.Item1,
  818. Filter.Create<Entity>(data.Item1, x => x.ID).InList(ids),
  819. Columns.None(data.Item1)
  820. .Add(data.Item2.Select(x => x.Item1))
  821. .Add<Entity>(x => x.ID)));
  822. }
  823. }
  824. var results = Client.QueryMultiple(queryDefs);
  825. foreach(var (prop, data) in newData)
  826. {
  827. var table = results.GetOrDefault(prop.Name);
  828. if(table is null)
  829. {
  830. continue;
  831. }
  832. var keyCol = table.GetColumnIndex<Entity, Guid>(x => x.ID);
  833. var dict = table.Rows.ToDictionary(x => x.Get<Guid>(keyCol));
  834. foreach (var entity in data.Item3)
  835. {
  836. var linkID = (Guid)prop.Getter()(entity);
  837. if (dict.TryGetValue(linkID, out var row))
  838. {
  839. foreach (var (name, property) in data.Item2)
  840. {
  841. if (!entity.LoadedColumns.Contains(property.Name))
  842. {
  843. property.Setter()(entity, row[name]);
  844. entity.LoadedColumns.Add(property.Name);
  845. }
  846. }
  847. }
  848. }
  849. }
  850. }
  851. }
  852. }