DynamicManyToManyGrid.cs 14 KB

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