DynamicManyToManyGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. public virtual bool Visible => Security.CanView<TManyToMany>();
  55. private static bool IsAutoEntity => typeof(TManyToMany).HasAttribute<AutoEntity>();
  56. protected DynamicGridCustomColumnsComponent<TManyToMany> ColumnsComponent;
  57. public HashSet<string>? LoadedColumns { get; set; }
  58. public DynamicManyToManyGrid()
  59. {
  60. MultiSelect = true;
  61. thisproperty = CoreUtils.GetManyToManyThisProperty(typeof(TManyToMany), typeof(TThis));
  62. otherproperty = CoreUtils.GetManyToManyOtherProperty(typeof(TManyToMany), typeof(TThis));
  63. HiddenColumns.Add(x => x.ID);
  64. HiddenColumns.Add(CoreUtils.CreateLambdaExpression<TManyToMany>(otherproperty.Name + ".ID"));
  65. ColumnsComponent = new DynamicGridCustomColumnsComponent<TManyToMany>(this, GetTag());
  66. }
  67. protected override void Init()
  68. {
  69. }
  70. protected override void DoReconfigure(DynamicGridOptions options)
  71. {
  72. options.RecordCount = true;
  73. options.SelectColumns = true;
  74. options.MultiSelect = true;
  75. if (Security.CanEdit<TManyToMany>() && !ReadOnly)
  76. {
  77. options.AddRows = true;
  78. options.EditRows = true;
  79. }
  80. if (Security.CanDelete<TManyToMany>() && !ReadOnly)
  81. options.DeleteRows = true;
  82. if (Security.CanImport<TManyToMany>() && !ReadOnly)
  83. options.ImportData = true;
  84. if (Security.CanExport<TManyToMany>())
  85. options.ExportData = true;
  86. if (Security.CanMerge<TManyToMany>())
  87. options.MultiSelect = true;
  88. }
  89. public bool MultiSelect { get; set; }
  90. public DynamicEditorGrid EditorGrid { get; set; }
  91. public string Caption()
  92. {
  93. //var m2m = typeof(TManyToMany).GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Contains(typeof(TThis)));
  94. //Type other = m2m.GenericTypeArguments.FirstOrDefault(x => x != typeof(TThis));
  95. //var serv = System.Data.Entity PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us"));
  96. //var plural = serv.Pluralize(source);
  97. //return MvcHtmlString.Create(plural);
  98. var result = new Inflector.Inflector(new CultureInfo("en")).Pluralize(OtherType().Name);
  99. return result;
  100. }
  101. public virtual int Order { get; set; } = int.MinValue;
  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. public void Cancel()
  302. {
  303. foreach(var item in MasterList)
  304. {
  305. item.CancelChanges();
  306. }
  307. WorkingList = MasterList.ToList();
  308. Refresh(false, true);
  309. }
  310. private void RefreshData(CoreTable data)
  311. {
  312. MasterList = data.ToArray<TManyToMany>();
  313. WorkingList = MasterList.ToList();
  314. Refresh(true, true);
  315. Ready = true;
  316. }
  317. protected override void Reload(
  318. Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany>? sort,
  319. CancellationToken token, Action<CoreTable?, Exception?> action)
  320. {
  321. var results = new CoreTable();
  322. results.LoadColumns(typeof(TManyToMany));
  323. this.EnsureColumns(columns);
  324. if (sort != null)
  325. {
  326. var exp = IQueryableExtensions.ToLambda<TManyToMany>(sort.Expression);
  327. var sorted = sort.Direction == SortDirection.Ascending
  328. ? WorkingList.AsQueryable().OrderBy(exp)
  329. : WorkingList.AsQueryable().OrderByDescending(exp);
  330. foreach (var then in sort.Thens)
  331. {
  332. var thexp = IQueryableExtensions.ToLambda<TManyToMany>(then.Expression);
  333. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  334. }
  335. WorkingList = sorted.ToList();
  336. }
  337. results.LoadRows(WorkingList);
  338. //results.LoadRows(WorkingList);
  339. action.Invoke(results, null);
  340. }
  341. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  342. {
  343. var type = CoreUtils.GetProperty(typeof(TManyToMany), column.ColumnName).DeclaringType;
  344. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TThis)))
  345. return new NullEditor();
  346. return base.GetEditor(item, column);
  347. }
  348. public override void LoadEditorButtons(TManyToMany item, DynamicEditorButtons buttons)
  349. {
  350. base.LoadEditorButtons(item, buttons);
  351. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  352. }
  353. private void AuditTrailClick(object sender, object? item)
  354. {
  355. if (item is not TManyToMany entity) return;
  356. var window = new AuditWindow(entity.ID);
  357. window.ShowDialog();
  358. }
  359. public override DynamicEditorPages LoadEditorPages(TManyToMany item)
  360. {
  361. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  362. }
  363. protected override bool BeforeCopy(IList<TManyToMany> items)
  364. {
  365. if (!base.BeforeCopy(items)) return false;
  366. for(int i = 0; i < items.Count; ++i)
  367. {
  368. var newItem = items[i].Clone();
  369. newItem.ID = Guid.Empty;
  370. items[i] = newItem;
  371. }
  372. return true;
  373. }
  374. }