DynamicManyToManyGrid.cs 13 KB

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