DynamicManyToManyGrid.cs 13 KB

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