DynamicManyToManyGrid.cs 14 KB

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