DynamicGridUtils.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  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.Core;
  12. using InABox.Wpf;
  13. using InABox.Core.Reports;
  14. using Syncfusion.Data.Extensions;
  15. using System.Diagnostics.CodeAnalysis;
  16. using System.Data;
  17. using System.Windows.Media;
  18. using AutoProperties;
  19. using InABox.WPF;
  20. namespace InABox.DynamicGrid;
  21. [Caption("Set Default Column Selections")]
  22. public class CanSetDefaultColumns : EnabledSecurityDescriptor<CoreLicense>
  23. {
  24. }
  25. [LibraryInitializer]
  26. public static class DynamicGridUtils
  27. {
  28. private static IEnumerable<Type>? _allm2mtypes;
  29. private static IEnumerable<Type>? _allm2mpages;
  30. private static IEnumerable<Type>? _allo2mtypes;
  31. private static IEnumerable<Type>? _allo2mpages;
  32. private static IEnumerable<Type>? _allcepages;
  33. private static IEnumerable<Type>? _alleltypes;
  34. private static Dictionary<Type, IList<Type>> _onetomanypages = new();
  35. private static Dictionary<Type, IList<Type>> _manytomanytomanypages = new();
  36. private static Dictionary<Type, IList<Tuple<Type, PropertyInfo>>> _enclosedlistpages = new();
  37. private static Dictionary<Type, IList<Type>> _customeditorpages = new();
  38. // HACK: These are really dumb
  39. public static Action<ReportTemplate, DataModel>? PreviewReport { get; set; }
  40. public static Action<FrameworkElement?, string, DataModel, bool>? PrintMenu { get; set; }
  41. public static readonly MainResources Resources = new();
  42. public static void RegisterClasses()
  43. {
  44. // String assyname = "_" + Assembly.GetExecutingAssembly().GetName().Name;
  45. // AssemblyName assemblyName = new AssemblyName(assyname);
  46. // AppDomain appDomain = Thread.GetDomain();
  47. //
  48. // String assyFile = String.Format("{0}.dll", assemblyName.Name);
  49. // String path = "";
  50. // if (Assembly.GetEntryAssembly() != null)
  51. // {
  52. // path = Path.Combine(
  53. // Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  54. // Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  55. // );
  56. // }
  57. // else
  58. // {
  59. // path = Path.Combine(
  60. // Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  61. // Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location)
  62. // );
  63. // }
  64. //
  65. // if (!Directory.Exists(path))
  66. // Directory.CreateDirectory(path);
  67. // AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, path);
  68. //
  69. // ModuleBuilder module = assemblyBuilder.DefineDynamicModule(assyFile); //,true);
  70. //
  71. // if (_allm2mtypes == null)
  72. // {
  73. // _allm2mtypes = CoreUtils.TypeList(
  74. // AppDomain.CurrentDomain.GetAssemblies(),
  75. // x => x.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>))
  76. // );
  77. // }
  78. //
  79. // var maps = _allm2mtypes.Where(x => x.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Last().Equals(typeof(Document))));
  80. //
  81. // foreach (var map in maps)
  82. // {
  83. // var intf = map.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Last().Equals(typeof(Document)));
  84. // Type entity = intf.GenericTypeArguments.First();
  85. // Type basetype = typeof(DynamicDocumentGrid<,>).MakeGenericType(map, entity);
  86. // TypeBuilder tbService = module.DefineType(String.Format("{0}", map.EntityName().Replace(".", "_")), TypeAttributes.Public | TypeAttributes.Class);
  87. // tbService.SetParent(basetype);
  88. // Type final = tbService.CreateType();
  89. // }
  90. //
  91. // try
  92. // {
  93. // assemblyBuilder.Save(assyFile);
  94. // }
  95. // catch (Exception e)
  96. // {
  97. // Logger.Send(LogType.Error, "", String.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  98. // }
  99. }
  100. #region Pages
  101. public static IEnumerable<Type> GetManyToManyTypes(Type type)
  102. {
  103. _allm2mtypes ??= CoreUtils.Entities.Where(x => x.HasInterface(typeof(IManyToMany<,>))).ToArray();
  104. return _allm2mtypes.Where(x => x.GetInterfaces().Any(
  105. i => i.IsGenericType
  106. && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  107. && i.GenericTypeArguments[0] == type)
  108. );
  109. }
  110. public static void LoadManyToManyPages(Type type, DynamicEditorPages pages)
  111. {
  112. if (!_manytomanytomanypages.TryGetValue(type, out var pageTypes))
  113. {
  114. pageTypes = new List<Type>();
  115. var maps = GetManyToManyTypes(type);
  116. foreach (var map in maps)
  117. {
  118. if (ClientFactory.IsSupported(map))
  119. {
  120. _allm2mpages ??= CoreUtils.Entities.Where(
  121. x => x.IsClass
  122. && !x.IsGenericType
  123. && x.HasInterface(typeof(IDynamicManyToManyGrid<,>)))
  124. .ToArray();
  125. var subtypes = _allm2mpages.Where(
  126. x => x.GetInterfaces().Any(i =>
  127. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDynamicManyToManyGrid<,>) &&
  128. i.GenericTypeArguments.First().Equals(map) && i.GenericTypeArguments.Last().Equals(type))
  129. );
  130. if (subtypes.Any())
  131. {
  132. pageTypes.Add(subtypes.First());
  133. }
  134. else
  135. {
  136. pageTypes.Add(typeof(DynamicManyToManyGrid<,>).MakeGenericType(map, type));
  137. }
  138. }
  139. }
  140. _manytomanytomanypages[type] = pageTypes.ToArray();
  141. }
  142. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  143. }
  144. public static IEnumerable<Type> GetOneToManyTypes(Type type)
  145. {
  146. _allo2mtypes ??= CoreUtils.Entities.Where(
  147. x => x.HasInterface(typeof(IOneToMany<>)) && !x.HasAttribute<ObsoleteAttribute>())
  148. .ToArray();
  149. return _allo2mtypes
  150. .Where(x => x.GetInterfaces().Any(i =>
  151. i.IsGenericType
  152. && i.GetGenericTypeDefinition() == typeof(IOneToMany<>)
  153. && i.GenericTypeArguments.Contains(type)))
  154. .OrderBy(x => x.EntityName());
  155. }
  156. public static void LoadOneToManyPages(Type type, DynamicEditorPages pages)
  157. {
  158. if (!_onetomanypages.TryGetValue(type, out var pageTypes))
  159. {
  160. pageTypes = new List<Type>();
  161. var maps = GetOneToManyTypes(type);
  162. foreach (var map in maps)
  163. {
  164. if (ClientFactory.IsSupported(map))
  165. {
  166. _allo2mpages ??= CoreUtils.Entities.Where(
  167. x =>
  168. x.IsClass
  169. && !x.IsGenericType
  170. && x.HasInterface(typeof(IDynamicOneToManyGrid<,>))
  171. && !x.HasInterface<ISpecificGrid>())
  172. .ToArray();
  173. var subtypes = _allo2mpages.Where(x => x.GetInterfaces().Any(
  174. i => i.IsGenericType
  175. && i.GetGenericTypeDefinition() == typeof(IDynamicOneToManyGrid<,>)
  176. && i.GenericTypeArguments.First().Equals(type)
  177. && i.GenericTypeArguments.Last().Equals(map)
  178. )
  179. );
  180. if (subtypes.Any())
  181. {
  182. pageTypes.Add(subtypes.First());
  183. }
  184. else
  185. {
  186. pageTypes.Add(typeof(DynamicOneToManyGrid<,>).MakeGenericType(type, map));
  187. }
  188. }
  189. }
  190. _onetomanypages[type] = pageTypes.ToArray();
  191. }
  192. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  193. }
  194. public static void LoadCustomEditorPages(Type type, DynamicEditorPages pages)
  195. {
  196. if (!_customeditorpages.TryGetValue(type, out var pageTypes))
  197. {
  198. _allcepages ??= CoreUtils.Entities.Where(
  199. x => x.IsClass
  200. && !x.IsGenericType
  201. && x.HasInterface(typeof(IDynamicCustomEditorPage<>)))
  202. .ToArray();
  203. pageTypes = _allcepages.Where(x => x.GetInterfaces().Any(i =>
  204. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDynamicCustomEditorPage<>) &&
  205. i.GenericTypeArguments.First().Equals(type))).ToArray();
  206. _customeditorpages[type] = pageTypes;
  207. }
  208. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  209. }
  210. public static void LoadEnclosedListPages(Type type, DynamicEditorPages pages)
  211. {
  212. if (!_enclosedlistpages.TryGetValue(type, out var pageTypes))
  213. {
  214. pageTypes = new List<Tuple<Type, PropertyInfo>>();
  215. foreach (var property in type.GetProperties())
  216. {
  217. if (property.PropertyType.GetInterfaces().Contains(typeof(IList)))
  218. {
  219. var curtype = property.PropertyType;
  220. var gentype = property.PropertyType.GetGenericArguments().FirstOrDefault();
  221. while (gentype == null && curtype?.BaseType != null)
  222. {
  223. curtype = curtype.BaseType;
  224. gentype = curtype?.GetGenericArguments().FirstOrDefault();
  225. }
  226. if (gentype != null)
  227. if (gentype.IsSubclassOf(typeof(BaseObject)))
  228. {
  229. var editor = property.GetCustomAttributes().FirstOrDefault(x => x is BaseEditor);
  230. if (editor == null || !(editor is NullEditor))
  231. {
  232. _alleltypes ??= CoreUtils.Entities.Where(
  233. x => x.IsClass
  234. && !x.IsGenericType
  235. && x.HasInterface(typeof(IDynamicEnclosedListGrid<,>)))
  236. .ToArray();
  237. var subtypes = _alleltypes.Where(
  238. x => x.GetInterfaces().Any(
  239. i => i.IsGenericType
  240. && i.GetGenericTypeDefinition() == typeof(IDynamicEnclosedListGrid<,>)
  241. && i.GenericTypeArguments.First().Equals(type)
  242. && i.GenericTypeArguments.Last().Equals(gentype)
  243. )
  244. );
  245. if (subtypes.Any())
  246. {
  247. pageTypes.Add(new(subtypes.First(), property));
  248. }
  249. else
  250. {
  251. subtypes = _alleltypes.Where(x => x.GetInterfaces().Any(i => (i.GenericTypeArguments.LastOrDefault()?.Equals(gentype) == true)));
  252. if (subtypes.Any())
  253. {
  254. pageTypes.Add(new(subtypes.First().MakeGenericType(type), property));
  255. }
  256. else
  257. {
  258. try
  259. {
  260. pageTypes.Add(new(typeof(DynamicEnclosedListGrid<,>).MakeGenericType(type, gentype), property));
  261. }
  262. catch (Exception e)
  263. {
  264. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  265. }
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }
  272. _enclosedlistpages[type] = pageTypes.ToArray();
  273. }
  274. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x.Item1, x.Item2) as IDynamicEditorPage)!));
  275. }
  276. #endregion
  277. #region Columns
  278. public static IColumns LoadEditorColumns(Type T, IColumns? additional = null)
  279. {
  280. var result = Columns.Create(T, ColumnTypeFlags.EditorColumns);
  281. if(additional is not null)
  282. {
  283. foreach (var col in additional)
  284. result.Add(col.Property);
  285. }
  286. foreach (var col in result.ColumnNames().ToArray())
  287. {
  288. var prop = DatabaseSchema.Property(T, col);
  289. if (prop?.Editor is DataLookupEditor dataLookup)
  290. {
  291. foreach (var lookupColumn in LookupFactory.DefineLookupFilterColumns(T, prop.Name))
  292. {
  293. result.Add(lookupColumn);
  294. }
  295. }
  296. }
  297. return result;
  298. }
  299. public static Columns<T> LoadEditorColumns<T>(Columns<T>? additional = null) => (LoadEditorColumns(typeof(T), additional) as Columns<T>)!;
  300. #endregion
  301. #region Editor Values
  302. /// <summary>
  303. /// Set the property <paramref name="name"/> of <paramref name="items"/> to <paramref name="value"/>, and return all changed properties.
  304. /// </summary>
  305. /// <returns>A dictionary containing changed properties, with the property name as the key, and the new value as the value.</returns>
  306. public static Dictionary<string, object?> UpdateEditorValue(BaseObject[] items, string name, object? value)
  307. {
  308. Logger.Send(LogType.Information, "", string.Format("DynamicGridUtils.UpdateEditorValue({0},{1},{2})", items.Length, name, value));
  309. var sw = new Stopwatch();
  310. var changes = new Dictionary<string, object?>();
  311. var props = DatabaseSchema.Properties(items.First().GetType()).ToArray();
  312. foreach (var item in items)
  313. {
  314. //Dictionary<String, object> previous = new Dictionary<string, object>();
  315. var previous = CoreUtils.GetValues(item, props);
  316. //if (item.OriginalValues != null)
  317. //{
  318. // foreach (var key in item.OriginalValues.Keys)
  319. // previous[key] = item.OriginalValues[key];
  320. //}
  321. var prop = DatabaseSchema.Property(item.GetType(), name);
  322. if (prop is CustomProperty)
  323. {
  324. if (!item.HasOriginalValue(name))
  325. item.SetOriginalValue(name, item.UserProperties[name]);
  326. item.UserProperties[name] = value;
  327. }
  328. else
  329. {
  330. if (prop != null)
  331. try
  332. {
  333. var getter = prop.Getter();
  334. var oldvalue = getter != null ? getter.Invoke(item) : CoreUtils.GetPropertyValue(item, name);
  335. var setter = prop.Setter();
  336. if (setter != null && value != null)
  337. setter.Invoke(item, value);
  338. else
  339. CoreUtils.SetPropertyValue(item, name, value);
  340. }
  341. catch (Exception)
  342. {
  343. Logger.Send(LogType.Error, "",
  344. string.Format("Unable to Set Value for [{0}.{1}] (Value is {2})", item.GetType().Name, name, value));
  345. }
  346. }
  347. var current = CoreUtils.GetValues(item, props);
  348. CoreUtils.MergeChanges(previous, current, changes);
  349. }
  350. return changes;
  351. }
  352. public static void UpdateEditorValue(BaseObject[] items, string name, object? value, Dictionary<string, object?> changes)
  353. {
  354. var results = UpdateEditorValue(items, name, value);
  355. foreach (var key in results.Keys)
  356. changes[key] = results[key];
  357. }
  358. #endregion
  359. #region Dynamic Grid Creation
  360. public static IDynamicGrid CreateDynamicGrid(Type gridType, Type entityType)
  361. {
  362. var type = FindDynamicGrid(gridType, entityType);
  363. return (Activator.CreateInstance(type) as IDynamicGrid)
  364. ?? throw new ArgumentException("Argument must be a type of IDynamicGrid", nameof(gridType));
  365. }
  366. public static DynamicGrid<TEntity> CreateDynamicGrid<TEntity>(Type gridType)
  367. where TEntity : BaseObject, new()
  368. {
  369. var type = FindDynamicGrid(gridType, typeof(TEntity));
  370. return (Activator.CreateInstance(type) as DynamicGrid<TEntity>)
  371. ?? throw new ArgumentException("Argument must be a type of IDynamicGrid", nameof(gridType));
  372. }
  373. private static Dictionary<Type, Type[]> _dynamicGrids = new();
  374. public static bool TryFindDynamicGrid(Type gridType, Type entityType, [NotNullWhen(true)] out Type? grid)
  375. {
  376. if (!_dynamicGrids.TryGetValue(gridType, out var grids))
  377. {
  378. grids = CoreUtils.Entities.Where(
  379. myType =>
  380. myType.IsClass
  381. && !myType.IsGenericType
  382. && myType.IsAssignableTo(typeof(IDynamicGrid))
  383. && !myType.IsAssignableTo(typeof(ISpecificGrid))
  384. ).ToArray();
  385. _dynamicGrids[gridType] = grids;
  386. }
  387. grids = grids.Where(x => x.IsSubclassOfRawGeneric(gridType)).ToArray();
  388. var entityGrids = grids.Where(x =>
  389. {
  390. var baseGrid = x.GetSuperclassDefinition(typeof(DynamicGrid<>));
  391. return baseGrid?.GenericTypeArguments[0] == entityType;
  392. }).ToList();
  393. var defaults = entityGrids.Where(x => x.IsAssignableTo(typeof(IDefaultGrid))).ToList();
  394. if (defaults.Count > 0)
  395. {
  396. if (defaults.Count > 1)
  397. {
  398. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error: {defaults.Count} IDefaultGrid derivations for {gridType.Name} of {entityType.Name}");
  399. }
  400. grid = defaults.First();
  401. return true;
  402. }
  403. grid = entityGrids.FirstOrDefault();
  404. return grid is not null;
  405. }
  406. public static Type FindDynamicGrid(Type gridType, Type entityType)
  407. {
  408. if(TryFindDynamicGrid(gridType, entityType, out var grid))
  409. {
  410. return grid;
  411. }
  412. return gridType.MakeGenericType(entityType);
  413. }
  414. public static Window CreateGridWindow(string title, IDynamicGrid dynamicGrid, bool showbuttons = false, Func<bool>? okclicked = null)
  415. {
  416. dynamicGrid.Margin = new Thickness(5);
  417. var window = new ThemableWindow { Title = title };
  418. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  419. window.SetValue(WindowBehavior.HideCloseButtonProperty, showbuttons);
  420. var grid = new Grid();
  421. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
  422. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  423. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  424. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  425. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
  426. var fe = dynamicGrid as FrameworkElement;
  427. fe.SetValue(Grid.RowProperty,0);
  428. fe.SetValue(Grid.ColumnProperty, 0);
  429. fe.SetValue(Grid.ColumnSpanProperty, 3);
  430. grid.Children.Add(fe);
  431. if (showbuttons)
  432. {
  433. var ok = new Button();
  434. ok.Content = "OK";
  435. ok.SetValue(Grid.RowProperty,1);
  436. ok.SetValue(Grid.ColumnProperty,1);
  437. ok.Margin = new Thickness(0,0,5,5);
  438. ok.Width = 80;
  439. ok.Height = 35;
  440. ok.Click += (sender, args) =>
  441. {
  442. if (okclicked?.Invoke() ?? true)
  443. window.DialogResult = true;
  444. };
  445. grid.Children.Add(ok);
  446. var cancel = new Button();
  447. cancel.Content = "Cancel";
  448. cancel.SetValue(Grid.RowProperty,1);
  449. cancel.SetValue(Grid.ColumnProperty,2);
  450. cancel.Margin = new Thickness(0,0,5,5);
  451. cancel.Width = 80;
  452. cancel.Height = 35;
  453. cancel.Click += (sender, args) =>
  454. {
  455. window.DialogResult = false;
  456. };
  457. grid.Children.Add(cancel);
  458. }
  459. window.Content = grid;
  460. dynamicGrid.Refresh(true, true);
  461. return window;
  462. }
  463. public static Window CreateGridWindow(string title, Type entityType, Type? gridType = null, bool showbuttons = false)
  464. {
  465. gridType ??= typeof(DynamicGrid<>);
  466. var grid = CreateDynamicGrid(gridType, entityType);
  467. return CreateGridWindow(title, grid, showbuttons);
  468. }
  469. public static Window CreateGridWindow<TGrid, TEntity>(string title, bool showbuttons = false)
  470. where TEntity : BaseObject
  471. where TGrid : IDynamicGrid
  472. {
  473. return CreateGridWindow(title, typeof(TEntity), typeof(TGrid), showbuttons);
  474. }
  475. public static Window CreateGridWindow<TEntity>(string title, bool showbuttons = false)
  476. where TEntity : BaseObject
  477. {
  478. return CreateGridWindow(title, typeof(TEntity), null, showbuttons);
  479. }
  480. #endregion
  481. #region Non-modal Editing
  482. public class DynamicGridEntityEditLock(IEnumerable<Guid> ids)
  483. {
  484. public HashSet<Guid> ObjectIDs { get; set; } = ids.ToHashSet();
  485. public ISubPanel? Panel { get; set; }
  486. }
  487. private static Dictionary<Guid, DynamicGridEntityEditLock> CurrentEditLocks = new();
  488. /// <summary>
  489. /// Attempt to begin editing <paramref name="objs"/>, failing if those entities are already being edited elsewhere.
  490. /// </summary>
  491. /// <remarks>
  492. /// If returns <see langword="true"/>, then <paramref name="editLock"/> will contain a new edit lock which contains the
  493. /// new entities. Otherwise, <paramref name="editLock"/> will be the lock on the entities that are already being edited.
  494. /// </remarks>
  495. public static bool TryEdit(BaseObject[] objs, out DynamicGridEntityEditLock editLock)
  496. {
  497. lock (CurrentEditLocks)
  498. {
  499. var ids = new List<Guid>();
  500. foreach(var obj in objs)
  501. {
  502. if(obj is Entity entity && entity.ID != Guid.Empty)
  503. {
  504. if (CurrentEditLocks.TryGetValue(entity.ID, out editLock))
  505. {
  506. return false;
  507. }
  508. else
  509. {
  510. ids.Add(entity.ID);
  511. }
  512. }
  513. }
  514. editLock = new(ids);
  515. foreach(var id in ids)
  516. {
  517. CurrentEditLocks.Add(id, editLock);
  518. }
  519. return true;
  520. }
  521. }
  522. public static void FinishEdit(BaseObject[] objs)
  523. {
  524. lock (CurrentEditLocks)
  525. {
  526. foreach(var obj in objs)
  527. {
  528. if(obj is Entity entity && entity.ID != Guid.Empty)
  529. {
  530. if(CurrentEditLocks.Remove(entity.ID, out var editLock))
  531. {
  532. editLock.ObjectIDs.Remove(entity.ID);
  533. }
  534. }
  535. }
  536. }
  537. }
  538. #endregion
  539. #region Editing BaseObject
  540. /// <summary>
  541. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a list of <see cref="BaseObject"/>s. Use for objects not saved in the database.
  542. /// </summary>
  543. /// <typeparam name="T"></typeparam>
  544. /// <param name="items"></param>
  545. /// <param name="pageDataHandler"></param>
  546. /// <param name="preloadPages"></param>
  547. /// <returns></returns>
  548. public static bool EditObjects<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  549. where T : BaseObject, new()
  550. {
  551. var grid = new DynamicItemsListGrid<T>();
  552. customiseGrid?.Invoke(grid);
  553. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  554. }
  555. /// <summary>
  556. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a <see cref="BaseObject"/>. Use for objects not saved in the database.
  557. /// </summary>
  558. /// <typeparam name="T"></typeparam>
  559. /// <param name="items"></param>
  560. /// <param name="pageDataHandler"></param>
  561. /// <param name="preloadPages"></param>
  562. /// <returns></returns>
  563. public static bool EditObject<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  564. where T : BaseObject, new()
  565. {
  566. var grid = new DynamicItemsListGrid<T>();
  567. customiseGrid?.Invoke(grid);
  568. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  569. }
  570. /// <summary>
  571. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a <typeparamref name="T"/>.
  572. /// </summary>
  573. /// <typeparam name="T"></typeparam>
  574. /// <param name="item"></param>
  575. /// <param name="pageDataHandler"></param>
  576. /// <param name="preloadPages"></param>
  577. /// <param name="customiseGrid"></param>
  578. /// <returns></returns>
  579. public static bool EditEntity<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  580. where T : BaseObject, new()
  581. {
  582. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  583. customiseGrid?.Invoke(grid);
  584. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  585. }
  586. /// <summary>
  587. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a list of <typeparamref name="T"/>.
  588. /// </summary>
  589. /// <typeparam name="T"></typeparam>
  590. /// <param name="item"></param>
  591. /// <param name="pageDataHandler"></param>
  592. /// <param name="preloadPages"></param>
  593. /// <param name="customiseGrid"></param>
  594. /// <returns></returns>
  595. public static bool EditEntities<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  596. where T : BaseObject, new()
  597. {
  598. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  599. customiseGrid?.Invoke(grid);
  600. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  601. }
  602. /// <summary>
  603. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a <typeparamref name="T"/>, by loading it from the database.
  604. /// </summary>
  605. public static bool EditEntity<T>(Guid id, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  606. where T : Entity, IRemotable, IPersistent, new()
  607. {
  608. var grid = (CreateDynamicGrid<T>(typeof(DynamicDataGrid<>)) as DynamicDataGrid<T>)!;
  609. customiseGrid?.Invoke(grid);
  610. var item = Client.Query<T>(
  611. new Filter<T>(x => x.ID).IsEqualTo(id),
  612. grid.LoadEditorColumns())
  613. .ToObjects<T>().FirstOrDefault();
  614. if (item is null) return false;
  615. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  616. }
  617. #endregion
  618. #region Drag + Drop
  619. public static string DragFormat => typeof(DynamicGridDragFormat).FullName ?? "";
  620. /// <summary>
  621. /// Try to get data dragged from a <see cref="DynamicGrid{T}"/> from a <see cref="DragEventArgs"/>, returning <see langword="true"/>
  622. /// if data was present.
  623. /// </summary>
  624. /// <param name="e"></param>
  625. public static bool TryGetDropData(
  626. DragEventArgs e,
  627. [NotNullWhen(true)] out Type? type,
  628. [NotNullWhen(true)] out CoreTable? table)
  629. {
  630. if (e.Data.GetDataPresent(DragFormat))
  631. {
  632. var data = e.Data.GetData(DragFormat) as DynamicGridDragFormat;
  633. if (data is not null)
  634. {
  635. table = new CoreTable();
  636. foreach (var column in data.Table.Columns)
  637. {
  638. if (column is DataColumn dataColumn)
  639. {
  640. table.Columns.Add(new CoreColumn { ColumnName = dataColumn.ColumnName.Replace('_', '.'), DataType = dataColumn.DataType });
  641. }
  642. }
  643. foreach (var row in data.Table.Rows)
  644. {
  645. if (row is DataRow dataRow)
  646. {
  647. var coreRow = table.NewRow();
  648. coreRow.LoadValues(dataRow.ItemArray);
  649. table.Rows.Add(coreRow);
  650. }
  651. }
  652. type = data.Entity;
  653. return true;
  654. }
  655. }
  656. table = null;
  657. type = null;
  658. return false;
  659. }
  660. #endregion
  661. #region Style
  662. public static Brush SelectionBackground { get; set; } = new SolidColorBrush(Colors.Black);
  663. public static Brush SelectionForeground { get; set; } = new SolidColorBrush(Colors.Silver);
  664. public static Brush FilterBackground { get; set; } = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xE9, 0xF7, 0xC9));
  665. public static Brush FilterForeground{ get; set; } = new SolidColorBrush(Colors.Black);
  666. #endregion
  667. public static void PopulateFormMenu<TEntityForm, TEntity, TEntityLink>(
  668. ItemsControl menu,
  669. Guid entityID,
  670. Func<TEntity> loadEntity,
  671. bool editOnAdd = false,
  672. DynamicFormEditWindow.CustomiseDynamicFormEditWindow? customiseEditor = null)
  673. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  674. where TEntity : Entity
  675. where TEntityLink : BaseObject, IEntityLink<TEntity>, new()
  676. {
  677. var task = Task.Run(() =>
  678. {
  679. return new Client<TEntityForm>().Query(
  680. new Filter<TEntityForm>(x => x.Parent.ID).IsEqualTo(entityID),
  681. null).Rows.Select(x => x.ToObject<TEntityForm>()).ToList();
  682. });
  683. var addForm = new MenuItem { Header = "Add Form" };
  684. addForm.Click += (o, e) =>
  685. {
  686. var entity = loadEntity();
  687. var filter = LookupFactory.DefineChildFilter<TEntity, DigitalForm>(new TEntity[] { entity })
  688. ?? LookupFactory.DefineLookupFilter<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form, Array.Empty<TEntityForm>());
  689. var select = new MultiSelectDialog<DigitalForm>(
  690. filter,
  691. LookupFactory.DefineLookupColumns<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form).Add(x => x.Description),
  692. false);
  693. if(select.ShowDialog() == true)
  694. {
  695. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  696. if(digitalForm is not null)
  697. {
  698. var form = new TEntityForm
  699. {
  700. Description = digitalForm.Description
  701. };
  702. form.Parent.ID = entityID;
  703. form.Form.ID = digitalForm.ID;
  704. if (editOnAdd)
  705. {
  706. if (DynamicFormEditWindow.EditDigitalForm(form, out var dataModel, customise: customiseEditor))
  707. {
  708. dataModel.Update(null);
  709. }
  710. }
  711. else
  712. {
  713. new Client<TEntityForm>().Save(form, "Added by user");
  714. }
  715. }
  716. };
  717. };
  718. var manageForms = new MenuItem { Header = "Manage Forms..." };
  719. manageForms.Click += (o, e) =>
  720. {
  721. var window = new ThemableWindow() { Title = $"Manage {typeof(TEntity).Name} Forms" };
  722. var grid = new DynamicEntityFormGrid<TEntityForm, TEntity, TEntityLink>(loadEntity());
  723. grid.Refresh(true, true);
  724. grid.Margin = new Thickness(5);
  725. window.Content = grid;
  726. window.ShowDialog();
  727. };
  728. menu.Items.Add(addForm);
  729. menu.Items.Add(new Separator());
  730. menu.Items.Add(new MenuItem() { Header = "Loading...", IsEnabled = false });
  731. menu.Items.Add(new Separator());
  732. menu.Items.Add(manageForms);
  733. task.ContinueWith((task) =>
  734. {
  735. var entityForms = task.Result;
  736. menu.Items.Clear();
  737. menu.Items.Add(addForm);
  738. menu.Items.Add(new Separator());
  739. if (entityForms.Any())
  740. {
  741. foreach (var entityForm in entityForms)
  742. {
  743. var description = entityForm.Description;
  744. if (string.IsNullOrWhiteSpace(description))
  745. {
  746. description = entityForm.Form.Description;
  747. }
  748. var formItem = new MenuItem { Header = $"{entityForm.Number} : {description}" };
  749. formItem.Click += (o, e) =>
  750. {
  751. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, customise: customiseEditor))
  752. {
  753. dataModel.Update(null);
  754. }
  755. };
  756. menu.Items.Add(formItem);
  757. }
  758. }
  759. else
  760. {
  761. menu.Items.Add(new MenuItem() { Header = "No Forms", IsEnabled = false });
  762. }
  763. menu.Items.Add(new Separator());
  764. menu.Items.Add(manageForms);
  765. }, TaskScheduler.FromCurrentSynchronizationContext());
  766. }
  767. #region Alignment
  768. public static VerticalAlignment VerticalAlignment(this Alignment alignment)
  769. {
  770. if (alignment.Equals(Alignment.NotSet))
  771. return System.Windows.VerticalAlignment.Center;
  772. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.TopRight))
  773. return System.Windows.VerticalAlignment.Top;
  774. if (alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.MiddleRight))
  775. return System.Windows.VerticalAlignment.Center;
  776. return System.Windows.VerticalAlignment.Bottom;
  777. }
  778. public static HorizontalAlignment HorizontalAlignment(this Alignment alignment, Type datatype)
  779. {
  780. if (alignment.Equals(Alignment.NotSet))
  781. return datatype.IsNumeric() ? System.Windows.HorizontalAlignment.Right :
  782. datatype == typeof(bool) ? System.Windows.HorizontalAlignment.Center : System.Windows.HorizontalAlignment.Left;
  783. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  784. return System.Windows.HorizontalAlignment.Left;
  785. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  786. return System.Windows.HorizontalAlignment.Center;
  787. return System.Windows.HorizontalAlignment.Right;
  788. }
  789. public static TextAlignment TextAlignment(this Alignment alignment, Type datatype)
  790. {
  791. if (alignment.Equals(Alignment.NotSet))
  792. return datatype.IsNumeric() ? System.Windows.TextAlignment.Right :
  793. datatype == typeof(bool) ? System.Windows.TextAlignment.Center : System.Windows.TextAlignment.Left;
  794. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  795. return System.Windows.TextAlignment.Left;
  796. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  797. return System.Windows.TextAlignment.Center;
  798. return System.Windows.TextAlignment.Right;
  799. }
  800. #endregion
  801. }