DynamicManyToManyGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 DoReconfigure(DynamicGridOptions options)
  68. {
  69. base.DoReconfigure(options);
  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 { get; set; } = int.MinValue;
  100. public bool Ready { get; set; }
  101. public void Load(object item, Func<Type, CoreTable?>? PageDataHandler)
  102. {
  103. Item = (TThis)item;
  104. var data = PageDataHandler?.Invoke(typeof(TManyToMany));
  105. if (data != null)
  106. {
  107. RefreshData(data);
  108. }
  109. else
  110. {
  111. if (Item.ID == Guid.Empty)
  112. {
  113. data = new CoreTable();
  114. data.LoadColumns(typeof(TManyToMany));
  115. RefreshData(data);
  116. }
  117. else
  118. {
  119. var exp = CoreUtils.GetPropertyExpression<TManyToMany>(thisproperty.Name + ".ID");
  120. var filter = new Filter<TManyToMany>(exp).IsEqualTo(Item.ID).And(exp).IsNotEqualTo(Guid.Empty);
  121. var sort = LookupFactory.DefineSort<TManyToMany>();
  122. var columns = DynamicGridUtils.LoadEditorColumns(DataColumns());
  123. Client.Query(filter, columns, sort, null, (o, e) =>
  124. {
  125. if (o != null)
  126. {
  127. LoadedColumns = columns.ColumnNames().ToHashSet();
  128. Dispatcher.Invoke(() => RefreshData(o));
  129. }
  130. else if(e != null)
  131. {
  132. Dispatcher.Invoke(() =>
  133. {
  134. MessageWindow.ShowError("An error occurred while loading data.", e);
  135. });
  136. }
  137. });
  138. }
  139. }
  140. }
  141. public void BeforeSave(object item)
  142. {
  143. // Don't need to do anything here
  144. }
  145. public void AfterSave(object item)
  146. {
  147. if (IsAutoEntity)
  148. {
  149. return;
  150. }
  151. // First remove any deleted files
  152. foreach (var map in MasterList)
  153. if (!WorkingList.Contains(map))
  154. Client.Delete(map, typeof(TManyToMany).Name + " Deleted by User");
  155. foreach (var map in WorkingList)
  156. {
  157. var prop = GetThisLink(map);
  158. if (prop.ID != Item.ID)
  159. prop.ID = Item.ID;
  160. }
  161. if (WorkingList.Any(x => x.IsChanged()))
  162. Client.Save(WorkingList.Where(x => x.IsChanged()), "Updated by User");
  163. MasterList = WorkingList.ToArray();
  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.DefineChildFilter(typeof(TThis), OtherType(), new[] { Item });
  224. var filter = Filter.Create(OtherType(), "ID").NotInList(CurrentGuids());
  225. if (filter != null)
  226. {
  227. if (result != null)
  228. {
  229. filter.And(result);
  230. }
  231. return filter;
  232. }
  233. if (result != null) return result;
  234. return null;
  235. }
  236. protected override void DoAdd(bool openEditorOnDirectEdit = false)
  237. {
  238. if (MultiSelect)
  239. {
  240. var filter = GetFilter();
  241. var dlgtype = typeof(MultiSelectDialog<>).MakeGenericType(OtherType());
  242. var columns = LookupFactory.DefineLookupColumns(typeof(TManyToMany), OtherType(), otherproperty.Name);
  243. var prefix = otherproperty.Name + ".";
  244. foreach(var column in DataColumns())
  245. {
  246. if(column.Property.StartsWith(prefix))
  247. {
  248. columns.Add(column.Property[prefix.Length..]);
  249. }
  250. }
  251. var dlg = (Activator.CreateInstance(dlgtype, filter, columns, true) as IMultiSelectDialog)!;
  252. if (dlg.ShowDialog())
  253. {
  254. var guids = CurrentGuids();
  255. foreach (var entity in dlg.Data().ToObjects(OtherType()).Cast<Entity>())
  256. {
  257. if (!guids.Contains(entity.ID))
  258. {
  259. var newitem = CreateItem();
  260. var prop = GetOtherLink(newitem);
  261. prop.ID = entity.ID;
  262. prop.Synchronise(entity);
  263. SaveItem(newitem);
  264. }
  265. }
  266. Refresh(false, true);
  267. }
  268. }
  269. else
  270. {
  271. base.DoAdd();
  272. }
  273. }
  274. public override TManyToMany CreateItem()
  275. {
  276. var result = new TManyToMany();
  277. if (Item != null)
  278. {
  279. var prop = GetThisLink(result);
  280. prop.ID = Item.ID;
  281. prop.Synchronise(Item);
  282. }
  283. return result;
  284. }
  285. public override TManyToMany LoadItem(CoreRow row)
  286. {
  287. return WorkingList[_recordmap[row].Index];
  288. }
  289. public override void SaveItem(TManyToMany item)
  290. {
  291. if (!WorkingList.Contains(item))
  292. WorkingList.Add(item);
  293. }
  294. public override void DeleteItems(params CoreRow[] rows)
  295. {
  296. foreach (var row in rows)
  297. {
  298. var id = row.Get<TManyToMany, Guid>(c => c.ID);
  299. var item = WorkingList.FirstOrDefault(x => x.ID.Equals(id));
  300. if (item != null)
  301. WorkingList.Remove(item);
  302. }
  303. }
  304. public void Cancel()
  305. {
  306. foreach(var item in MasterList)
  307. {
  308. item.CancelChanges();
  309. }
  310. WorkingList = MasterList.ToList();
  311. Refresh(false, true);
  312. }
  313. private void RefreshData(CoreTable data)
  314. {
  315. MasterList = data.ToArray<TManyToMany>();
  316. WorkingList = MasterList.ToList();
  317. Refresh(true, true);
  318. Ready = true;
  319. }
  320. protected override void Reload(
  321. Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany>? sort,
  322. CancellationToken token, Action<CoreTable?, Exception?> action)
  323. {
  324. var results = new CoreTable();
  325. results.LoadColumns(typeof(TManyToMany));
  326. this.EnsureColumns(columns);
  327. if (sort != null)
  328. {
  329. var exp = IQueryableExtensions.ToLambda<TManyToMany>(sort.Expression);
  330. var sorted = sort.Direction == SortDirection.Ascending
  331. ? WorkingList.AsQueryable().OrderBy(exp)
  332. : WorkingList.AsQueryable().OrderByDescending(exp);
  333. foreach (var then in sort.Thens)
  334. {
  335. var thexp = IQueryableExtensions.ToLambda<TManyToMany>(then.Expression);
  336. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  337. }
  338. WorkingList = sorted.ToList();
  339. }
  340. results.LoadRows(WorkingList);
  341. //results.LoadRows(WorkingList);
  342. action.Invoke(results, null);
  343. }
  344. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  345. {
  346. var type = CoreUtils.GetProperty(typeof(TManyToMany), column.ColumnName).DeclaringType;
  347. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TThis)))
  348. return new NullEditor();
  349. return base.GetEditor(item, column);
  350. }
  351. public override void LoadEditorButtons(TManyToMany item, DynamicEditorButtons buttons)
  352. {
  353. base.LoadEditorButtons(item, buttons);
  354. buttons.Add("Audit Trail", Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  355. }
  356. private void AuditTrailClick(object sender, object? item)
  357. {
  358. if (item is not TManyToMany entity) return;
  359. var window = new AuditWindow(entity.ID);
  360. window.ShowDialog();
  361. }
  362. public override DynamicEditorPages LoadEditorPages(TManyToMany item)
  363. {
  364. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  365. }
  366. protected override bool BeforeCopy(IList<TManyToMany> items)
  367. {
  368. if (!base.BeforeCopy(items)) return false;
  369. for(int i = 0; i < items.Count; ++i)
  370. {
  371. var newItem = items[i].Clone();
  372. newItem.ID = Guid.Empty;
  373. items[i] = newItem;
  374. }
  375. return true;
  376. }
  377. }