DynamicGridUtils.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. namespace InABox.DynamicGrid;
  19. [Caption("Set Default Column Selections")]
  20. public class CanSetDefaultColumns : EnabledSecurityDescriptor<CoreLicense>
  21. {
  22. }
  23. [LibraryInitializer]
  24. public static class DynamicGridUtils
  25. {
  26. private static IEnumerable<Type>? _allm2mtypes;
  27. private static IEnumerable<Type>? _allm2mpages;
  28. private static IEnumerable<Type>? _allo2mtypes;
  29. private static IEnumerable<Type>? _allo2mpages;
  30. private static IEnumerable<Type>? _allcepages;
  31. private static IEnumerable<Type>? _alleltypes;
  32. private static Dictionary<Type, IList<Type>> _onetomanypages = new();
  33. private static Dictionary<Type, IList<Type>> _manytomanytomanypages = new();
  34. private static Dictionary<Type, IList<Tuple<Type, PropertyInfo>>> _enclosedlistpages = new();
  35. private static Dictionary<Type, IList<Type>> _customeditorpages = new();
  36. // HACK: These are really dumb
  37. public static Action<ReportTemplate, DataModel>? PreviewReport { get; set; }
  38. public static Action<FrameworkElement?, string, DataModel, bool>? PrintMenu { get; set; }
  39. public static readonly MainResources Resources = new();
  40. public static void RegisterClasses()
  41. {
  42. // String assyname = "_" + Assembly.GetExecutingAssembly().GetName().Name;
  43. // AssemblyName assemblyName = new AssemblyName(assyname);
  44. // AppDomain appDomain = Thread.GetDomain();
  45. //
  46. // String assyFile = String.Format("{0}.dll", assemblyName.Name);
  47. // String path = "";
  48. // if (Assembly.GetEntryAssembly() != null)
  49. // {
  50. // path = Path.Combine(
  51. // Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  52. // Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  53. // );
  54. // }
  55. // else
  56. // {
  57. // path = Path.Combine(
  58. // Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  59. // Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location)
  60. // );
  61. // }
  62. //
  63. // if (!Directory.Exists(path))
  64. // Directory.CreateDirectory(path);
  65. // AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, path);
  66. //
  67. // ModuleBuilder module = assemblyBuilder.DefineDynamicModule(assyFile); //,true);
  68. //
  69. // if (_allm2mtypes == null)
  70. // {
  71. // _allm2mtypes = CoreUtils.TypeList(
  72. // AppDomain.CurrentDomain.GetAssemblies(),
  73. // x => x.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>))
  74. // );
  75. // }
  76. //
  77. // var maps = _allm2mtypes.Where(x => x.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Last().Equals(typeof(Document))));
  78. //
  79. // foreach (var map in maps)
  80. // {
  81. // var intf = map.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>) && i.GenericTypeArguments.Last().Equals(typeof(Document)));
  82. // Type entity = intf.GenericTypeArguments.First();
  83. // Type basetype = typeof(DynamicDocumentGrid<,>).MakeGenericType(map, entity);
  84. // TypeBuilder tbService = module.DefineType(String.Format("{0}", map.EntityName().Replace(".", "_")), TypeAttributes.Public | TypeAttributes.Class);
  85. // tbService.SetParent(basetype);
  86. // Type final = tbService.CreateType();
  87. // }
  88. //
  89. // try
  90. // {
  91. // assemblyBuilder.Save(assyFile);
  92. // }
  93. // catch (Exception e)
  94. // {
  95. // Logger.Send(LogType.Error, "", String.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  96. // }
  97. }
  98. #region Pages
  99. public static IEnumerable<Type> GetManyToManyTypes(Type type)
  100. {
  101. _allm2mtypes ??= CoreUtils.Entities.Where(x => x.HasInterface(typeof(IManyToMany<,>))).ToArray();
  102. return _allm2mtypes.Where(x => x.GetInterfaces().Any(
  103. i => i.IsGenericType
  104. && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  105. && i.GenericTypeArguments[0] == type)
  106. );
  107. }
  108. public static void LoadManyToManyPages(Type type, DynamicEditorPages pages)
  109. {
  110. if (!_manytomanytomanypages.TryGetValue(type, out var pageTypes))
  111. {
  112. pageTypes = new List<Type>();
  113. var maps = GetManyToManyTypes(type);
  114. foreach (var map in maps)
  115. {
  116. if (ClientFactory.IsSupported(map))
  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. }
  138. _manytomanytomanypages[type] = pageTypes.ToArray();
  139. }
  140. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  141. }
  142. public static IEnumerable<Type> GetOneToManyTypes(Type type)
  143. {
  144. _allo2mtypes ??= CoreUtils.Entities.Where(
  145. x => x.HasInterface(typeof(IOneToMany<>)) && !x.HasAttribute<ObsoleteAttribute>())
  146. .ToArray();
  147. return _allo2mtypes
  148. .Where(x => x.GetInterfaces().Any(i =>
  149. i.IsGenericType
  150. && i.GetGenericTypeDefinition() == typeof(IOneToMany<>)
  151. && i.GenericTypeArguments.Contains(type)))
  152. .OrderBy(x => x.EntityName());
  153. }
  154. public static void LoadOneToManyPages(Type type, DynamicEditorPages pages)
  155. {
  156. if (!_onetomanypages.TryGetValue(type, out var pageTypes))
  157. {
  158. pageTypes = new List<Type>();
  159. var maps = GetOneToManyTypes(type);
  160. foreach (var map in maps)
  161. {
  162. if (ClientFactory.IsSupported(map))
  163. {
  164. _allo2mpages ??= CoreUtils.Entities.Where(
  165. x =>
  166. x.IsClass
  167. && !x.IsGenericType
  168. && x.HasInterface(typeof(IDynamicOneToManyGrid<,>))
  169. && !x.HasInterface<ISpecificGrid>())
  170. .ToArray();
  171. var subtypes = _allo2mpages.Where(x => x.GetInterfaces().Any(
  172. i => i.IsGenericType
  173. && i.GetGenericTypeDefinition() == typeof(IDynamicOneToManyGrid<,>)
  174. && i.GenericTypeArguments.First().Equals(type)
  175. && i.GenericTypeArguments.Last().Equals(map)
  176. )
  177. );
  178. if (subtypes.Any())
  179. {
  180. pageTypes.Add(subtypes.First());
  181. }
  182. else
  183. {
  184. pageTypes.Add(typeof(DynamicOneToManyGrid<,>).MakeGenericType(type, map));
  185. }
  186. }
  187. }
  188. _onetomanypages[type] = pageTypes.ToArray();
  189. }
  190. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  191. }
  192. public static void LoadCustomEditorPages(Type type, DynamicEditorPages pages)
  193. {
  194. if (!_customeditorpages.TryGetValue(type, out var pageTypes))
  195. {
  196. _allcepages ??= CoreUtils.Entities.Where(
  197. x => x.IsClass
  198. && !x.IsGenericType
  199. && x.HasInterface(typeof(IDynamicCustomEditorPage<>)))
  200. .ToArray();
  201. pageTypes = _allcepages.Where(x => x.GetInterfaces().Any(i =>
  202. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDynamicCustomEditorPage<>) &&
  203. i.GenericTypeArguments.First().Equals(type))).ToArray();
  204. _customeditorpages[type] = pageTypes;
  205. }
  206. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x) as IDynamicEditorPage)!));
  207. }
  208. public static void LoadEnclosedListPages(Type type, DynamicEditorPages pages)
  209. {
  210. if (!_enclosedlistpages.TryGetValue(type, out var pageTypes))
  211. {
  212. pageTypes = new List<Tuple<Type, PropertyInfo>>();
  213. foreach (var property in type.GetProperties())
  214. {
  215. if (property.PropertyType.GetInterfaces().Contains(typeof(IList)))
  216. {
  217. var curtype = property.PropertyType;
  218. var gentype = property.PropertyType.GetGenericArguments().FirstOrDefault();
  219. while (gentype == null && curtype?.BaseType != null)
  220. {
  221. curtype = curtype.BaseType;
  222. gentype = curtype?.GetGenericArguments().FirstOrDefault();
  223. }
  224. if (gentype != null)
  225. if (gentype.IsSubclassOf(typeof(BaseObject)))
  226. {
  227. var editor = property.GetCustomAttributes().FirstOrDefault(x => x is BaseEditor);
  228. if (editor == null || !(editor is NullEditor))
  229. {
  230. _alleltypes ??= CoreUtils.Entities.Where(
  231. x => x.IsClass
  232. && !x.IsGenericType
  233. && x.HasInterface(typeof(IDynamicEnclosedListGrid<,>)))
  234. .ToArray();
  235. var subtypes = _alleltypes.Where(
  236. x => x.GetInterfaces().Any(
  237. i => i.IsGenericType
  238. && i.GetGenericTypeDefinition() == typeof(IDynamicEnclosedListGrid<,>)
  239. && i.GenericTypeArguments.First().Equals(type)
  240. && i.GenericTypeArguments.Last().Equals(gentype)
  241. )
  242. );
  243. if (subtypes.Any())
  244. {
  245. pageTypes.Add(new(subtypes.First(), property));
  246. }
  247. else
  248. {
  249. subtypes = _alleltypes.Where(x => x.GetInterfaces().Any(i => (i.GenericTypeArguments.LastOrDefault()?.Equals(gentype) == true)));
  250. if (subtypes.Any())
  251. {
  252. pageTypes.Add(new(subtypes.First().MakeGenericType(type), property));
  253. }
  254. else
  255. {
  256. try
  257. {
  258. pageTypes.Add(new(typeof(DynamicEnclosedListGrid<,>).MakeGenericType(type, gentype), property));
  259. }
  260. catch (Exception e)
  261. {
  262. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  263. }
  264. }
  265. }
  266. }
  267. }
  268. }
  269. }
  270. _enclosedlistpages[type] = pageTypes.ToArray();
  271. }
  272. pages.AddRange(pageTypes.Select(x => (Activator.CreateInstance(x.Item1, x.Item2) as IDynamicEditorPage)!));
  273. }
  274. #endregion
  275. #region Columns
  276. public static IColumns LoadEditorColumns(Type T, IColumns? additional = null)
  277. {
  278. var result = Columns.Create(T, ColumnTypeFlags.EditorColumns);
  279. if(additional is not null)
  280. {
  281. foreach (var col in additional)
  282. result.Add(col.Property);
  283. }
  284. foreach (var col in result.ColumnNames().ToArray())
  285. {
  286. var prop = DatabaseSchema.Property(T, col);
  287. if (prop?.Editor is DataLookupEditor dataLookup)
  288. {
  289. foreach (var lookupColumn in LookupFactory.DefineLookupFilterColumns(T, prop.Name))
  290. {
  291. result.Add(lookupColumn);
  292. }
  293. }
  294. }
  295. return result;
  296. }
  297. public static Columns<T> LoadEditorColumns<T>(Columns<T>? additional = null) => (LoadEditorColumns(typeof(T), additional) as Columns<T>)!;
  298. #endregion
  299. #region Editor Values
  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)
  409. {
  410. dynamicGrid.Margin = new Thickness(5);
  411. var window = new ThemableWindow { Title = title, Content = dynamicGrid };
  412. dynamicGrid.Refresh(true, true);
  413. return window;
  414. }
  415. public static Window CreateGridWindow(string title, Type entityType, Type? gridType = null)
  416. {
  417. gridType ??= typeof(DynamicGrid<>);
  418. var grid = CreateDynamicGrid(gridType, entityType);
  419. return CreateGridWindow(title, grid);
  420. }
  421. public static Window CreateGridWindow<TGrid, TEntity>(string title)
  422. where TEntity : BaseObject
  423. where TGrid : IDynamicGrid
  424. {
  425. return CreateGridWindow(title, typeof(TEntity), typeof(TGrid));
  426. }
  427. public static Window CreateGridWindow<TEntity>(string title)
  428. where TEntity : BaseObject
  429. {
  430. return CreateGridWindow(title, typeof(TEntity));
  431. }
  432. #endregion
  433. #region Non-modal Editing
  434. public class DynamicGridEntityEditLock(IEnumerable<Guid> ids)
  435. {
  436. public HashSet<Guid> ObjectIDs { get; set; } = ids.ToHashSet();
  437. public ISubPanel? Panel { get; set; }
  438. }
  439. private static Dictionary<Guid, DynamicGridEntityEditLock> CurrentEditLocks = new();
  440. /// <summary>
  441. /// Attempt to begin editing <paramref name="objs"/>, failing if those entities are already being edited elsewhere.
  442. /// </summary>
  443. /// <remarks>
  444. /// If returns <see langword="true"/>, then <paramref name="editLock"/> will contain a new edit lock which contains the
  445. /// new entities. Otherwise, <paramref name="editLock"/> will be the lock on the entities that are already being edited.
  446. /// </remarks>
  447. public static bool TryEdit(BaseObject[] objs, out DynamicGridEntityEditLock editLock)
  448. {
  449. lock (CurrentEditLocks)
  450. {
  451. var ids = new List<Guid>();
  452. foreach(var obj in objs)
  453. {
  454. if(obj is Entity entity && entity.ID != Guid.Empty)
  455. {
  456. if (CurrentEditLocks.TryGetValue(entity.ID, out editLock))
  457. {
  458. return false;
  459. }
  460. else
  461. {
  462. ids.Add(entity.ID);
  463. }
  464. }
  465. }
  466. editLock = new(ids);
  467. foreach(var id in ids)
  468. {
  469. CurrentEditLocks.Add(id, editLock);
  470. }
  471. return true;
  472. }
  473. }
  474. public static void FinishEdit(BaseObject[] objs)
  475. {
  476. lock (CurrentEditLocks)
  477. {
  478. foreach(var obj in objs)
  479. {
  480. if(obj is Entity entity && entity.ID != Guid.Empty)
  481. {
  482. if(CurrentEditLocks.Remove(entity.ID, out var editLock))
  483. {
  484. editLock.ObjectIDs.Remove(entity.ID);
  485. }
  486. }
  487. }
  488. }
  489. }
  490. #endregion
  491. #region Editing BaseObject
  492. /// <summary>
  493. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a list of <see cref="BaseObject"/>s. Use for objects not saved in the database.
  494. /// </summary>
  495. /// <typeparam name="T"></typeparam>
  496. /// <param name="items"></param>
  497. /// <param name="pageDataHandler"></param>
  498. /// <param name="preloadPages"></param>
  499. /// <returns></returns>
  500. public static bool EditObjects<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  501. where T : BaseObject, new()
  502. {
  503. var grid = new DynamicItemsListGrid<T>();
  504. customiseGrid?.Invoke(grid);
  505. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  506. }
  507. /// <summary>
  508. /// Edit (using <see cref="DynamicItemsListGrid{T}"/>) a <see cref="BaseObject"/>. Use for objects not saved in the database.
  509. /// </summary>
  510. /// <typeparam name="T"></typeparam>
  511. /// <param name="items"></param>
  512. /// <param name="pageDataHandler"></param>
  513. /// <param name="preloadPages"></param>
  514. /// <returns></returns>
  515. public static bool EditObject<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  516. where T : BaseObject, new()
  517. {
  518. var grid = new DynamicItemsListGrid<T>();
  519. customiseGrid?.Invoke(grid);
  520. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  521. }
  522. /// <summary>
  523. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a <typeparamref name="T"/>.
  524. /// </summary>
  525. /// <typeparam name="T"></typeparam>
  526. /// <param name="item"></param>
  527. /// <param name="pageDataHandler"></param>
  528. /// <param name="preloadPages"></param>
  529. /// <param name="customiseGrid"></param>
  530. /// <returns></returns>
  531. public static bool EditEntity<T>(T item, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  532. where T : Entity, new()
  533. {
  534. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  535. customiseGrid?.Invoke(grid);
  536. return grid.EditItems(new T[] { item }, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  537. }
  538. /// <summary>
  539. /// Edit (using a grid sourced with <see cref="CreateDynamicGrid{T}(Type)"/>) a list of <typeparamref name="T"/>.
  540. /// </summary>
  541. /// <typeparam name="T"></typeparam>
  542. /// <param name="item"></param>
  543. /// <param name="pageDataHandler"></param>
  544. /// <param name="preloadPages"></param>
  545. /// <param name="customiseGrid"></param>
  546. /// <returns></returns>
  547. public static bool EditEntities<T>(T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false, Action<DynamicGrid<T>>? customiseGrid = null)
  548. where T : Entity, new()
  549. {
  550. var grid = CreateDynamicGrid<T>(typeof(DynamicGrid<>));
  551. customiseGrid?.Invoke(grid);
  552. return grid.EditItems(items, PageDataHandler: pageDataHandler, PreloadPages: preloadPages);
  553. }
  554. #endregion
  555. #region Drag + Drop
  556. public static string DragFormat => typeof(DynamicGridDragFormat).FullName ?? "";
  557. /// <summary>
  558. /// Try to get data dragged from a <see cref="DynamicGrid{T}"/> from a <see cref="DragEventArgs"/>, returning <see langword="true"/>
  559. /// if data was present.
  560. /// </summary>
  561. /// <param name="e"></param>
  562. public static bool TryGetDropData(
  563. DragEventArgs e,
  564. [NotNullWhen(true)] out Type? type,
  565. [NotNullWhen(true)] out CoreTable? table)
  566. {
  567. if (e.Data.GetDataPresent(DragFormat))
  568. {
  569. var data = e.Data.GetData(DragFormat) as DynamicGridDragFormat;
  570. if (data is not null)
  571. {
  572. table = new CoreTable();
  573. foreach (var column in data.Table.Columns)
  574. {
  575. if (column is DataColumn dataColumn)
  576. {
  577. table.Columns.Add(new CoreColumn { ColumnName = dataColumn.ColumnName.Replace('_', '.'), DataType = dataColumn.DataType });
  578. }
  579. }
  580. foreach (var row in data.Table.Rows)
  581. {
  582. if (row is DataRow dataRow)
  583. {
  584. var coreRow = table.NewRow();
  585. coreRow.LoadValues(dataRow.ItemArray);
  586. table.Rows.Add(coreRow);
  587. }
  588. }
  589. type = data.Entity;
  590. return true;
  591. }
  592. }
  593. table = null;
  594. type = null;
  595. return false;
  596. }
  597. #endregion
  598. #region Style
  599. public static Brush SelectionBackground { get; set; } = new SolidColorBrush(Colors.Black);
  600. public static Brush SelectionForeground { get; set; } = new SolidColorBrush(Colors.Silver);
  601. public static Brush FilterBackground { get; set; } = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xE9, 0xF7, 0xC9));
  602. #endregion
  603. public static void PopulateFormMenu<TEntityForm, TEntity, TEntityLink>(
  604. ItemsControl menu,
  605. Guid entityID,
  606. Func<TEntity> loadEntity,
  607. bool editOnAdd = false,
  608. DynamicFormEditWindow.CustomiseDynamicFormEditWindow? customiseEditor = null)
  609. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  610. where TEntity : Entity
  611. where TEntityLink : BaseObject, IEntityLink<TEntity>, new()
  612. {
  613. var task = Task.Run(() =>
  614. {
  615. return new Client<TEntityForm>().Query(
  616. new Filter<TEntityForm>(x => x.Parent.ID).IsEqualTo(entityID),
  617. null).Rows.Select(x => x.ToObject<TEntityForm>()).ToList();
  618. });
  619. var addForm = new MenuItem { Header = "Add Form" };
  620. addForm.Click += (o, e) =>
  621. {
  622. var entity = loadEntity();
  623. var filter = LookupFactory.DefineChildFilter<TEntity, DigitalForm>(new TEntity[] { entity })
  624. ?? LookupFactory.DefineLookupFilter<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form, Array.Empty<TEntityForm>());
  625. var select = new MultiSelectDialog<DigitalForm>(
  626. filter,
  627. LookupFactory.DefineLookupColumns<TEntityForm, DigitalForm, DigitalFormLink>(x => x.Form).Add(x => x.Description),
  628. false);
  629. if(select.ShowDialog() == true)
  630. {
  631. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  632. if(digitalForm is not null)
  633. {
  634. var form = new TEntityForm
  635. {
  636. Description = digitalForm.Description
  637. };
  638. form.Parent.ID = entityID;
  639. form.Form.ID = digitalForm.ID;
  640. if (editOnAdd)
  641. {
  642. if (DynamicFormEditWindow.EditDigitalForm(form, out var dataModel, customise: customiseEditor))
  643. {
  644. dataModel.Update(null);
  645. }
  646. }
  647. else
  648. {
  649. new Client<TEntityForm>().Save(form, "Added by user");
  650. }
  651. }
  652. };
  653. };
  654. var manageForms = new MenuItem { Header = "Manage Forms..." };
  655. manageForms.Click += (o, e) =>
  656. {
  657. var window = new ThemableWindow() { Title = $"Manage {typeof(TEntity).Name} Forms" };
  658. var grid = new DynamicEntityFormGrid<TEntityForm, TEntity, TEntityLink>(loadEntity());
  659. grid.Refresh(true, true);
  660. grid.Margin = new Thickness(5);
  661. window.Content = grid;
  662. window.ShowDialog();
  663. };
  664. menu.Items.Add(addForm);
  665. menu.Items.Add(new Separator());
  666. menu.Items.Add(new MenuItem() { Header = "Loading...", IsEnabled = false });
  667. menu.Items.Add(new Separator());
  668. menu.Items.Add(manageForms);
  669. task.ContinueWith((task) =>
  670. {
  671. var entityForms = task.Result;
  672. menu.Items.Clear();
  673. menu.Items.Add(addForm);
  674. menu.Items.Add(new Separator());
  675. if (entityForms.Any())
  676. {
  677. foreach (var entityForm in entityForms)
  678. {
  679. var description = entityForm.Description;
  680. if (string.IsNullOrWhiteSpace(description))
  681. {
  682. description = entityForm.Form.Description;
  683. }
  684. var formItem = new MenuItem { Header = $"{entityForm.Number} : {description}" };
  685. formItem.Click += (o, e) =>
  686. {
  687. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, customise: customiseEditor))
  688. {
  689. dataModel.Update(null);
  690. }
  691. };
  692. menu.Items.Add(formItem);
  693. }
  694. }
  695. else
  696. {
  697. menu.Items.Add(new MenuItem() { Header = "No Forms", IsEnabled = false });
  698. }
  699. menu.Items.Add(new Separator());
  700. menu.Items.Add(manageForms);
  701. }, TaskScheduler.FromCurrentSynchronizationContext());
  702. }
  703. #region Alignment
  704. public static VerticalAlignment VerticalAlignment(this Alignment alignment)
  705. {
  706. if (alignment.Equals(Alignment.NotSet))
  707. return System.Windows.VerticalAlignment.Center;
  708. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.TopRight))
  709. return System.Windows.VerticalAlignment.Top;
  710. if (alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.MiddleRight))
  711. return System.Windows.VerticalAlignment.Center;
  712. return System.Windows.VerticalAlignment.Bottom;
  713. }
  714. public static HorizontalAlignment HorizontalAlignment(this Alignment alignment, Type datatype)
  715. {
  716. if (alignment.Equals(Alignment.NotSet))
  717. return datatype.IsNumeric() ? System.Windows.HorizontalAlignment.Right :
  718. datatype == typeof(bool) ? System.Windows.HorizontalAlignment.Center : System.Windows.HorizontalAlignment.Left;
  719. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  720. return System.Windows.HorizontalAlignment.Left;
  721. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  722. return System.Windows.HorizontalAlignment.Center;
  723. return System.Windows.HorizontalAlignment.Right;
  724. }
  725. public static TextAlignment TextAlignment(this Alignment alignment, Type datatype)
  726. {
  727. if (alignment.Equals(Alignment.NotSet))
  728. return datatype.IsNumeric() ? System.Windows.TextAlignment.Right :
  729. datatype == typeof(bool) ? System.Windows.TextAlignment.Center : System.Windows.TextAlignment.Left;
  730. if (alignment.Equals(Alignment.TopLeft) || alignment.Equals(Alignment.MiddleLeft) || alignment.Equals(Alignment.BottomLeft))
  731. return System.Windows.TextAlignment.Left;
  732. if (alignment.Equals(Alignment.TopCenter) || alignment.Equals(Alignment.MiddleCenter) || alignment.Equals(Alignment.BottomCenter))
  733. return System.Windows.TextAlignment.Center;
  734. return System.Windows.TextAlignment.Right;
  735. }
  736. #endregion
  737. }