DynamicDataGrid.cs 25 KB

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