DynamicGridUtils.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. public static Dictionary<string, object?> UpdateEditorValue(BaseObject[] items, string name, object? value)
  303. {
  304. Logger.Send(LogType.Information, "", string.Format("DynamicGridUtils.UpdateEditorValue({0},{1},{2})", items.Length, name, value));
  305. var sw = new Stopwatch();
  306. var changes = new Dictionary<string, object?>();
  307. var props = DatabaseSchema.Properties(items.First().GetType()).ToArray();
  308. foreach (var item in items)
  309. {
  310. //Dictionary<String, object> previous = new Dictionary<string, object>();
  311. var previous = CoreUtils.GetValues(item, props);
  312. //if (item.OriginalValues != null)
  313. //{
  314. // foreach (var key in item.OriginalValues.Keys)
  315. // previous[key] = item.OriginalValues[key];
  316. //}
  317. var prop = DatabaseSchema.Property(item.GetType(), name);
  318. if (prop is CustomProperty)
  319. {
  320. if (!item.HasOriginalValue(name))
  321. item.SetOriginalValue(name, item.UserProperties[name]);
  322. item.UserProperties[name] = value;
  323. }
  324. else
  325. {
  326. if (prop != null)
  327. try
  328. {
  329. var getter = prop.Getter();
  330. var oldvalue = getter != null ? getter.Invoke(item) : CoreUtils.GetPropertyValue(item, name);
  331. var setter = prop.Setter();
  332. if (setter != null && value != null)
  333. setter.Invoke(item, value);
  334. else
  335. CoreUtils.SetPropertyValue(item, name, value);
  336. }
  337. catch (Exception)
  338. {
  339. Logger.Send(LogType.Error, "",
  340. string.Format("Unable to Set Value for [{0}.{1}] (Value is {2})", item.GetType().Name, name, value));
  341. }
  342. }
  343. var current = CoreUtils.GetValues(item, props);
  344. CoreUtils.MergeChanges(previous, current, changes);
  345. }
  346. return changes;
  347. }
  348. public static void UpdateEditorValue(BaseObject[] items, string name, object? value, Dictionary<string, object?> changes)
  349. {
  350. var results = UpdateEditorValue(items, name, value);
  351. foreach (var key in results.Keys)
  352. changes[key] = results[key];
  353. }
  354. #endregion
  355. #region Dynamic Grid Creation
  356. public static IDynamicGrid CreateDynamicGrid(Type gridType, Type entityType)
  357. {
  358. var type = FindDynamicGrid(gridType, entityType);
  359. return (Activator.CreateInstance(type) as IDynamicGrid)
  360. ?? throw new ArgumentException("Argument must be a type of IDynamicGrid", nameof(gridType));
  361. }
  362. public static DynamicGrid<TEntity> CreateDynamicGrid<TEntity>(Type gridType)
  363. where TEntity : BaseObject, new()
  364. {
  365. var type = FindDynamicGrid(gridType, typeof(TEntity));
  366. return (Activator.CreateInstance(type) as DynamicGrid<TEntity>)
  367. ?? throw new ArgumentException("Argument must be a type of IDynamicGrid", nameof(gridType));
  368. }
  369. private static Dictionary<Type, Type[]> _dynamicGrids = new();
  370. public static bool TryFindDynamicGrid(Type gridType, Type entityType, [NotNullWhen(true)] out Type? grid)
  371. {
  372. if (!_dynamicGrids.TryGetValue(gridType, out var grids))
  373. {
  374. grids = CoreUtils.Entities.Where(
  375. myType =>
  376. myType.IsClass
  377. && !myType.IsGenericType
  378. && myType.IsAssignableTo(typeof(IDynamicGrid))
  379. && !myType.IsAssignableTo(typeof(ISpecificGrid))
  380. ).ToArray();
  381. _dynamicGrids[gridType] = grids;
  382. }
  383. grids = grids.Where(x => x.IsSubclassOfRawGeneric(gridType)).ToArray();
  384. var entityGrids = grids.Where(x =>
  385. {
  386. var baseGrid = x.GetSuperclassDefinition(typeof(DynamicGrid<>));
  387. return baseGrid?.GenericTypeArguments[0] == entityType;
  388. }).ToList();
  389. var defaults = entityGrids.Where(x => x.IsAssignableTo(typeof(IDefaultGrid))).ToList();
  390. if (defaults.Count > 0)
  391. {
  392. if (defaults.Count > 1)
  393. {
  394. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error: {defaults.Count} IDefaultGrid derivations for {gridType.Name} of {entityType.Name}");
  395. }
  396. grid = defaults.First();
  397. return true;
  398. }
  399. grid = entityGrids.FirstOrDefault();
  400. return grid is not null;
  401. }
  402. public static Type FindDynamicGrid(Type gridType, Type entityType)
  403. {
  404. if(TryFindDynamicGrid(gridType, entityType, out var grid))
  405. {
  406. return grid;
  407. }
  408. return gridType.MakeGenericType(entityType);
  409. }
  410. public static Window CreateGridWindow(string title, IDynamicGrid dynamicGrid, bool showbuttons = false, Func<bool>? okclicked = null)
  411. {
  412. dynamicGrid.Margin = new Thickness(5);
  413. var window = new ThemableWindow { Title = title };
  414. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  415. window.SetValue(WindowBehavior.HideCloseButtonProperty, showbuttons);
  416. var grid = new Grid();
  417. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
  418. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  419. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  420. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  421. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
  422. var fe = dynamicGrid as FrameworkElement;
  423. fe.SetValue(Grid.RowProperty,0);
  424. fe.SetValue(Grid.ColumnProperty, 0);
  425. fe.SetValue(Grid.ColumnSpanProperty, 3);
  426. grid.Children.Add(fe);
  427. if (showbuttons)
  428. {
  429. var ok = new Button();
  430. ok.Content = "OK";
  431. ok.SetValue(Grid.RowProperty,1);
  432. ok.SetValue(Grid.ColumnProperty,1);
  433. ok.Margin = new Thickness(0,0,5,5);
  434. ok.Width = 80;
  435. ok.Height = 35;
  436. ok.Click += (sender, args) =>
  437. {
  438. if (okclicked?.Invoke() ?? true)
  439. window.DialogResult = true;
  440. };
  441. grid.Children.Add(ok);
  442. var cancel = new Button();
  443. cancel.Content = "Cancel";
  444. cancel.SetValue(Grid.RowProperty,1);
  445. cancel.SetValue(Grid.ColumnProperty,2);
  446. cancel.Margin = new Thickness(0,0,5,5);
  447. cancel.Width = 80;
  448. cancel.Height = 35;
  449. cancel.Click += (sender, args) =>
  450. {
  451. window.DialogResult = false;
  452. };
  453. grid.Children.Add(cancel);
  454. }
  455. window.Content = grid;
  456. dynamicGrid.Refresh(true, true);
  457. return window;
  458. }
  459. public static Window CreateGridWindow(string title, Type entityType, Type? gridType = null, bool showbuttons = false)
  460. {
  461. gridType ??= typeof(DynamicGrid<>);
  462. var grid = CreateDynamicGrid(gridType, entityType);
  463. return CreateGridWindow(title, grid, showbuttons);
  464. }
  465. public static Window CreateGridWindow<TGrid, TEntity>(string title, bool showbuttons = false)
  466. where TEntity : BaseObject
  467. where TGrid : IDynamicGrid
  468. {
  469. return CreateGridWindow(title, typeof(TEntity), typeof(TGrid), showbuttons);
  470. }
  471. public static Window CreateGridWindow<TEntity>(string title, bool showbuttons = false)
  472. where TEntity : BaseObject
  473. {
  474. return CreateGridWindow(title, typeof(TEntity), null, showbuttons);
  475. }
  476. #endregion
  477. #region Non-modal Editing
  478. public class DynamicGridEntityEditLock(IEnumerable<Guid> ids)
  479. {
  480. public HashSet<Guid> ObjectIDs { get; set; } = ids.ToHashSet();
  481. public ISubPanel? Panel { get; set; }
  482. }
  483. private static Dictionary<Guid, DynamicGridEntityEditLock> CurrentEditLocks = new();
  484. /// <summary>
  485. /// Attempt to begin editing <paramref name="objs"/>, failing if those entities are already being edited elsewhere.
  486. /// </summary>
  487. /// <remarks>
  488. /// If returns <see langword="true"/>, then <paramref name="editLock"/> will contain a new edit lock which contains the
  489. /// new entities. Otherwise, <paramref name="editLock"/> will be the lock on the entities that are already being edited.
  490. /// </remarks>
  491. public static bool TryEdit(BaseObject[] objs, out DynamicGridEntityEditLock editLock)
  492. {
  493. lock (CurrentEditLocks)
  494. {
  495. var ids = new List<Guid>();
  496. foreach(var obj in objs)
  497. {
  498. if(obj is Entity entity && entity.ID != Guid.Empty)
  499. {
  500. if (CurrentEditLocks.TryGetValue(entity.ID, out editLock))
  501. {
  502. return false;
  503. }
  504. else
  505. {
  506. ids.Add(entity.ID);
  507. }
  508. }
  509. }
  510. editLock = new(ids);
  511. foreach(var id in ids)
  512. {
  513. CurrentEditLocks.Add(id, editLock);
  514. }
  515. return true;
  516. }
  517. }
  518. public static void FinishEdit(BaseObject[] objs)
  519. {
  520. lock (CurrentEditLocks)
  521. {
  522. foreach(var obj in objs)
  523. {
  524. if(obj is Entity entity && entity.ID != Guid.Empty)
  525. {
  526. if(CurrentEditLocks.Remove(entity.ID, out var editLock))
  527. {
  528. editLock.ObjectIDs.Remove(entity.ID);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. #endregion
  535. #region Editing BaseObject
  536. /// <summary>
  537. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a list of <see cref="BaseObject"/>s. Use for objects not saved in the database.
  538. /// </summary>
  539. /// <typeparam name="T"></typeparam>
  540. /// <param name="items"></param>
  541. /// <param name="pageDataHandler"></param>
  542. /// <param name="preloadPages"></param>
  543. /// <returns></returns>
  544. public static bool EditObjects<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  545. where T : BaseObject, new()
  546. {
  547. var grid = new DynamicItemsListGrid<T>();
  548. customiseGrid?.Invoke(grid);
  549. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  550. }
  551. /// <summary>
  552. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a <see cref="BaseObject"/>. Use for objects not saved in the database.
  553. /// </summary>
  554. /// <typeparam name="T"></typeparam>
  555. /// <param name="items"></param>
  556. /// <param name="pageDataHandler"></param>
  557. /// <param name="preloadPages"></param>
  558. /// <returns></returns>
  559. public static bool EditObject<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  560. where T : BaseObject, new()
  561. {
  562. var grid = new DynamicItemsListGrid<T>();
  563. customiseGrid?.Invoke(grid);
  564. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  565. }
  566. /// <summary>
  567. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a <typeparamref name="T"/>.
  568. /// </summary>
  569. /// <typeparam name="T"></typeparam>
  570. /// <param name="item"></param>
  571. /// <param name="pageDataHandler"></param>
  572. /// <param name="preloadPages"></param>
  573. /// <param name="customiseGrid"></param>
  574. /// <returns></returns>
  575. public static bool EditEntity<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  576. where T : BaseObject, new()
  577. {
  578. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  579. customiseGrid?.Invoke(grid);
  580. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  581. }
  582. /// <summary>
  583. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a list of <typeparamref name="T"/>.
  584. /// </summary>
  585. /// <typeparam name="T"></typeparam>
  586. /// <param name="item"></param>
  587. /// <param name="pageDataHandler"></param>
  588. /// <param name="preloadPages"></param>
  589. /// <param name="customiseGrid"></param>
  590. /// <returns></returns>
  591. public static bool EditEntities<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  592. where T : BaseObject, new()
  593. {
  594. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  595. customiseGrid?.Invoke(grid);
  596. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  597. }
  598. #endregion
  599. #region Drag + Drop
  600. public static string DragFormat => typeof(DynamicGridDragFormat).FullName ?? "";
  601. /// <summary>
  602. /// Try to get data dragged from a <see cref="DynamicGrid{T}"/> from a <see cref="DragEventArgs"/>, returning <see langword="true"/>
  603. /// if data was present.
  604. /// </summary>
  605. /// <param name="e"></param>
  606. public static bool TryGetDropData(
  607. DragEventArgs e,
  608. [NotNullWhen(true)] out Type? type,
  609. [NotNullWhen(true)] out CoreTable? table)
  610. {
  611. if (e.Data.GetDataPresent(DragFormat))
  612. {
  613. var data = e.Data.GetData(DragFormat) as DynamicGridDragFormat;
  614. if (data is not null)
  615. {
  616. table = new CoreTable();
  617. foreach (var column in data.Table.Columns)
  618. {
  619. if (column is DataColumn dataColumn)
  620. {
  621. table.Columns.Add(new CoreColumn { ColumnName = dataColumn.ColumnName.Replace('_', '.'), DataType = dataColumn.DataType });
  622. }
  623. }
  624. foreach (var row in data.Table.Rows)
  625. {
  626. if (row is DataRow dataRow)
  627. {
  628. var coreRow = table.NewRow();
  629. coreRow.LoadValues(dataRow.ItemArray);
  630. table.Rows.Add(coreRow);
  631. }
  632. }
  633. type = data.Entity;
  634. return true;
  635. }
  636. }
  637. table = null;
  638. type = null;
  639. return false;
  640. }
  641. #endregion
  642. #region Style
  643. public static Brush SelectionBackground { get; set; } = new SolidColorBrush(Colors.Black);
  644. public static Brush SelectionForeground { get; set; } = new SolidColorBrush(Colors.Silver);
  645. public static Brush FilterBackground { get; set; } = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xE9, 0xF7, 0xC9));
  646. #endregion
  647. public static void PopulateFormMenu<TEntityForm, TEntity, TEntityLink>(
  648. ItemsControl menu,
  649. Guid entityID,
  650. Func<TEntity> loadEntity,
  651. bool editOnAdd = false,
  652. DynamicFormEditWindow.CustomiseDynamicFormEditWindow? customiseEditor = null)
  653. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  654. where TEntity : Entity
  655. where TEntityLink : BaseObject, IEntityLink<TEntity>, new()
  656. {
  657. var task = Task.Run(() =>
  658. {
  659. return new Client<TEntityForm>().Query(
  660. new Filter<TEntityForm>(x => x.Parent.ID).IsEqualTo(entityID),
  661. null).Rows.Select(x => x.ToObject<TEntityForm>()).ToList();
  662. });
  663. var addForm = new MenuItem { Header = "Add Form" };
  664. addForm.Click += (o, e) =>
  665. {
  666. var entity = loadEntity();
  667. var filter = LookupFactory.DefineChildFilter<TEntity, DigitalForm>(new TEntity[] { entity })
  668. ?? LookupFactory.DefineLookupFilter<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form, Array.Empty<TEntityForm>());
  669. var select = new MultiSelectDialog<DigitalForm>(
  670. filter,
  671. LookupFactory.DefineLookupColumns<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form).Add(x => x.Description),
  672. false);
  673. if(select.ShowDialog() == true)
  674. {
  675. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  676. if(digitalForm is not null)
  677. {
  678. var form = new TEntityForm
  679. {
  680. Description = digitalForm.Description
  681. };
  682. form.Parent.ID = entityID;
  683. form.Form.ID = digitalForm.ID;
  684. if (editOnAdd)
  685. {
  686. if (DynamicFormEditWindow.EditDigitalForm(form, out var dataModel, customise: customiseEditor))
  687. {
  688. dataModel.Update(null);
  689. }
  690. }
  691. else
  692. {
  693. new Client<TEntityForm>().Save(form, "Added by user");
  694. }
  695. }
  696. };
  697. };
  698. var manageForms = new MenuItem { Header = "Manage Forms..." };
  699. manageForms.Click += (o, e) =>
  700. {
  701. var window = new ThemableWindow() { Title = $"Manage {typeof(TEntity).Name} Forms" };
  702. var grid = new DynamicEntityFormGrid<TEntityForm, TEntity, TEntityLink>(loadEntity());
  703. grid.Refresh(true, true);
  704. grid.Margin = new Thickness(5);
  705. window.Content = grid;
  706. window.ShowDialog();
  707. };
  708. menu.Items.Add(addForm);
  709. menu.Items.Add(new Separator());
  710. menu.Items.Add(new MenuItem() { Header = "Loading...", IsEnabled = false });
  711. menu.Items.Add(new Separator());
  712. menu.Items.Add(manageForms);
  713. task.ContinueWith((task) =>
  714. {
  715. var entityForms = task.Result;
  716. menu.Items.Clear();
  717. menu.Items.Add(addForm);
  718. menu.Items.Add(new Separator());
  719. if (entityForms.Any())
  720. {
  721. foreach (var entityForm in entityForms)
  722. {
  723. var description = entityForm.Description;
  724. if (string.IsNullOrWhiteSpace(description))
  725. {
  726. description = entityForm.Form.Description;
  727. }
  728. var formItem = new MenuItem { Header = $"{entityForm.Number} : {description}" };
  729. formItem.Click += (o, e) =>
  730. {
  731. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, customise: customiseEditor))
  732. {
  733. dataModel.Update(null);
  734. }
  735. };
  736. menu.Items.Add(formItem);
  737. }
  738. }
  739. else
  740. {
  741. menu.Items.Add(new MenuItem() { Header = "No Forms", IsEnabled = false });
  742. }
  743. menu.Items.Add(new Separator());
  744. menu.Items.Add(manageForms);
  745. }, TaskScheduler.FromCurrentSynchronizationContext());
  746. }
  747. #region Alignment
  748. public static VerticalAlignment VerticalAlignment(this Alignment alignment)
  749. {
  750. if (alignment.Equals(Alignment.NotSet))
  751. return System.Windows.VerticalAlignment.Center;
  752. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.TopRight))
  753. return System.Windows.VerticalAlignment.Top;
  754. if (alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.MiddleRight))
  755. return System.Windows.VerticalAlignment.Center;
  756. return System.Windows.VerticalAlignment.Bottom;
  757. }
  758. public static HorizontalAlignment HorizontalAlignment(this Alignment alignment, Type datatype)
  759. {
  760. if (alignment.Equals(Alignment.NotSet))
  761. return datatype.IsNumeric() ? System.Windows.HorizontalAlignment.Right :
  762. datatype == typeof(bool) ? System.Windows.HorizontalAlignment.Center : System.Windows.HorizontalAlignment.Left;
  763. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  764. return System.Windows.HorizontalAlignment.Left;
  765. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  766. return System.Windows.HorizontalAlignment.Center;
  767. return System.Windows.HorizontalAlignment.Right;
  768. }
  769. public static TextAlignment TextAlignment(this Alignment alignment, Type datatype)
  770. {
  771. if (alignment.Equals(Alignment.NotSet))
  772. return datatype.IsNumeric() ? System.Windows.TextAlignment.Right :
  773. datatype == typeof(bool) ? System.Windows.TextAlignment.Center : System.Windows.TextAlignment.Left;
  774. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  775. return System.Windows.TextAlignment.Left;
  776. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  777. return System.Windows.TextAlignment.Center;
  778. return System.Windows.TextAlignment.Right;
  779. }
  780. #endregion
  781. }