DynamicManyToManyGrid.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. CoreTable? data = null;
  92. if (PageDataHandler != null)
  93. data = PageDataHandler.Invoke(typeof(TManyToMany));
  94. if (data != null)
  95. {
  96. RefreshData(data);
  97. }
  98. else
  99. {
  100. if (Item.ID == Guid.Empty)
  101. {
  102. data = new CoreTable();
  103. data.LoadColumns(typeof(TManyToMany));
  104. RefreshData(data);
  105. }
  106. else
  107. {
  108. var exp = CoreUtils.GetPropertyExpression<TManyToMany>(thisproperty.Name + ".ID");
  109. var filter = new Filter<TManyToMany>(exp).IsEqualTo(Item.ID).And(exp).IsNotEqualTo(Guid.Empty);
  110. var sort = LookupFactory.DefineSort<TManyToMany>();
  111. new Client<TManyToMany>().Query(filter, null, sort, (o, e) => {
  112. if(o != null)
  113. {
  114. Dispatcher.Invoke(() => RefreshData(o));
  115. }
  116. else if(e != null)
  117. {
  118. Logger.Send(LogType.Information, ClientFactory.UserID, $"Unknown Error: {CoreUtils.FormatException(e)}");
  119. MessageBox.Show("An error occurred while loading data.");
  120. }
  121. });
  122. }
  123. }
  124. }
  125. public void BeforeSave(object item)
  126. {
  127. // Don't need to do anything here
  128. }
  129. public void AfterSave(object item)
  130. {
  131. // First remove any deleted files
  132. foreach (var map in MasterList)
  133. if (!WorkingList.Contains(map))
  134. new Client<TManyToMany>().Delete(map, typeof(TManyToMany).Name + " Deleted by User");
  135. foreach (var map in WorkingList)
  136. {
  137. var prop = (IEntityLink)thisproperty.GetValue(map);
  138. if (prop.ID != Item.ID)
  139. prop.ID = Item.ID;
  140. }
  141. if (WorkingList.Any(x => x.IsChanged()))
  142. new Client<TManyToMany>().Save(WorkingList.Where(x => x.IsChanged()), "Updated by User");
  143. }
  144. public Size MinimumSize()
  145. {
  146. return new Size(400, 400);
  147. }
  148. private Type OtherType() =>
  149. CoreUtils.GetManyToManyOtherType(typeof(TManyToMany), typeof(TThis));
  150. private string GetTag()
  151. {
  152. return typeof(TManyToMany).Name + "." + typeof(TThis).Name;
  153. }
  154. protected override DynamicGridColumns LoadColumns()
  155. {
  156. var tag = GetTag();
  157. var global = Task.Run(() => new GlobalConfiguration<DynamicGridColumns>(tag).Load());
  158. var user = Task.Run(() => new UserConfiguration<DynamicGridColumns>(tag).Load());
  159. Task.WaitAll(global, user);
  160. var columns = user.Result.Any() ? user.Result : global.Result;
  161. if (columns.Count == 0)
  162. columns.AddRange(base.LoadColumns().Where(x => !x.ColumnName.StartsWith(thisproperty.Name)));
  163. return columns;
  164. }
  165. protected override void SaveColumns(DynamicGridColumns columns)
  166. {
  167. var tag = GetTag();
  168. new UserConfiguration<DynamicGridColumns>(tag).Save(columns);
  169. }
  170. protected override DynamicGridSettings LoadSettings()
  171. {
  172. var tag = GetTag();
  173. var user = Task.Run(() => new UserConfiguration<DynamicGridSettings>(tag).Load());
  174. user.Wait();
  175. //var global = Task.Run(() => new GlobalConfiguration<DynamicGridSettings>(tag).Load());
  176. //global.Wait();
  177. //Task.WaitAll(user, global);
  178. //var columns = user.Result.Any() ? user.Result : global.Result;
  179. return user.Result;
  180. }
  181. protected override void SaveSettings(DynamicGridSettings settings)
  182. {
  183. var tag = GetTag();
  184. new UserConfiguration<DynamicGridSettings>(tag).Save(settings);
  185. }
  186. protected virtual Guid[] CurrentGuids()
  187. {
  188. var result = new List<Guid>();
  189. foreach (var item in WorkingList)
  190. {
  191. var prop = (IEntityLink)otherproperty.GetValue(item);
  192. result.Add(prop.ID);
  193. }
  194. return result.ToArray();
  195. }
  196. protected virtual object GetFilter()
  197. {
  198. var result = LookupFactory.DefineFilter(OtherType(), typeof(TThis), new[] { (TThis)Item }) as IFilter;
  199. var filtertype = typeof(Filter<>).MakeGenericType(OtherType());
  200. var filtermethod = filtertype.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(x =>
  201. x.Name.Equals("List") && x.GetParameters().Last().ParameterType.IsAssignableFrom(typeof(IEnumerable<Guid>))).First();
  202. var filterexpression = CoreUtils.GetPropertyExpression(OtherType(), "ID");
  203. var filtervalues = CurrentGuids();
  204. var filter = filtermethod.Invoke(null, new object[] { filterexpression, ListOperator.Excludes, filtervalues }) as IFilter;
  205. if (filter != null)
  206. {
  207. if (result != null)
  208. {
  209. filter.And(result);
  210. }
  211. return filter;
  212. }
  213. if (result != null) return result;
  214. return null;
  215. }
  216. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  217. {
  218. if (MultiSelect)
  219. {
  220. var filter = GetFilter();
  221. var dlgtype = typeof(MultiSelectDialog<>).MakeGenericType(OtherType());
  222. var dlg = Activator.CreateInstance(dlgtype, filter, null, true) as IMultiSelectDialog;
  223. if (dlg.ShowDialog())
  224. {
  225. var guids = CurrentGuids();
  226. var items = dlgtype.GetMethod("Items").Invoke(dlg, new object[] { null }) as IEnumerable;
  227. foreach (var item in items)
  228. {
  229. var entity = item as Entity;
  230. if (!guids.Contains(entity.ID))
  231. {
  232. var newitem = CreateItem();
  233. var prop = (IEntityLink)otherproperty.GetValue(newitem);
  234. prop.ID = entity.ID;
  235. prop.Synchronise(entity);
  236. SaveItem(newitem);
  237. }
  238. }
  239. Refresh(false, true);
  240. }
  241. }
  242. else
  243. {
  244. base.DoAdd();
  245. }
  246. }
  247. protected override TManyToMany CreateItem()
  248. {
  249. var result = new TManyToMany();
  250. if (Item != null)
  251. {
  252. var prop = (IEntityLink)thisproperty.GetValue(result);
  253. prop.ID = Item.ID;
  254. prop.Synchronise(Item);
  255. }
  256. return result;
  257. }
  258. protected override TManyToMany LoadItem(CoreRow row)
  259. {
  260. return WorkingList[_recordmap[row].Index];
  261. }
  262. public override void SaveItem(TManyToMany item)
  263. {
  264. if (!WorkingList.Contains(item))
  265. WorkingList.Add(item);
  266. }
  267. protected override void DeleteItems(params CoreRow[] rows)
  268. {
  269. foreach (var row in rows)
  270. {
  271. var id = row.Get<TManyToMany, Guid>(c => c.ID);
  272. var item = WorkingList.FirstOrDefault(x => x.ID.Equals(id));
  273. if (item != null)
  274. WorkingList.Remove(item);
  275. }
  276. }
  277. private void RefreshData(CoreTable data)
  278. {
  279. MasterList = data.Rows.Select(x => x.ToObject<TManyToMany>()).ToArray();
  280. WorkingList = MasterList.ToList();
  281. Refresh(true, true);
  282. Ready = true;
  283. }
  284. protected override void Reload(Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany>? sort,
  285. Action<CoreTable?, Exception?> action)
  286. {
  287. var results = new CoreTable();
  288. results.LoadColumns(typeof(TManyToMany));
  289. if (sort != null)
  290. {
  291. var exp = IQueryableExtensions.ToLambda<TManyToMany>(sort.Expression);
  292. var sorted = sort.Direction == SortDirection.Ascending
  293. ? WorkingList.AsQueryable().OrderBy(exp)
  294. : WorkingList.AsQueryable().OrderByDescending(exp);
  295. foreach (var then in sort.Thens)
  296. {
  297. var thexp = IQueryableExtensions.ToLambda<TManyToMany>(then.Expression);
  298. sorted = sort.Direction == SortDirection.Ascending ? sorted.ThenBy(exp) : sorted.ThenByDescending(exp);
  299. }
  300. WorkingList = sorted.ToList();
  301. }
  302. results.LoadRows(WorkingList);
  303. //results.LoadRows(WorkingList);
  304. action.Invoke(results, null);
  305. }
  306. protected override BaseEditor? GetEditor(object item, DynamicGridColumn column)
  307. {
  308. var type = CoreUtils.GetProperty(typeof(TManyToMany), column.ColumnName).DeclaringType;
  309. if (type.GetInterfaces().Contains(typeof(IEntityLink)) && type.ContainsInheritedGenericType(typeof(TThis)))
  310. return new NullEditor();
  311. return base.GetEditor(item, column);
  312. }
  313. public override void LoadEditorButtons(TManyToMany item, DynamicEditorButtons buttons)
  314. {
  315. base.LoadEditorButtons(item, buttons);
  316. if (ClientFactory.IsSupported<AuditTrail>())
  317. buttons.Add("Audit Trail",Wpf.Resources.view.AsBitmapImage(), item, AuditTrailClick);
  318. }
  319. private void AuditTrailClick(object sender, object item)
  320. {
  321. var entity = (TManyToMany)item;
  322. var window = new AuditWindow(entity.ID);
  323. window.ShowDialog();
  324. }
  325. public override DynamicEditorPages LoadEditorPages(TManyToMany item)
  326. {
  327. return item.ID != Guid.Empty ? base.LoadEditorPages(item) : new DynamicEditorPages();
  328. }
  329. protected override bool BeforePaste(IEnumerable<TManyToMany> items, ClipAction action)
  330. {
  331. if (action == ClipAction.Copy)
  332. {
  333. foreach (var item in items)
  334. {
  335. item.ID = Guid.Empty;
  336. }
  337. }
  338. return base.BeforePaste(items, action);
  339. }
  340. }
  341. }