DynamicGridUtils.cs 37 KB

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