DynamicManyToManyGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. protected override DynamicGridColumns LoadColumns()
  163. {
  164. return ColumnsComponent.LoadColumns();
  165. }
  166. protected override void SaveColumns(DynamicGridColumns columns)
  167. {
  168. ColumnsComponent.SaveColumns(columns);
  169. }
  170. protected override void LoadColumnsMenu(ContextMenu menu)
  171. {
  172. base.LoadColumnsMenu(menu);
  173. ColumnsComponent.LoadColumnsMenu(menu);
  174. }
  175. protected override DynamicGridSettings LoadSettings()
  176. {
  177. var tag = GetTag();
  178. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  179. user.Wait();
  180. //var global = Task.Run(() => new GlobalConfiguration<DynamicGridSettings>(tag).Load());
  181. //global.Wait();
  182. //Task.WaitAll(user, global);
  183. //var columns = user.Result.Any() ? user.Result : global.Result;
  184. return user.Result;
  185. }
  186. protected override void SaveSettings(DynamicGridSettings settings)
  187. {
  188. var tag = GetTag();
  189. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  190. }
  191. protected virtual Guid[] CurrentGuids()
  192. {
  193. var result = new List<Guid>();
  194. foreach (var item in WorkingList)
  195. {
  196. //var prop = GetOtherLink(item);
  197. var prop = GetThisLink(item);
  198. result.Add(prop.ID);
  199. }
  200. return result.ToArray();
  201. }
  202. protected virtual object GetFilter()
  203. {
  204. var result = LookupFactory.DefineFilter(OtherType(), typeof(TThis), new[] { (TThis)Item });
  205. var filtertype = typeof(Filter<>).MakeGenericType(OtherType());
  206. var filtermethod = filtertype.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(x =>
  207. x.Name.Equals("List") && x.GetParameters().Last().ParameterType.IsAssignableFrom(typeof(IEnumerable<Guid>))).First();
  208. var filterexpression = CoreUtils.GetPropertyExpression(OtherType(), "ID");
  209. var filtervalues = CurrentGuids();
  210. var filter = filtermethod.Invoke(null, new object[] { filterexpression, ListOperator.Excludes, filtervalues }) as IFilter;
  211. if (filter != null)
  212. {
  213. if (result != null)
  214. {
  215. filter.And(result);
  216. }
  217. return filter;
  218. }
  219. if (result != null) return result;
  220. return null;
  221. }
  222. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  223. {
  224. if (MultiSelect)
  225. {
  226. var filter = GetFilter();
  227. var dlgtype = typeof(MultiSelectDialog<>).MakeGenericType(OtherType());
  228. var dlg = (Activator.CreateInstance(dlgtype, filter, null, true) as IMultiSelectDialog)!;
  229. if (dlg.ShowDialog())
  230. {
  231. var guids = CurrentGuids();
  232. var items = dlgtype.GetMethod("Items").Invoke(dlg, new object[] { null }) as IEnumerable;
  233. foreach (var item in items)
  234. {
  235. var entity = item as Entity;
  236. if (!guids.Contains(entity.ID))
  237. {
  238. var newitem = CreateItem();
  239. var prop = GetOtherLink(newitem);
  240. prop.ID = entity.ID;
  241. prop.Synchronise(entity);
  242. SaveItem(newitem);
  243. }
  244. }
  245. Refresh(false, true);
  246. }
  247. }
  248. else
  249. {
  250. base.DoAdd();
  251. }
  252. }
  253. protected override TManyToMany CreateItem()
  254. {
  255. var result = new TManyToMany();
  256. if (Item != null)
  257. {
  258. var prop = GetThisLink(result);
  259. prop.ID = Item.ID;
  260. prop.Synchronise(Item);
  261. }
  262. return result;
  263. }
  264. protected override TManyToMany LoadItem(CoreRow row)
  265. {
  266. return WorkingList[_recordmap[row].Index];
  267. }
  268. public override void SaveItem(TManyToMany item)
  269. {
  270. if (!WorkingList.Contains(item))
  271. WorkingList.Add(item);
  272. }
  273. protected override void DeleteItems(params CoreRow[] rows)
  274. {
  275. foreach (var row in rows)
  276. {
  277. var id = row.Get<TManyToMany, Guid>(c => c.ID);
  278. var item = WorkingList.FirstOrDefault(x => x.ID.Equals(id));
  279. if (item != null)
  280. WorkingList.Remove(item);
  281. }
  282. }
  283. private void RefreshData(CoreTable data)
  284. {
  285. MasterList = data.Rows.Select(x => x.ToObject<TManyToMany>()).ToArray();
  286. WorkingList = MasterList.ToList();
  287. Refresh(true, true);
  288. Ready = true;
  289. }
  290. protected override void Reload(Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany>? sort,
  291. Action<CoreTable?, Exception?> action)
  292. {
  293. var results = new CoreTable();
  294. results.LoadColumns(typeof(TManyToMany));
  295. if (sort != null)
  296. {
  297. var exp = IQueryableExtensions.ToLambda<TManyToMany>(sort.Expression);
  298. var sorted = sort.Direction == SortDirection.Ascending
  299. ? WorkingList.AsQueryable().OrderBy(exp)
  300. : WorkingList.AsQueryable().OrderByDescending(exp);
  301. foreach (var then in sort.Thens)
  302. {
  303. var thexp = IQueryableExtensions.ToLambda<TManyToMany>(then.Expression);
  304. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  305. }
  306. WorkingList = sorted.ToList();
  307. }
  308. results.LoadRows(WorkingList);
  309. //results.LoadRows(WorkingList);
  310. action.Invoke(results, null);
  311. }
  312. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  313. {
  314. var type = CoreUtils.GetProperty(typeof(TManyToMany), column.ColumnName).DeclaringType;
  315. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TThis)))
  316. return new NullEditor();
  317. return base.GetEditor(item, column);
  318. }
  319. public override void LoadEditorButtons(TManyToMany item, DynamicEditorButtons buttons)
  320. {
  321. base.LoadEditorButtons(item, buttons);
  322. if (ClientFactory.IsSupported<AuditTrail>())
  323. buttons.Add("Audit Trail",Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  324. }
  325. private void AuditTrailClick(object sender, object item)
  326. {
  327. var entity = (TManyToMany)item;
  328. var window = new AuditWindow(entity.ID);
  329. window.ShowDialog();
  330. }
  331. public override DynamicEditorPages LoadEditorPages(TManyToMany item)
  332. {
  333. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  334. }
  335. protected override bool BeforePaste(IEnumerable<TManyToMany> items, ClipAction action)
  336. {
  337. if (action == ClipAction.Copy)
  338. {
  339. foreach (var item in items)
  340. {
  341. item.ID = Guid.Empty;
  342. }
  343. }
  344. return base.BeforePaste(items, action);
  345. }
  346. }
  347. }