DynamicManyToManyGrid.cs 15 KB

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