DynamicManyToManyGrid.cs 13 KB

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