DynamicManyToManyGrid.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using InABox.Clients;
  11. using InABox.Configuration;
  12. using InABox.Core;
  13. using InABox.Wpf;
  14. using InABox.WPF;
  15. namespace InABox.DynamicGrid;
  16. public interface IDynamicManyToManyGrid<TManyToMany, TThis> : IDynamicEditorPage
  17. {
  18. }
  19. public class DynamicManyToManyGrid<TManyToMany, TThis> : DynamicGrid<TManyToMany>, IDynamicEditorPage, IDynamicManyToManyGrid<TManyToMany, TThis>
  20. where TThis : Entity, new()
  21. where TManyToMany : Entity, IPersistent, IRemotable, new()
  22. {
  23. //private Guid ID = Guid.Empty;
  24. protected TThis Item;
  25. /// <summary>
  26. /// Keeps a cache of initially loaded objects, so that we can figure out which guys to delete when we save.
  27. /// </summary>
  28. private TManyToMany[] MasterList = Array.Empty<TManyToMany>();
  29. protected PropertyInfo otherproperty;
  30. protected IEntityLink GetOtherLink(TManyToMany item) => (otherproperty.GetValue(item) as IEntityLink)!;
  31. protected PropertyInfo thisproperty;
  32. protected IEntityLink GetThisLink(TManyToMany item) => (thisproperty.GetValue(item) as IEntityLink)!;
  33. protected List<TManyToMany> WorkingList = new();
  34. public PageType PageType => PageType.Other;
  35. private bool _readOnly;
  36. public bool ReadOnly
  37. {
  38. get => _readOnly;
  39. set
  40. {
  41. if(_readOnly != value)
  42. {
  43. _readOnly = value;
  44. Reconfigure();
  45. }
  46. }
  47. }
  48. private static bool IsAutoEntity => typeof(TManyToMany).HasAttribute<AutoEntity>();
  49. protected DynamicGridCustomColumnsComponent<TManyToMany> ColumnsComponent;
  50. /// <summary>
  51. /// A set of columns representing which columns have been loaded from the database.
  52. /// </summary>
  53. /// <remarks>
  54. /// This is used to refresh the data when the columns change.<br/>
  55. ///
  56. /// It is <see langword="null"/> if no data has been loaded from the database (that is, the data was gotten from
  57. /// a page data handler instead.)
  58. /// </remarks>
  59. private HashSet<string>? LoadedColumns;
  60. public DynamicManyToManyGrid()
  61. {
  62. MultiSelect = true;
  63. thisproperty = CoreUtils.GetManyToManyThisProperty(typeof(TManyToMany), typeof(TThis));
  64. otherproperty = CoreUtils.GetManyToManyOtherProperty(typeof(TManyToMany), typeof(TThis));
  65. HiddenColumns.Add(x => x.ID);
  66. HiddenColumns.Add(CoreUtils.CreateLambdaExpression<TManyToMany>(otherproperty.Name + ".ID"));
  67. ColumnsComponent = new DynamicGridCustomColumnsComponent<TManyToMany>(this, GetTag());
  68. }
  69. protected override void Init()
  70. {
  71. }
  72. protected override void DoReconfigure(FluentList<DynamicGridOption> options)
  73. {
  74. options.BeginUpdate();
  75. options.Add(DynamicGridOption.RecordCount)
  76. .Add(DynamicGridOption.SelectColumns)
  77. .Add(DynamicGridOption.MultiSelect);
  78. if (Security.CanEdit<TManyToMany>() && !ReadOnly)
  79. options.Add(DynamicGridOption.AddRows).Add(DynamicGridOption.EditRows);
  80. if (Security.CanDelete<TManyToMany>() && !ReadOnly)
  81. options.Add(DynamicGridOption.DeleteRows);
  82. if (Security.CanImport<TManyToMany>() && !ReadOnly)
  83. options.Add(DynamicGridOption.ImportData);
  84. if (Security.CanExport<TManyToMany>())
  85. options.Add(DynamicGridOption.ExportData);
  86. if (Security.CanMerge<TManyToMany>())
  87. options.Add(DynamicGridOption.MultiSelect);
  88. options.EndUpdate();
  89. }
  90. public bool MultiSelect { get; set; }
  91. public DynamicEditorGrid EditorGrid { get; set; }
  92. public string Caption()
  93. {
  94. //var m2m = typeof(TManyToMany).GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Contains(typeof(TThis)));
  95. //Type other = m2m.GenericTypeArguments.FirstOrDefault(x => x != typeof(TThis));
  96. //var serv = System.Data.Entity PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us"));
  97. //var plural = serv.Pluralize(source);
  98. //return MvcHtmlString.Create(plural);
  99. var result = new Inflector.Inflector(new CultureInfo("en")).Pluralize(OtherType().Name);
  100. return result;
  101. }
  102. public virtual int Order()
  103. {
  104. return int.MinValue;
  105. }
  106. public bool Ready { get; set; }
  107. public void Load(object item, Func<Type, CoreTable?>? PageDataHandler)
  108. {
  109. Item = (TThis)item;
  110. var data = PageDataHandler?.Invoke(typeof(TManyToMany));
  111. if (data != null)
  112. {
  113. RefreshData(data);
  114. }
  115. else
  116. {
  117. if (Item.ID == Guid.Empty)
  118. {
  119. data = new CoreTable();
  120. data.LoadColumns(typeof(TManyToMany));
  121. RefreshData(data);
  122. }
  123. else
  124. {
  125. var exp = CoreUtils.GetPropertyExpression<TManyToMany>(thisproperty.Name + ".ID");
  126. var filter = new Filter<TManyToMany>(exp).IsEqualTo(Item.ID).And(exp).IsNotEqualTo(Guid.Empty);
  127. var sort = LookupFactory.DefineSort<TManyToMany>();
  128. var columns = DynamicGridUtils.LoadEditorColumns(DataColumns());
  129. Client.Query(filter, columns, sort, (o, e) =>
  130. {
  131. if (o != null)
  132. {
  133. LoadedColumns = columns.ColumnNames().ToHashSet();
  134. Dispatcher.Invoke(() => RefreshData(o));
  135. }
  136. else if(e != null)
  137. {
  138. Dispatcher.Invoke(() =>
  139. {
  140. MessageWindow.ShowError("An error occurred while loading data.", e);
  141. });
  142. }
  143. });
  144. }
  145. }
  146. }
  147. public void BeforeSave(object item)
  148. {
  149. // Don't need to do anything here
  150. }
  151. public void AfterSave(object item)
  152. {
  153. if (IsAutoEntity)
  154. {
  155. return;
  156. }
  157. // First remove any deleted files
  158. foreach (var map in MasterList)
  159. if (!WorkingList.Contains(map))
  160. Client.Delete(map, typeof(TManyToMany).Name + " Deleted by User");
  161. foreach (var map in WorkingList)
  162. {
  163. var prop = GetThisLink(map);
  164. if (prop.ID != Item.ID)
  165. prop.ID = Item.ID;
  166. }
  167. if (WorkingList.Any(x => x.IsChanged()))
  168. Client.Save(WorkingList.Where(x => x.IsChanged()), "Updated by User");
  169. }
  170. public Size MinimumSize()
  171. {
  172. return new Size(400, 400);
  173. }
  174. private static Type OtherType() =>
  175. CoreUtils.GetManyToManyOtherType(typeof(TManyToMany), typeof(TThis));
  176. private static string GetTag()
  177. {
  178. return typeof(TManyToMany).Name + "." + typeof(TThis).Name;
  179. }
  180. public override DynamicGridColumns GenerateColumns()
  181. {
  182. var cols = new DynamicGridColumns();
  183. cols.AddRange(base.GenerateColumns().Where(x => !x.ColumnName.StartsWith(thisproperty.Name + ".")));
  184. return cols;
  185. }
  186. protected override DynamicGridColumns LoadColumns()
  187. {
  188. return ColumnsComponent.LoadColumns();
  189. }
  190. protected override void SaveColumns(DynamicGridColumns columns)
  191. {
  192. ColumnsComponent.SaveColumns(columns);
  193. }
  194. protected override void LoadColumnsMenu(ContextMenu menu)
  195. {
  196. base.LoadColumnsMenu(menu);
  197. ColumnsComponent.LoadColumnsMenu(menu);
  198. }
  199. protected override DynamicGridSettings LoadSettings()
  200. {
  201. var tag = GetTag();
  202. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  203. user.Wait();
  204. //var global = Task.Run(() => new GlobalConfiguration<DynamicGridSettings>(tag).Load());
  205. //global.Wait();
  206. //Task.WaitAll(user, global);
  207. //var columns = user.Result.Any() ? user.Result : global.Result;
  208. return user.Result;
  209. }
  210. protected override void SaveSettings(DynamicGridSettings settings)
  211. {
  212. var tag = GetTag();
  213. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  214. }
  215. protected virtual Guid[] CurrentGuids()
  216. {
  217. var result = new List<Guid>();
  218. foreach (var item in WorkingList)
  219. {
  220. //var prop = GetOtherLink(item);
  221. var prop = GetThisLink(item);
  222. result.Add(prop.ID);
  223. }
  224. return result.ToArray();
  225. }
  226. protected virtual IFilter? GetFilter()
  227. {
  228. var result = LookupFactory.DefineFilter(OtherType(), typeof(TThis), new[] { (TThis)Item });
  229. var filtertype = typeof(Filter<>).MakeGenericType(OtherType());
  230. var filtermethod = filtertype.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(x =>
  231. x.Name.Equals("List") && x.GetParameters().Last().ParameterType.IsAssignableFrom(typeof(IEnumerable<Guid>))).First();
  232. var filterexpression = CoreUtils.GetPropertyExpression(OtherType(), "ID");
  233. var filtervalues = CurrentGuids();
  234. var filter = filtermethod.Invoke(null, new object[] { filterexpression, ListOperator.Excludes, filtervalues }) as IFilter;
  235. if (filter != null)
  236. {
  237. if (result != null)
  238. {
  239. filter.And(result);
  240. }
  241. return filter;
  242. }
  243. if (result != null) return result;
  244. return null;
  245. }
  246. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  247. {
  248. if (MultiSelect)
  249. {
  250. var filter = GetFilter();
  251. var dlgtype = typeof(MultiSelectDialog<>).MakeGenericType(OtherType());
  252. var dlg = (Activator.CreateInstance(dlgtype, filter, null, true) as IMultiSelectDialog)!;
  253. if (dlg.ShowDialog())
  254. {
  255. var guids = CurrentGuids();
  256. foreach (var entity in dlg.Items(null))
  257. {
  258. if (!guids.Contains(entity.ID))
  259. {
  260. var newitem = CreateItem();
  261. var prop = GetOtherLink(newitem);
  262. prop.ID = entity.ID;
  263. prop.Synchronise(entity);
  264. SaveItem(newitem);
  265. }
  266. }
  267. Refresh(false, true);
  268. }
  269. }
  270. else
  271. {
  272. base.DoAdd();
  273. }
  274. }
  275. protected override TManyToMany CreateItem()
  276. {
  277. var result = new TManyToMany();
  278. if (Item != null)
  279. {
  280. var prop = GetThisLink(result);
  281. prop.ID = Item.ID;
  282. prop.Synchronise(Item);
  283. }
  284. return result;
  285. }
  286. protected override TManyToMany LoadItem(CoreRow row)
  287. {
  288. return WorkingList[_recordmap[row].Index];
  289. }
  290. public override void SaveItem(TManyToMany item)
  291. {
  292. if (!WorkingList.Contains(item))
  293. WorkingList.Add(item);
  294. }
  295. protected override void DeleteItems(params CoreRow[] rows)
  296. {
  297. foreach (var row in rows)
  298. {
  299. var id = row.Get<TManyToMany, Guid>(c => c.ID);
  300. var item = WorkingList.FirstOrDefault(x => x.ID.Equals(id));
  301. if (item != null)
  302. WorkingList.Remove(item);
  303. }
  304. }
  305. private void RefreshData(CoreTable data)
  306. {
  307. MasterList = data.ToArray<TManyToMany>();
  308. WorkingList = MasterList.ToList();
  309. Refresh(true, true);
  310. Ready = true;
  311. }
  312. protected override void Reload(Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany>? sort,
  313. Action<CoreTable?, Exception?> action)
  314. {
  315. var results = new CoreTable();
  316. results.LoadColumns(typeof(TManyToMany));
  317. if (LoadedColumns is not null)
  318. {
  319. // Figure out which columns we still need.
  320. var newColumns = columns.Where(x => !LoadedColumns.Contains(x.Property)).ToColumns();
  321. if (newColumns.Any() && typeof(TManyToMany).GetCustomAttribute<AutoEntity>() is null)
  322. {
  323. var data = Client.Query(
  324. new Filter<TManyToMany>(x => x.ID).InList(WorkingList.Select(x => x.ID).Where(x => x != Guid.Empty).ToArray()),
  325. // We also need to add ID, so we know which item to fill.
  326. newColumns.Add(x => x.ID));
  327. foreach (var row in data.Rows)
  328. {
  329. var item = WorkingList.FirstOrDefault(x => x.ID == row.Get<TManyToMany, Guid>(y => y.ID));
  330. if (item is not null)
  331. {
  332. row.FillObject(item, overrideExisting: false);
  333. }
  334. }
  335. // Remember that we have now loaded this data.
  336. foreach (var column in newColumns)
  337. {
  338. LoadedColumns.Add(column.Property);
  339. }
  340. }
  341. }
  342. if (sort != null)
  343. {
  344. var exp = IQueryableExtensions.ToLambda<TManyToMany>(sort.Expression);
  345. var sorted = sort.Direction == SortDirection.Ascending
  346. ? WorkingList.AsQueryable().OrderBy(exp)
  347. : WorkingList.AsQueryable().OrderByDescending(exp);
  348. foreach (var then in sort.Thens)
  349. {
  350. var thexp = IQueryableExtensions.ToLambda<TManyToMany>(then.Expression);
  351. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  352. }
  353. WorkingList = sorted.ToList();
  354. }
  355. results.LoadRows(WorkingList);
  356. //results.LoadRows(WorkingList);
  357. action.Invoke(results, null);
  358. }
  359. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  360. {
  361. var type = CoreUtils.GetProperty(typeof(TManyToMany), column.ColumnName).DeclaringType;
  362. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TThis)))
  363. return new NullEditor();
  364. return base.GetEditor(item, column);
  365. }
  366. public override void LoadEditorButtons(TManyToMany item, DynamicEditorButtons buttons)
  367. {
  368. base.LoadEditorButtons(item, buttons);
  369. if (ClientFactory.IsSupported<AuditTrail>())
  370. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  371. }
  372. private void AuditTrailClick(object sender, object? item)
  373. {
  374. if (item is not TManyToMany entity) return;
  375. var window = new AuditWindow(entity.ID);
  376. window.ShowDialog();
  377. }
  378. public override DynamicEditorPages LoadEditorPages(TManyToMany item)
  379. {
  380. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  381. }
  382. protected override bool BeforePaste(IEnumerable<TManyToMany> items, ClipAction action)
  383. {
  384. if (action == ClipAction.Copy)
  385. {
  386. foreach (var item in items)
  387. {
  388. item.ID = Guid.Empty;
  389. }
  390. }
  391. return base.BeforePaste(items, action);
  392. }
  393. }