Client.cs 32 KB

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