DynamicManyToManyGrid.cs 14 KB

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