DynamicDataGrid.cs 24 KB

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