DynamicDataGrid.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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(field));
  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 = rows.Select(x => x.ToObject<TEntity>()).ToArray();
  278. var deletes = new List<TEntity>();
  279. foreach (var row in rows)
  280. {
  281. var delete = new TEntity();
  282. foreach (var column in FilterColumns)
  283. {
  284. CoreUtils.SetPropertyValue(delete, column.Property, row[column.Property]);
  285. }
  286. deletes.Add(delete);
  287. }
  288. Client.Delete(deletes, "Deleted on User Request");
  289. DoChanged();
  290. }
  291. private object GetPropertyValue(Expression member, object obj)
  292. {
  293. var objectMember = Expression.Convert(member, typeof(object));
  294. var getterLambda = Expression.Lambda<Func<object>>(objectMember);
  295. var getter = getterLambda.Compile();
  296. return getter();
  297. }
  298. protected override void ObjectToRow(TEntity obj, CoreRow row)
  299. {
  300. foreach (var column in Data.Columns)
  301. {
  302. var prop = DatabaseSchema.Property(obj.GetType(), column.ColumnName);
  303. if (prop is StandardProperty)
  304. row.Set(column.ColumnName, CoreUtils.GetPropertyValue(obj, prop.Name));
  305. else if (prop is CustomProperty)
  306. row.Set(column.ColumnName, obj.UserProperties[column.ColumnName]);
  307. }
  308. }
  309. public override void LoadEditorButtons(TEntity item, DynamicEditorButtons buttons)
  310. {
  311. base.LoadEditorButtons(item, buttons);
  312. if (ClientFactory.IsSupported<AuditTrail>())
  313. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  314. }
  315. private void AuditTrailClick(object sender, TEntity entity)
  316. {
  317. var window = new AuditWindow(entity.ID);
  318. window.ShowDialog();
  319. }
  320. protected override DynamicGridColumns LoadColumns()
  321. {
  322. return ColumnsComponent.LoadColumns();
  323. }
  324. protected override void SaveColumns(DynamicGridColumns columns)
  325. {
  326. ColumnsComponent.SaveColumns(columns);
  327. }
  328. protected override void LoadColumnsMenu(ContextMenu menu)
  329. {
  330. base.LoadColumnsMenu(menu);
  331. ColumnsComponent.LoadColumnsMenu(menu);
  332. }
  333. public string GetTag()
  334. {
  335. var tag = typeof(TEntity).Name;
  336. if (!string.IsNullOrWhiteSpace(ColumnsTag))
  337. tag = string.Format("{0}.{1}", tag, ColumnsTag);
  338. return tag;
  339. }
  340. protected override DynamicGridSettings LoadSettings()
  341. {
  342. var tag = GetTag();
  343. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  344. user.Wait();
  345. //var global = Task.Run(() => new GlobalConfiguration<DynamicGridSettings>(tag).Load());
  346. //global.Wait();
  347. //Task.WaitAll(user, global);
  348. //var columns = user.Result.Any() ? user.Result : global.Result;
  349. return user.Result;
  350. }
  351. protected override void SaveSettings(DynamicGridSettings settings)
  352. {
  353. var tag = GetTag();
  354. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  355. }
  356. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  357. {
  358. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == column.ColumnName);
  359. if (prop != null)
  360. return prop.Editor;
  361. return base.GetEditor(item, column);
  362. }
  363. protected override object? GetEditorValue(object item, string name)
  364. {
  365. if (item is TEntity entity)
  366. {
  367. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == name);
  368. if (prop is CustomProperty)
  369. {
  370. if (entity.UserProperties.ContainsKey(name))
  371. return entity.UserProperties[name];
  372. return null;
  373. }
  374. }
  375. return base.GetEditorValue(item, name);
  376. }
  377. protected override void SetEditorValue(object item, string name, object value)
  378. {
  379. var prop = DatabaseSchema.Properties(typeof(TEntity)).FirstOrDefault(x => x.Name == name);
  380. if (prop is CustomProperty && item is TEntity entity)
  381. {
  382. entity.UserProperties[name] = value;
  383. }
  384. else
  385. {
  386. base.SetEditorValue(item, name, value);
  387. }
  388. }
  389. protected bool Duplicate(
  390. CoreRow row,
  391. Expression<Func<TEntity, object?>> codefield,
  392. Type[] childtypes)
  393. {
  394. var id = row.Get<TEntity, Guid>(x => x.ID);
  395. var code = row.Get(codefield) as string;
  396. var tasks = new List<Task>();
  397. var itemtask = Task.Run(() =>
  398. {
  399. var filter = new Filter<TEntity>(x => x.ID).IsEqualTo(id);
  400. var result = new Client<TEntity>().Load(filter).FirstOrDefault()
  401. ?? throw new Exception("Entity does not exist!");
  402. return result;
  403. });
  404. tasks.Add(itemtask);
  405. Task<List<string?>>? codetask = null;
  406. if (!string.IsNullOrWhiteSpace(code))
  407. {
  408. codetask = Task.Run(() =>
  409. {
  410. var columns = Columns.None<TEntity>().Add(codefield);
  411. //columns.Add<String>(codefield);
  412. var filter = new Filter<TEntity>(codefield).BeginsWith(code);
  413. var table = new Client<TEntity>().Query(filter, columns);
  414. var result = table.Rows.Select(x => x.Get(codefield) as string).ToList();
  415. return result;
  416. });
  417. tasks.Add(codetask);
  418. }
  419. var children = new Dictionary<Type, CoreTable>();
  420. foreach (var childtype in childtypes)
  421. {
  422. var childtask = Task.Run(() =>
  423. {
  424. var prop = childtype.GetProperties().FirstOrDefault(x =>
  425. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)) &&
  426. x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == typeof(TEntity));
  427. if (prop is not null)
  428. {
  429. var filter = Core.Filter.Create(childtype);
  430. filter.Property = prop.Name + ".ID";
  431. filter.Operator = Operator.IsEqualTo;
  432. filter.Value = id;
  433. var sort = LookupFactory.DefineSort(childtype);
  434. var client = ClientFactory.CreateClient(childtype);
  435. var table = client.Query(filter, null, sort);
  436. foreach (var r in table.Rows)
  437. {
  438. r["ID"] = Guid.Empty;
  439. r[prop.Name + ".ID"] = Guid.Empty;
  440. }
  441. children[childtype] = table;
  442. }
  443. else
  444. {
  445. Logger.Send(LogType.Error, "", $"DynamicDataGrid<{typeof(TEntity)}>.Duplicate(): No parent property found for child type {childtype}");
  446. }
  447. });
  448. tasks.Add(childtask);
  449. }
  450. Task.WaitAll(tasks.ToArray());
  451. var item = itemtask.Result;
  452. item.ID = Guid.Empty;
  453. if (codetask != null)
  454. {
  455. var codes = codetask.Result;
  456. var i = 1;
  457. while (codes.Contains(string.Format("{0} ({1})", code, i)))
  458. i++;
  459. var codeprop = CoreUtils.GetFullPropertyName(codefield, ".");
  460. CoreUtils.SetPropertyValue(item, codeprop, string.Format("{0} ({1})", code, i));
  461. }
  462. var grid = new DynamicDataGrid<TEntity>();
  463. return grid.EditItems(new[] { item }, t => children.ContainsKey(t) ? children[t] : null, true);
  464. }
  465. private bool MergeClick(Button arg1, CoreRow[] rows)
  466. {
  467. if (rows == null || rows.Length <= 1)
  468. return false;
  469. return DoMerge(rows);
  470. }
  471. protected virtual bool DoMerge(CoreRow[] rows)
  472. {
  473. var targetid = rows.Last().Get<TEntity, Guid>(x => x.ID);
  474. var target = rows.Last().ToObject<TEntity>().ToString();
  475. var otherids = rows.Select(r => r.Get<TEntity, Guid>(x => x.ID)).Where(x => x != targetid).ToArray();
  476. string[] others = rows.Where(r => otherids.Contains(r.Get<Guid>("ID"))).Select(x => x.ToObject<TEntity>().ToString()!).ToArray();
  477. var nRows = rows.Length;
  478. if (!MessageWindow.ShowYesNo(
  479. $"This will merge the following items:\n\n" +
  480. $"- {string.Join("\n- ", others)}\n\n" +
  481. $" into:\n\n" +
  482. $"- {target}\n\n" +
  483. $"After this, the items will be permanently removed.\n" +
  484. $"Are you sure you wish to do this?",
  485. "Merge Items Warning"))
  486. return false;
  487. using (new WaitCursor())
  488. {
  489. var types = CoreUtils.Entities.Where(
  490. x =>
  491. !x.IsGenericType
  492. && x.IsSubclassOf(typeof(Entity))
  493. && !x.Equals(typeof(AuditTrail))
  494. && !x.Equals(typeof(TEntity))
  495. && x.GetCustomAttribute<AutoEntity>() == null
  496. && x.HasInterface<IRemotable>()
  497. && x.HasInterface<IPersistent>()
  498. ).ToArray();
  499. foreach (var type in types)
  500. {
  501. var props = CoreUtils.PropertyList(
  502. type,
  503. x =>
  504. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  505. && x.PropertyType.GetInheritedGenericTypeArguments().Contains(typeof(TEntity))
  506. );
  507. foreach (var prop in DatabaseSchema.LocalProperties(type))
  508. {
  509. if(prop.Parent is null
  510. || prop.Parent.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>)) is not Type intDef
  511. || intDef.GenericTypeArguments[0] != typeof(TEntity))
  512. {
  513. continue;
  514. }
  515. var filter = Filter.Create(type, prop.Name).InList(otherids);
  516. var columns = Columns.None(type).Add("ID").Add(prop.Name);
  517. var updates = ClientFactory.CreateClient(type).Query(filter, columns).Rows.ToArray(r => r.ToObject(type));
  518. if (updates.Length != 0)
  519. {
  520. foreach (var update in updates)
  521. prop.Setter()(update, targetid);
  522. ClientFactory.CreateClient(type).Save(updates, $"Merged {typeof(TEntity).Name} Records");
  523. }
  524. }
  525. }
  526. var histories = new Client<AuditTrail>()
  527. .Query(
  528. new Filter<AuditTrail>(x => x.EntityID).InList(otherids),
  529. Columns.None<AuditTrail>()
  530. .Add(x => x.ID).Add(x => x.EntityID))
  531. .ToArray<AuditTrail>();
  532. foreach (var history in histories)
  533. history.EntityID = targetid;
  534. if (histories.Length != 0)
  535. new Client<AuditTrail>().Save(histories, "");
  536. var deletes = new List<object>();
  537. foreach (var otherid in otherids)
  538. {
  539. var delete = new TEntity();
  540. CoreUtils.SetPropertyValue(delete, "ID", otherid);
  541. deletes.Add(delete);
  542. }
  543. ClientFactory.CreateClient(typeof(TEntity))
  544. .Delete(deletes, string.Format("Merged {0} Records", typeof(TEntity).EntityName().Split('.').Last()));
  545. return true;
  546. }
  547. }
  548. protected override IEnumerable<TEntity> LoadDuplicatorItems(CoreRow[] rows)
  549. {
  550. return rows.Select(x => x.ToObject<TEntity>());
  551. }
  552. protected override bool BeforeCopy(IList<TEntity> items)
  553. {
  554. if (!base.BeforeCopy(items)) return false;
  555. for(int i = 0; i < items.Count; ++i)
  556. {
  557. var newItem = items[i].Clone();
  558. newItem.ID = Guid.Empty;
  559. items[i] = newItem;
  560. }
  561. return true;
  562. }
  563. protected override void CustomiseExportFilters(Filters<TEntity> filters, CoreRow[] visiblerows)
  564. {
  565. base.CustomiseExportFilters(filters, visiblerows);
  566. /*if (IsEntity)
  567. {
  568. var ids = visiblerows.Select(r => r.Get<TEntity, Guid>(c => c.ID)).ToArray();
  569. filters.Add(new Filter<TEntity>(x => x.ID).InList(ids));
  570. }
  571. else
  572. {
  573. Filter<TEntity>? filter = null;
  574. foreach (var row in visiblerows)
  575. {
  576. var rowFilter = GetRowFilter(row);
  577. if(rowFilter is not null)
  578. {
  579. if (filter is null)
  580. {
  581. filter = rowFilter;
  582. }
  583. else
  584. {
  585. filter.Or(rowFilter);
  586. }
  587. }
  588. }
  589. filters.Add(filter);
  590. }*/
  591. }
  592. protected override IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<TEntity> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  593. {
  594. var queries = new Dictionary<string, IQueryDef>();
  595. var columns = tableColumns.ToList();
  596. foreach (var table in columns)
  597. {
  598. var tableType = table.Item1;
  599. PropertyInfo? property = null;
  600. var m2m = CoreUtils.GetManyToMany(tableType, typeof(TEntity));
  601. IFilter? queryFilter = null;
  602. if (m2m != null)
  603. {
  604. property = CoreUtils.GetManyToManyThisProperty(tableType, typeof(TEntity));
  605. }
  606. else
  607. {
  608. var o2m = CoreUtils.GetOneToMany(tableType, typeof(TEntity));
  609. if (o2m != null)
  610. {
  611. property = CoreUtils.GetOneToManyProperty(tableType, typeof(TEntity));
  612. }
  613. }
  614. if (property != null)
  615. {
  616. var subQuery = new SubQuery<TEntity>();
  617. subQuery.Filter = filter.Combine();
  618. subQuery.Column = new Column<TEntity>(x => x.ID);
  619. queryFilter = (Activator.CreateInstance(typeof(Filter<>).MakeGenericType(tableType)) as IFilter)!;
  620. queryFilter.Property = property.Name + ".ID";
  621. queryFilter.InQuery(subQuery);
  622. queries[tableType.Name] = new QueryDef(tableType)
  623. {
  624. Filter = queryFilter,
  625. Columns = table.Item2
  626. };
  627. }
  628. }
  629. var results = Client.QueryMultiple(queries);
  630. return columns.Select(x => new Tuple<Type?, CoreTable>(x.Item1, results[x.Item1.Name]));
  631. }
  632. protected override CoreTable LoadImportKeys(String[] fields)
  633. {
  634. return Client.Query(null, Columns.None<TEntity>().Add(fields));
  635. }
  636. }