DynamicDataGrid.cs 25 KB

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