DynamicManyToManyGrid.cs 14 KB

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