DynamicDataGrid.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Controls;
  12. using InABox.Clients;
  13. using InABox.Configuration;
  14. using InABox.Core;
  15. using InABox.Wpf;
  16. using InABox.WPF;
  17. using Expression = System.Linq.Expressions.Expression;
  18. namespace InABox.DynamicGrid;
  19. public interface IDynamicDataGrid : IDynamicGrid
  20. {
  21. /// <summary>
  22. /// The tag the the DynamicGridColumns are stored against. If set to <see langword="null"/>,
  23. /// the name of <typeparamref name="TEntity"/> is used as a default.
  24. /// </summary>
  25. string? ColumnsTag { get; set; }
  26. IColumns LoadEditorColumns();
  27. Type DataType { get; }
  28. }
  29. public class DynamicDataGrid<TEntity> : DynamicGrid<TEntity>, IDynamicDataGrid where TEntity : Entity, IRemotable, IPersistent, new()
  30. {
  31. public delegate void OnReloadEventHandler(object sender, Filters<TEntity> criteria, Columns<TEntity> columns, ref SortOrder<TEntity>? sortby);
  32. private readonly int ChunkSize = 500;
  33. private Button MergeBtn = null!; //Late-initialised
  34. public DynamicGridFilterButtonComponent<TEntity> FilterComponent;
  35. protected DynamicGridCustomColumnsComponent<TEntity> ColumnsComponent;
  36. private Column<TEntity>[] FilterColumns;
  37. public Type DataType => typeof(TEntity);
  38. public DynamicDataGrid() : base()
  39. {
  40. var fields = DatabaseSchema.Properties(typeof(TEntity));
  41. foreach (var field in fields)
  42. if (!MasterColumns.Any(x => x.ColumnName == field.Name))
  43. MasterColumns.Add(new DynamicGridColumn { ColumnName = field.Name });
  44. var cols = LookupFactory.DefineColumns<TEntity>();
  45. // Minimum Columns for Lookup values
  46. foreach (var col in cols)
  47. HiddenColumns.Add(col);
  48. if (typeof(TEntity).GetInterfaces().Contains(typeof(IProblems)))
  49. {
  50. HiddenColumns.Add(x => (x as IProblems)!.Problem.Notes);
  51. HiddenColumns.Add(x=>(x as IProblems)!.Problem.Resolved);
  52. var coltype = typeof(DynamicProblemsColumn<>).MakeGenericType(typeof(TEntity));
  53. var column = Activator.CreateInstance(coltype, this);
  54. var dac = (column as DynamicActionColumn)!;
  55. ActionColumns.Add(dac);
  56. }
  57. SetupFilterColumns();
  58. }
  59. protected override void Init()
  60. {
  61. FilterComponent = new(this,
  62. new GlobalConfiguration<CoreFilterDefinitions>(GetTag()),
  63. new UserConfiguration<CoreFilterDefinitions>(GetTag()));
  64. FilterComponent.OnFilterRefresh += () => Refresh(false, true);
  65. ColumnsComponent = new DynamicGridCustomColumnsComponent<TEntity>(this, GetTag());
  66. MergeBtn = AddButton("Merge", Wpf.Resources.merge.AsBitmapImage(Color.White), MergeClick);
  67. }
  68. protected override void DoReconfigure(DynamicGridOptions options)
  69. {
  70. if (Security.CanEdit<TEntity>())
  71. {
  72. options.AddRows = true;
  73. options.EditRows = true;
  74. }
  75. if (Security.CanDelete<TEntity>())
  76. options.DeleteRows = true;
  77. if (Security.CanImport<TEntity>() && typeof(TEntity).HasInterface<IImportable>())
  78. options.ImportData = true;
  79. if (Security.CanExport<TEntity>() && typeof(TEntity).HasInterface<IExportable>())
  80. options.ExportData = true;
  81. if (Security.CanMerge<TEntity>())
  82. options.MultiSelect = true;
  83. }
  84. [MemberNotNull(nameof(FilterColumns))]
  85. private void SetupFilterColumns()
  86. {
  87. if (typeof(TEntity).GetCustomAttribute<AutoEntity>() is AutoEntity auto)
  88. {
  89. if (auto.Generator is not null)
  90. {
  91. var columns = auto.Generator.IDColumns;
  92. FilterColumns = columns.Select(x => new Column<TEntity>(x.Property)).ToArray();
  93. }
  94. else
  95. {
  96. FilterColumns = Array.Empty<Column<TEntity>>();
  97. }
  98. }
  99. else
  100. {
  101. FilterColumns = new[] { new Column<TEntity>(x => x.ID) };
  102. }
  103. foreach (var column in FilterColumns)
  104. {
  105. AddHiddenColumn(column.Property);
  106. }
  107. }
  108. protected override void BeforeLoad(IDynamicEditorForm form, TEntity[] items)
  109. {
  110. form.ReadOnly = form.ReadOnly || !Security.CanEdit<TEntity>();
  111. base.BeforeLoad(form, items);
  112. }
  113. private string? _columnsTag;
  114. public string? ColumnsTag
  115. {
  116. get => _columnsTag;
  117. set
  118. {
  119. _columnsTag = value;
  120. ColumnsComponent.Tag = GetTag();
  121. }
  122. }
  123. protected override void OptionsChanged()
  124. {
  125. base.OptionsChanged();
  126. if (MergeBtn != null)
  127. MergeBtn.Visibility = Visibility.Collapsed;
  128. FilterComponent.ShowFilterList = Options.FilterRows && !Options.HideDatabaseFilters;
  129. }
  130. protected override void SelectItems(CoreRow[]? rows)
  131. {
  132. base.SelectItems(rows);
  133. MergeBtn.Visibility = Options.MultiSelect && typeof(TEntity).IsAssignableTo(typeof(IMergeable)) && Security.CanMerge<TEntity>() && rows != null && rows.Length > 1
  134. ? Visibility.Visible
  135. : Visibility.Collapsed;
  136. }
  137. public event OnReloadEventHandler? OnReload;
  138. protected override string FormatRecordCount(int count)
  139. {
  140. return IsPaging
  141. ? $"{base.FormatRecordCount(count)} (loading..)"
  142. : base.FormatRecordCount(count);
  143. }
  144. protected override void Reload(
  145. Filters<TEntity> criteria, Columns<TEntity> columns, ref SortOrder<TEntity>? sort,
  146. CancellationToken token, Action<CoreTable?, Exception?> action)
  147. {
  148. criteria.Add(FilterComponent.GetFilter());
  149. OnReload?.Invoke(this, criteria, columns, ref sort);
  150. if(Options.PageSize > 0)
  151. {
  152. var inSort = sort;
  153. Task.Run(() =>
  154. {
  155. var page = CoreRange.Database(Options.PageSize);
  156. var filter = criteria.Combine();
  157. IsPaging = true;
  158. while (!token.IsCancellationRequested)
  159. {
  160. try
  161. {
  162. var data = Client.Query(filter, columns, inSort, page);
  163. data.Offset = page.Offset;
  164. IsPaging = data.Rows.Count == page.Limit;
  165. if (token.IsCancellationRequested)
  166. {
  167. break;
  168. }
  169. action(data, null);
  170. if (!IsPaging)
  171. break;
  172. // Proposal - Let's slow it down a bit to enhance UI responsiveness?
  173. Thread.Sleep(100);
  174. page.Next();
  175. }
  176. catch (Exception e)
  177. {
  178. action(null, e);
  179. break;
  180. }
  181. }
  182. }, token);
  183. }
  184. else
  185. {
  186. Client.Query(criteria.Combine(), columns, sort, action);
  187. }
  188. }
  189. private CoreRow[]? SelectedBeforeRefresh;
  190. protected override void OnAfterRefresh()
  191. {
  192. base.OnAfterRefresh();
  193. if (SelectedBeforeRefresh is not null)
  194. {
  195. var selectedValues = SelectedBeforeRefresh
  196. .Select(x => FilterColumns.Select(c => x[c.Property]).ToList())
  197. .ToList();
  198. SelectedBeforeRefresh = null;
  199. var selectedRows = Data.Rows.Where(r =>
  200. {
  201. return selectedValues.Any(v =>
  202. {
  203. for (int i = 0; i < v.Count; ++i)
  204. {
  205. if (v[i]?.Equals(r[FilterColumns[i].Property]) != true)
  206. return false;
  207. }
  208. return true;
  209. });
  210. }).ToArray();
  211. SelectedRows = selectedRows;
  212. SelectItems(selectedRows);
  213. }
  214. }
  215. public override void Refresh(bool reloadcolumns, bool reloaddata)
  216. {
  217. SelectedBeforeRefresh = SelectedRows;
  218. base.Refresh(reloadcolumns, reloaddata);
  219. }
  220. IColumns IDynamicDataGrid.LoadEditorColumns() => LoadEditorColumns();
  221. public Columns<TEntity> LoadEditorColumns()
  222. {
  223. return DynamicGridUtils.LoadEditorColumns(DataColumns());
  224. }
  225. private Filter<TEntity>? GetRowFilter(CoreRow row)
  226. {
  227. var newFilters = new Filters<TEntity>();
  228. foreach (var column in FilterColumns)
  229. {
  230. newFilters.Add(new Filter<TEntity>(column.Property).IsEqualTo(row[column.Property]));
  231. }
  232. return newFilters.Combine();
  233. }
  234. public override TEntity[] LoadItems(IList<CoreRow> rows)
  235. {
  236. Filter<TEntity>? filter = null;
  237. var results = new List<TEntity>(rows.Count);
  238. for (var i = 0; i < rows.Count; i += ChunkSize)
  239. {
  240. var chunk = rows.Skip(i).Take(ChunkSize);
  241. foreach (var row in chunk)
  242. {
  243. var newFilter = GetRowFilter(row);
  244. if (newFilter is not null)
  245. {
  246. if (filter is null)
  247. filter = newFilter;
  248. else
  249. filter = filter.Or(newFilter);
  250. }
  251. }
  252. var columns = LoadEditorColumns();
  253. var data = Client.Query(filter, columns);
  254. results.AddRange(data.ToObjects<TEntity>());
  255. }
  256. return results.ToArray();
  257. }
  258. public override TEntity LoadItem(CoreRow row)
  259. {
  260. var id = row.Get<TEntity, Guid>(x => x.ID);
  261. var filter = GetRowFilter(row);
  262. return Client.Query(filter, LoadEditorColumns()).ToObjects<TEntity>().FirstOrDefault()
  263. ?? throw new Exception($"No {typeof(TEntity).Name} with ID {id}");
  264. }
  265. public override void SaveItem(TEntity item)
  266. {
  267. Client.Save(item, "Edited by User");
  268. }
  269. public override void SaveItems(IEnumerable<TEntity> items)
  270. {
  271. Client.Save(items, "Edited by User");
  272. }
  273. public override void DeleteItems(params CoreRow[] rows)
  274. {
  275. var deletes = new List<TEntity>();
  276. foreach (var row in rows)
  277. {
  278. var delete = new TEntity();
  279. foreach (var column in FilterColumns)
  280. {
  281. CoreUtils.SetPropertyValue(delete, column.Property, row[column.Property]);
  282. }
  283. deletes.Add(delete);
  284. }
  285. Client.Delete(deletes, "Deleted on User Request");
  286. }
  287. private object GetPropertyValue(Expression member, object obj)
  288. {
  289. var objectMember = Expression.Convert(member, typeof(object));
  290. var getterLambda = Expression.Lambda<Func<object>>(objectMember);
  291. var getter = getterLambda.Compile();
  292. return getter();
  293. }
  294. protected override void ObjectToRow(TEntity obj, CoreRow row)
  295. {
  296. foreach (var column in Data.Columns)
  297. {
  298. var prop = DatabaseSchema.Property(obj.GetType(), column.ColumnName);
  299. if (prop is StandardProperty)
  300. row.Set(column.ColumnName, CoreUtils.GetPropertyValue(obj, prop.Name));
  301. else if (prop is CustomProperty)
  302. row.Set(column.ColumnName, obj.UserProperties[column.ColumnName]);
  303. }
  304. }
  305. public override void LoadEditorButtons(TEntity item, DynamicEditorButtons buttons)
  306. {
  307. base.LoadEditorButtons(item, buttons);
  308. if (ClientFactory.IsSupported<AuditTrail>())
  309. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  310. }
  311. private void AuditTrailClick(object sender, TEntity entity)
  312. {
  313. var window = new AuditWindow(entity.ID);
  314. window.ShowDialog();
  315. }
  316. protected override DynamicGridColumns LoadColumns()
  317. {
  318. return ColumnsComponent.LoadColumns();
  319. }
  320. protected override void SaveColumns(DynamicGridColumns columns)
  321. {
  322. ColumnsComponent.SaveColumns(columns);
  323. }
  324. protected override void LoadColumnsMenu(ContextMenu menu)
  325. {
  326. base.LoadColumnsMenu(menu);
  327. ColumnsComponent.LoadColumnsMenu(menu);
  328. }
  329. public string GetTag()
  330. {
  331. var tag = typeof(TEntity).Name;
  332. if (!string.IsNullOrWhiteSpace(ColumnsTag))
  333. tag = string.Format("{0}.{1}", tag, ColumnsTag);
  334. return tag;
  335. }
  336. protected override DynamicGridSettings LoadSettings()
  337. {
  338. var tag = GetTag();
  339. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  340. user.Wait();
  341. //var global = Task.Run(() => new GlobalConfiguration<DynamicGridSettings>(tag).Load());
  342. //global.Wait();
  343. //Task.WaitAll(user, global);
  344. //var columns = user.Result.Any() ? user.Result : global.Result;
  345. return user.Result;
  346. }
  347. protected override void SaveSettings(DynamicGridSettings settings)
  348. {
  349. var tag = GetTag();
  350. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  351. }
  352. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  353. {
  354. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == column.ColumnName);
  355. if (prop != null)
  356. return prop.Editor;
  357. return base.GetEditor(item, column);
  358. }
  359. protected override object? GetEditorValue(object item, string name)
  360. {
  361. if (item is TEntity entity)
  362. {
  363. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == name);
  364. if (prop is CustomProperty)
  365. {
  366. if (entity.UserProperties.ContainsKey(name))
  367. return entity.UserProperties[name];
  368. return null;
  369. }
  370. }
  371. return base.GetEditorValue(item, name);
  372. }
  373. protected override void SetEditorValue(object item, string name, object value)
  374. {
  375. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == name);
  376. if (prop is CustomProperty && item is TEntity entity)
  377. {
  378. entity.UserProperties[name] = value;
  379. }
  380. else
  381. {
  382. base.SetEditorValue(item, name, value);
  383. }
  384. }
  385. protected bool Duplicate(
  386. CoreRow row,
  387. Expression<Func<TEntity, object?>> codefield,
  388. Type[] childtypes)
  389. {
  390. var id = row.Get<TEntity, Guid>(x => x.ID);
  391. var code = row.Get(codefield) as string;
  392. var tasks = new List<Task>();
  393. var itemtask = Task.Run(() =>
  394. {
  395. var filter = new Filter<TEntity>(x => x.ID).IsEqualTo(id);
  396. var result = new Client<TEntity>().Load(filter).FirstOrDefault()
  397. ?? throw new Exception("Entity does not exist!");
  398. return result;
  399. });
  400. tasks.Add(itemtask);
  401. Task<List<string?>>? codetask = null;
  402. if (!string.IsNullOrWhiteSpace(code))
  403. {
  404. codetask = Task.Run(() =>
  405. {
  406. var columns = Columns.None<TEntity>().Add(codefield);
  407. //columns.Add<String>(codefield);
  408. var filter = new Filter<TEntity>(codefield).BeginsWith(code);
  409. var table = new Client<TEntity>().Query(filter, columns);
  410. var result = table.Rows.Select(x => x.Get(codefield) as string).ToList();
  411. return result;
  412. });
  413. tasks.Add(codetask);
  414. }
  415. var children = new Dictionary<Type, CoreTable>();
  416. foreach (var childtype in childtypes)
  417. {
  418. var childtask = Task.Run(() =>
  419. {
  420. var prop = childtype.GetProperties().FirstOrDefault(x =>
  421. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)) &&
  422. x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == typeof(TEntity));
  423. if (prop is not null)
  424. {
  425. var filter = Core.Filter.Create(childtype);
  426. filter.Expression = CoreUtils.GetMemberExpression(childtype, prop.Name + ".ID");
  427. filter.Operator = Operator.IsEqualTo;
  428. filter.Value = id;
  429. var sort = LookupFactory.DefineSort(childtype);
  430. var client = ClientFactory.CreateClient(childtype);
  431. var table = client.Query(filter, null, sort);
  432. foreach (var r in table.Rows)
  433. {
  434. r["ID"] = Guid.Empty;
  435. r[prop.Name + ".ID"] = Guid.Empty;
  436. }
  437. children[childtype] = table;
  438. }
  439. else
  440. {
  441. Logger.Send(LogType.Error, "", $"DynamicDataGrid<{typeof(TEntity)}>.Duplicate(): No parent property found for child type {childtype}");
  442. }
  443. });
  444. tasks.Add(childtask);
  445. }
  446. Task.WaitAll(tasks.ToArray());
  447. var item = itemtask.Result;
  448. item.ID = Guid.Empty;
  449. if (codetask != null)
  450. {
  451. var codes = codetask.Result;
  452. var i = 1;
  453. while (codes.Contains(string.Format("{0} ({1})", code, i)))
  454. i++;
  455. var codeprop = CoreUtils.GetFullPropertyName(codefield, ".");
  456. CoreUtils.SetPropertyValue(item, codeprop, string.Format("{0} ({1})", code, i));
  457. }
  458. var grid = new DynamicDataGrid<TEntity>();
  459. return grid.EditItems(new[] { item }, t => children.ContainsKey(t) ? children[t] : null, true);
  460. }
  461. private bool MergeClick(Button arg1, CoreRow[] rows)
  462. {
  463. if (rows == null || rows.Length <= 1)
  464. return false;
  465. return DoMerge(rows);
  466. }
  467. protected virtual bool DoMerge(CoreRow[] rows)
  468. {
  469. var targetid = rows.Last().Get<TEntity, Guid>(x => x.ID);
  470. var target = rows.Last().ToObject<TEntity>().ToString();
  471. var otherids = rows.Select(r => r.Get<TEntity, Guid>(x => x.ID)).Where(x => x != targetid).ToArray();
  472. string[] others = rows.Where(r => otherids.Contains(r.Get<Guid>("ID"))).Select(x => x.ToObject<TEntity>().ToString()!).ToArray();
  473. var nRows = rows.Length;
  474. if (!MessageWindow.ShowYesNo(
  475. $"This will merge the following items:\n\n" +
  476. $"- {string.Join("\n- ", others)}\n\n" +
  477. $" into:\n\n" +
  478. $"- {target}\n\n" +
  479. $"After this, the items will be permanently removed.\n" +
  480. $"Are you sure you wish to do this?",
  481. "Merge Items Warning"))
  482. return false;
  483. using (new WaitCursor())
  484. {
  485. var types = CoreUtils.Entities.Where(
  486. x =>
  487. !x.IsGenericType
  488. && x.IsSubclassOf(typeof(Entity))
  489. && !x.Equals(typeof(AuditTrail))
  490. && !x.Equals(typeof(TEntity))
  491. && x.GetCustomAttribute<AutoEntity>() == null
  492. && x.HasInterface<IRemotable>()
  493. && x.HasInterface<IPersistent>()
  494. ).ToArray();
  495. foreach (var type in types)
  496. {
  497. var props = CoreUtils.PropertyList(
  498. type,
  499. x =>
  500. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  501. && x.PropertyType.GetInheritedGenericTypeArguments().Contains(typeof(TEntity))
  502. );
  503. foreach (var prop in DatabaseSchema.LocalProperties(type))
  504. {
  505. if(prop.Parent is null
  506. || prop.Parent.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>)) is not Type intDef
  507. || intDef.GenericTypeArguments[0] != typeof(TEntity))
  508. {
  509. continue;
  510. }
  511. var filter = Filter.Create(type, prop.Name).InList(otherids);
  512. var columns = Columns.None(type).Add("ID").Add(prop.Name);
  513. var updates = ClientFactory.CreateClient(type).Query(filter, columns).Rows.ToArray(r => r.ToObject(type));
  514. if (updates.Length != 0)
  515. {
  516. foreach (var update in updates)
  517. prop.Setter()(update, targetid);
  518. ClientFactory.CreateClient(type).Save(updates, $"Merged {typeof(TEntity).Name} Records");
  519. }
  520. }
  521. }
  522. var histories = new Client<AuditTrail>()
  523. .Query(
  524. new Filter<AuditTrail>(x => x.EntityID).InList(otherids),
  525. Columns.None<AuditTrail>()
  526. .Add(x => x.ID).Add(x => x.EntityID))
  527. .ToArray<AuditTrail>();
  528. foreach (var history in histories)
  529. history.EntityID = targetid;
  530. if (histories.Length != 0)
  531. new Client<AuditTrail>().Save(histories, "");
  532. var deletes = new List<object>();
  533. foreach (var otherid in otherids)
  534. {
  535. var delete = new TEntity();
  536. CoreUtils.SetPropertyValue(delete, "ID", otherid);
  537. deletes.Add(delete);
  538. }
  539. ClientFactory.CreateClient(typeof(TEntity))
  540. .Delete(deletes, string.Format("Merged {0} Records", typeof(TEntity).EntityName().Split('.').Last()));
  541. return true;
  542. }
  543. }
  544. protected override IEnumerable<TEntity> LoadDuplicatorItems(CoreRow[] rows)
  545. {
  546. return rows.Select(x => x.ToObject<TEntity>());
  547. }
  548. protected override bool BeforePaste(IEnumerable<TEntity> items, ClipAction action)
  549. {
  550. if (action == ClipAction.Copy)
  551. {
  552. foreach (var item in items)
  553. item.ID = Guid.Empty;
  554. return true;
  555. }
  556. return base.BeforePaste(items, action);
  557. }
  558. protected override void CustomiseExportFilters(Filters<TEntity> filters, CoreRow[] visiblerows)
  559. {
  560. base.CustomiseExportFilters(filters, visiblerows);
  561. /*if (IsEntity)
  562. {
  563. var ids = visiblerows.Select(r => r.Get<TEntity, Guid>(c => c.ID)).ToArray();
  564. filters.Add(new Filter<TEntity>(x => x.ID).InList(ids));
  565. }
  566. else
  567. {
  568. Filter<TEntity>? filter = null;
  569. foreach (var row in visiblerows)
  570. {
  571. var rowFilter = GetRowFilter(row);
  572. if(rowFilter is not null)
  573. {
  574. if (filter is null)
  575. {
  576. filter = rowFilter;
  577. }
  578. else
  579. {
  580. filter.Or(rowFilter);
  581. }
  582. }
  583. }
  584. filters.Add(filter);
  585. }*/
  586. }
  587. protected override IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<TEntity> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  588. {
  589. var queries = new Dictionary<string, IQueryDef>();
  590. var columns = tableColumns.ToList();
  591. foreach (var table in columns)
  592. {
  593. var tableType = table.Item1;
  594. PropertyInfo? property = null;
  595. var m2m = CoreUtils.GetManyToMany(tableType, typeof(TEntity));
  596. IFilter? queryFilter = null;
  597. if (m2m != null)
  598. {
  599. property = CoreUtils.GetManyToManyThisProperty(tableType, typeof(TEntity));
  600. }
  601. else
  602. {
  603. var o2m = CoreUtils.GetOneToMany(tableType, typeof(TEntity));
  604. if (o2m != null)
  605. {
  606. property = CoreUtils.GetOneToManyProperty(tableType, typeof(TEntity));
  607. }
  608. }
  609. if (property != null)
  610. {
  611. var subQuery = new SubQuery<TEntity>();
  612. subQuery.Filter = filter.Combine();
  613. subQuery.Column = new Column<TEntity>(x => x.ID);
  614. queryFilter = (Activator.CreateInstance(typeof(Filter<>).MakeGenericType(tableType)) as IFilter)!;
  615. queryFilter.Expression = CoreUtils.GetMemberExpression(tableType, property.Name + ".ID");
  616. queryFilter.InQuery(subQuery);
  617. queries[tableType.Name] = new QueryDef(tableType)
  618. {
  619. Filter = queryFilter,
  620. Columns = table.Item2
  621. };
  622. }
  623. }
  624. var results = Client.QueryMultiple(queries);
  625. return columns.Select(x => new Tuple<Type?, CoreTable>(x.Item1, results[x.Item1.Name]));
  626. }
  627. protected override CoreTable LoadImportKeys(String[] fields)
  628. {
  629. return Client.Query(null, Columns.None<TEntity>().Add(fields));
  630. }
  631. }