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.SetValue(WindowBehavior.HideCloseButtonProperty, showbuttons);
  415. var grid = new Grid();
  416. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
  417. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  418. grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
  419. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  420. grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
  421. var fe = dynamicGrid as FrameworkElement;
  422. fe.SetValue(Grid.RowProperty,0);
  423. fe.SetValue(Grid.ColumnProperty, 0);
  424. fe.SetValue(Grid.ColumnSpanProperty, 3);
  425. grid.Children.Add(fe);
  426. if (showbuttons)
  427. {
  428. var ok = new Button();
  429. ok.Content = "OK";
  430. ok.SetValue(Grid.RowProperty,1);
  431. ok.SetValue(Grid.ColumnProperty,1);
  432. ok.Margin = new Thickness(0,0,5,5);
  433. ok.Width = 80;
  434. ok.Height = 35;
  435. ok.Click += (sender, args) =>
  436. {
  437. if (okclicked?.Invoke() ?? true)
  438. window.DialogResult = true;
  439. };
  440. grid.Children.Add(ok);
  441. var cancel = new Button();
  442. cancel.Content = "Cancel";
  443. cancel.SetValue(Grid.RowProperty,1);
  444. cancel.SetValue(Grid.ColumnProperty,2);
  445. cancel.Margin = new Thickness(0,0,5,5);
  446. cancel.Width = 80;
  447. cancel.Height = 35;
  448. cancel.Click += (sender, args) =>
  449. {
  450. window.DialogResult = false;
  451. };
  452. grid.Children.Add(cancel);
  453. }
  454. window.Content = grid;
  455. dynamicGrid.Refresh(true, true);
  456. return window;
  457. }
  458. public static Window CreateGridWindow(string title, Type entityType, Type? gridType = null, bool showbuttons = false)
  459. {
  460. gridType ??= typeof(DynamicGrid<>);
  461. var grid = CreateDynamicGrid(gridType, entityType);
  462. return CreateGridWindow(title, grid, showbuttons);
  463. }
  464. public static Window CreateGridWindow<TGrid, TEntity>(string title, bool showbuttons = false)
  465. where TEntity : BaseObject
  466. where TGrid : IDynamicGrid
  467. {
  468. return CreateGridWindow(title, typeof(TEntity), typeof(TGrid), showbuttons);
  469. }
  470. public static Window CreateGridWindow<TEntity>(string title, bool showbuttons = false)
  471. where TEntity : BaseObject
  472. {
  473. return CreateGridWindow(title, typeof(TEntity), null, showbuttons);
  474. }
  475. #endregion
  476. #region Non-modal Editing
  477. public class DynamicGridEntityEditLock(IEnumerable<Guid> ids)
  478. {
  479. public HashSet<Guid> ObjectIDs { get; set; } = ids.ToHashSet();
  480. public ISubPanel? Panel { get; set; }
  481. }
  482. private static Dictionary<Guid, DynamicGridEntityEditLock> CurrentEditLocks = new();
  483. /// <summary>
  484. /// Attempt to begin editing <paramref name="objs"/>, failing if those entities are already being edited elsewhere.
  485. /// </summary>
  486. /// <remarks>
  487. /// If returns <see langword="true"/>, then <paramref name="editLock"/> will contain a new edit lock which contains the
  488. /// new entities. Otherwise, <paramref name="editLock"/> will be the lock on the entities that are already being edited.
  489. /// </remarks>
  490. public static bool TryEdit(BaseObject[] objs, out DynamicGridEntityEditLock editLock)
  491. {
  492. lock (CurrentEditLocks)
  493. {
  494. var ids = new List<Guid>();
  495. foreach(var obj in objs)
  496. {
  497. if(obj is Entity entity && entity.ID != Guid.Empty)
  498. {
  499. if (CurrentEditLocks.TryGetValue(entity.ID, out editLock))
  500. {
  501. return false;
  502. }
  503. else
  504. {
  505. ids.Add(entity.ID);
  506. }
  507. }
  508. }
  509. editLock = new(ids);
  510. foreach(var id in ids)
  511. {
  512. CurrentEditLocks.Add(id, editLock);
  513. }
  514. return true;
  515. }
  516. }
  517. public static void FinishEdit(BaseObject[] objs)
  518. {
  519. lock (CurrentEditLocks)
  520. {
  521. foreach(var obj in objs)
  522. {
  523. if(obj is Entity entity && entity.ID != Guid.Empty)
  524. {
  525. if(CurrentEditLocks.Remove(entity.ID, out var editLock))
  526. {
  527. editLock.ObjectIDs.Remove(entity.ID);
  528. }
  529. }
  530. }
  531. }
  532. }
  533. #endregion
  534. #region Editing BaseObject
  535. /// <summary>
  536. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a list of <see cref="BaseObject"/>s. Use for objects not saved in the database.
  537. /// </summary>
  538. /// <typeparam name="T"></typeparam>
  539. /// <param name="items"></param>
  540. /// <param name="pageDataHandler"></param>
  541. /// <param name="preloadPages"></param>
  542. /// <returns></returns>
  543. public static bool EditObjects<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  544. where T : BaseObject, new()
  545. {
  546. var grid = new DynamicItemsListGrid<T>();
  547. customiseGrid?.Invoke(grid);
  548. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  549. }
  550. /// <summary>
  551. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a <see cref="BaseObject"/>. Use for objects not saved in the database.
  552. /// </summary>
  553. /// <typeparam name="T"></typeparam>
  554. /// <param name="items"></param>
  555. /// <param name="pageDataHandler"></param>
  556. /// <param name="preloadPages"></param>
  557. /// <returns></returns>
  558. public static bool EditObject<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  559. where T : BaseObject, new()
  560. {
  561. var grid = new DynamicItemsListGrid<T>();
  562. customiseGrid?.Invoke(grid);
  563. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  564. }
  565. /// <summary>
  566. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a <typeparamref name="T"/>.
  567. /// </summary>
  568. /// <typeparam name="T"></typeparam>
  569. /// <param name="item"></param>
  570. /// <param name="pageDataHandler"></param>
  571. /// <param name="preloadPages"></param>
  572. /// <param name="customiseGrid"></param>
  573. /// <returns></returns>
  574. public static bool EditEntity<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  575. where T : Entity, new()
  576. {
  577. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  578. customiseGrid?.Invoke(grid);
  579. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  580. }
  581. /// <summary>
  582. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a list of <typeparamref name="T"/>.
  583. /// </summary>
  584. /// <typeparam name="T"></typeparam>
  585. /// <param name="item"></param>
  586. /// <param name="pageDataHandler"></param>
  587. /// <param name="preloadPages"></param>
  588. /// <param name="customiseGrid"></param>
  589. /// <returns></returns>
  590. public static bool EditEntities<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  591. where T : Entity, new()
  592. {
  593. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  594. customiseGrid?.Invoke(grid);
  595. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  596. }
  597. #endregion
  598. #region Drag + Drop
  599. public static string DragFormat => typeof(DynamicGridDragFormat).FullName ?? "";
  600. /// <summary>
  601. /// Try to get data dragged from a <see cref="DynamicGrid{T}"/> from a <see cref="DragEventArgs"/>, returning <see langword="true"/>
  602. /// if data was present.
  603. /// </summary>
  604. /// <param name="e"></param>
  605. public static bool TryGetDropData(
  606. DragEventArgs e,
  607. [NotNullWhen(true)] out Type? type,
  608. [NotNullWhen(true)] out CoreTable? table)
  609. {
  610. if (e.Data.GetDataPresent(DragFormat))
  611. {
  612. var data = e.Data.GetData(DragFormat) as DynamicGridDragFormat;
  613. if (data is not null)
  614. {
  615. table = new CoreTable();
  616. foreach (var column in data.Table.Columns)
  617. {
  618. if (column is DataColumn dataColumn)
  619. {
  620. table.Columns.Add(new CoreColumn { ColumnName = dataColumn.ColumnName.Replace('_', '.'), DataType = dataColumn.DataType });
  621. }
  622. }
  623. foreach (var row in data.Table.Rows)
  624. {
  625. if (row is DataRow dataRow)
  626. {
  627. var coreRow = table.NewRow();
  628. coreRow.LoadValues(dataRow.ItemArray);
  629. table.Rows.Add(coreRow);
  630. }
  631. }
  632. type = data.Entity;
  633. return true;
  634. }
  635. }
  636. table = null;
  637. type = null;
  638. return false;
  639. }
  640. #endregion
  641. #region Style
  642. public static Brush SelectionBackground { get; set; } = new SolidColorBrush(Colors.Black);
  643. public static Brush SelectionForeground { get; set; } = new SolidColorBrush(Colors.Silver);
  644. public static Brush FilterBackground { get; set; } = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xE9, 0xF7, 0xC9));
  645. #endregion
  646. public static void PopulateFormMenu<TEntityForm, TEntity, TEntityLink>(
  647. ItemsControl menu,
  648. Guid entityID,
  649. Func<TEntity> loadEntity,
  650. bool editOnAdd = false,
  651. DynamicFormEditWindow.CustomiseDynamicFormEditWindow? customiseEditor = null)
  652. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  653. where TEntity : Entity
  654. where TEntityLink : BaseObject, IEntityLink<TEntity>, new()
  655. {
  656. var task = Task.Run(() =>
  657. {
  658. return new Client<TEntityForm>().Query(
  659. new Filter<TEntityForm>(x => x.Parent.ID).IsEqualTo(entityID),
  660. null).Rows.Select(x => x.ToObject<TEntityForm>()).ToList();
  661. });
  662. var addForm = new MenuItem { Header = "Add Form" };
  663. addForm.Click += (o, e) =>
  664. {
  665. var entity = loadEntity();
  666. var filter = LookupFactory.DefineChildFilter<TEntity, DigitalForm>(new TEntity[] { entity })
  667. ?? LookupFactory.DefineLookupFilter<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form, Array.Empty<TEntityForm>());
  668. var select = new MultiSelectDialog<DigitalForm>(
  669. filter,
  670. LookupFactory.DefineLookupColumns<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form).Add(x => x.Description),
  671. false);
  672. if(select.ShowDialog() == true)
  673. {
  674. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  675. if(digitalForm is not null)
  676. {
  677. var form = new TEntityForm
  678. {
  679. Description = digitalForm.Description
  680. };
  681. form.Parent.ID = entityID;
  682. form.Form.ID = digitalForm.ID;
  683. if (editOnAdd)
  684. {
  685. if (DynamicFormEditWindow.EditDigitalForm(form, out var dataModel, customise: customiseEditor))
  686. {
  687. dataModel.Update(null);
  688. }
  689. }
  690. else
  691. {
  692. new Client<TEntityForm>().Save(form, "Added by user");
  693. }
  694. }
  695. };
  696. };
  697. var manageForms = new MenuItem { Header = "Manage Forms..." };
  698. manageForms.Click += (o, e) =>
  699. {
  700. var window = new ThemableWindow() { Title = $"Manage {typeof(TEntity).Name} Forms" };
  701. var grid = new DynamicEntityFormGrid<TEntityForm, TEntity, TEntityLink>(loadEntity());
  702. grid.Refresh(true, true);
  703. grid.Margin = new Thickness(5);
  704. window.Content = grid;
  705. window.ShowDialog();
  706. };
  707. menu.Items.Add(addForm);
  708. menu.Items.Add(new Separator());
  709. menu.Items.Add(new MenuItem() { Header = "Loading...", IsEnabled = false });
  710. menu.Items.Add(new Separator());
  711. menu.Items.Add(manageForms);
  712. task.ContinueWith((task) =>
  713. {
  714. var entityForms = task.Result;
  715. menu.Items.Clear();
  716. menu.Items.Add(addForm);
  717. menu.Items.Add(new Separator());
  718. if (entityForms.Any())
  719. {
  720. foreach (var entityForm in entityForms)
  721. {
  722. var description = entityForm.Description;
  723. if (string.IsNullOrWhiteSpace(description))
  724. {
  725. description = entityForm.Form.Description;
  726. }
  727. var formItem = new MenuItem { Header = $"{entityForm.Number} : {description}" };
  728. formItem.Click += (o, e) =>
  729. {
  730. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, customise: customiseEditor))
  731. {
  732. dataModel.Update(null);
  733. }
  734. };
  735. menu.Items.Add(formItem);
  736. }
  737. }
  738. else
  739. {
  740. menu.Items.Add(new MenuItem() { Header = "No Forms", IsEnabled = false });
  741. }
  742. menu.Items.Add(new Separator());
  743. menu.Items.Add(manageForms);
  744. }, TaskScheduler.FromCurrentSynchronizationContext());
  745. }
  746. #region Alignment
  747. public static VerticalAlignment VerticalAlignment(this Alignment alignment)
  748. {
  749. if (alignment.Equals(Alignment.NotSet))
  750. return System.Windows.VerticalAlignment.Center;
  751. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.TopRight))
  752. return System.Windows.VerticalAlignment.Top;
  753. if (alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.MiddleRight))
  754. return System.Windows.VerticalAlignment.Center;
  755. return System.Windows.VerticalAlignment.Bottom;
  756. }
  757. public static HorizontalAlignment HorizontalAlignment(this Alignment alignment, Type datatype)
  758. {
  759. if (alignment.Equals(Alignment.NotSet))
  760. return datatype.IsNumeric() ? System.Windows.HorizontalAlignment.Right :
  761. datatype == typeof(bool) ? System.Windows.HorizontalAlignment.Center : System.Windows.HorizontalAlignment.Left;
  762. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  763. return System.Windows.HorizontalAlignment.Left;
  764. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  765. return System.Windows.HorizontalAlignment.Center;
  766. return System.Windows.HorizontalAlignment.Right;
  767. }
  768. public static TextAlignment TextAlignment(this Alignment alignment, Type datatype)
  769. {
  770. if (alignment.Equals(Alignment.NotSet))
  771. return datatype.IsNumeric() ? System.Windows.TextAlignment.Right :
  772. datatype == typeof(bool) ? System.Windows.TextAlignment.Center : System.Windows.TextAlignment.Left;
  773. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  774. return System.Windows.TextAlignment.Left;
  775. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  776. return System.Windows.TextAlignment.Center;
  777. return System.Windows.TextAlignment.Right;
  778. }
  779. #endregion
  780. }