DynamicDataGrid.cs 25 KB

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