DynamicGrid.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Data;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using InABox.Clients;
  15. using InABox.Core;
  16. using InABox.Wpf;
  17. using InABox.WPF;
  18. using Color = System.Drawing.Color;
  19. using Columns = InABox.Core.Columns;
  20. using String = System.String;
  21. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  22. using System.Threading;
  23. using System.Diagnostics.CodeAnalysis;
  24. namespace InABox.DynamicGrid;
  25. public abstract class DynamicGrid<T> : BaseDynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>,
  26. IImportDynamicGrid, IExportDynamicGrid, IDuplicateDynamicGrid, IHelpDynamicGrid
  27. where T : BaseObject, new()
  28. {
  29. #region Events
  30. public ValidateEvent<T>? OnValidate { get; set; }
  31. public event OnDefineFilter? OnDefineFilter;
  32. public event OnCreateItem? OnCreateItem;
  33. public event OnAfterCreateItem? OnAfterCreateItem;
  34. public event EditorValueChangedHandler? OnEditorValueChanged;
  35. public event OnAfterEditorValueChanged? OnAfterEditorValueChangedEvent;
  36. private List<(OnCustomiseEditor, OnCustomiseEditor<T>)> _customiseEditorEvents;
  37. event OnCustomiseEditor? IDynamicGrid.OnCustomiseEditor
  38. {
  39. add
  40. {
  41. if (value is null) return;
  42. void dlg(IDynamicEditorForm sender, T[]? items, DynamicGridColumn column, BaseEditor editor)
  43. {
  44. value?.Invoke(sender, items, column, editor);
  45. }
  46. _customiseEditorEvents ??= new();
  47. _customiseEditorEvents.Add((value, dlg));
  48. OnCustomiseEditor += dlg;
  49. }
  50. remove
  51. {
  52. var (_, dlg) = _customiseEditorEvents.FirstOrDefault(x => x.Item1 == value);
  53. if(dlg is not null)
  54. {
  55. OnCustomiseEditor -= dlg;
  56. }
  57. }
  58. }
  59. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  60. public event EntitySaveEvent? OnBeforeSave;
  61. public event EntitySaveEvent? OnAfterSave;
  62. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  63. public event EditorLoaded? OnEditorLoaded;
  64. public event OnLoadEditorButtons<T>? OnLoadEditorButtons;
  65. #endregion
  66. protected virtual string HelpSlug()
  67. {
  68. return typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_");
  69. }
  70. string IHelpDynamicGrid.HelpSlug() => HelpSlug();
  71. protected override bool CanDuplicate => typeof(T).IsAssignableTo(typeof(IDuplicatable));
  72. public DynamicGrid() : base()
  73. {
  74. }
  75. protected sealed override void PreInit()
  76. {
  77. MasterColumns = new DynamicGridColumns();
  78. MasterColumns.ExtractColumns(typeof(T));
  79. HiddenColumns = new HiddenColumnsList();
  80. if (typeof(T).IsAssignableTo(typeof(ISequenceable)))
  81. {
  82. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  83. }
  84. }
  85. protected override void Init()
  86. {
  87. }
  88. #region IDynamicGridUIComponentParent
  89. protected override IDynamicGridUIComponent CreateUIComponent()
  90. {
  91. return new DynamicGridGridUIComponent<T>
  92. {
  93. Parent = this
  94. };
  95. }
  96. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  97. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  98. => EntityChanged(obj, row, changedColumn, changes);
  99. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  100. {
  101. var result = new Dictionary<string, object?>();
  102. foreach (var (col, value) in updates)
  103. {
  104. UpdateRow(row, col.ColumnName, value, refresh: false);
  105. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  106. }
  107. EntityChanged(obj, row, changedColumn, result);
  108. }
  109. #endregion
  110. protected override DynamicGridRowStyleSelector GetRowStyleSelector()
  111. {
  112. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  113. }
  114. public DynamicGridColumns MasterColumns { get; protected set; }
  115. public override void OnItemSourceChanged(object value)
  116. {
  117. Data = value as CoreTable;
  118. Refresh(true, true);
  119. }
  120. public class HiddenColumnsList
  121. {
  122. private List<string> Columns { get; set; } = new();
  123. public IEnumerable<string> ColumnNames => Columns;
  124. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  125. public void Add(IColumn column) => Add(column.Property);
  126. public void Add(string column)
  127. {
  128. if (!Contains(column))
  129. Columns.Add(column);
  130. }
  131. public bool Contains(string column) => Columns.Contains(column);
  132. public void Add(IColumns columns)
  133. {
  134. foreach (var _column in columns)
  135. Add(_column);
  136. }
  137. }
  138. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  139. public HiddenColumnsList HiddenColumns { get; private set; }
  140. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  141. #region Options
  142. protected override void DoReconfigure(DynamicGridOptions options)
  143. {
  144. options.ReorderRows = IsSequenced;
  145. }
  146. #endregion
  147. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  148. {
  149. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  150. SaveItem(obj);
  151. foreach (var (key, value) in changes)
  152. {
  153. if (row.Table.GetColumnIndex(key) > -1)
  154. row[key] = value;
  155. }
  156. GetUIComponent().UpdateRow(row);
  157. }
  158. #region Column Handling
  159. /// <summary>
  160. /// Create a set of <see cref="DynamicGridColumns"/> according to the natural default sizes and formats and captions, based on the contents of <paramref name="columns"/>.
  161. /// </summary>
  162. /// <param name="columns"></param>
  163. /// <returns></returns>
  164. protected DynamicGridColumns ExtractColumns(Columns<T> columns)
  165. {
  166. var cols = new DynamicGridColumns();
  167. foreach (var col in columns)
  168. {
  169. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  170. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  171. cols.Add(mc);
  172. }
  173. return cols;
  174. }
  175. DynamicGridColumns IDynamicGrid.ExtractColumns(IColumns columns)
  176. {
  177. var cols = new DynamicGridColumns();
  178. foreach (var col in columns)
  179. {
  180. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  181. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  182. cols.Add(mc);
  183. }
  184. return cols;
  185. }
  186. public override DynamicGridColumns GenerateColumns()
  187. {
  188. var defaultCols = DefaultColumns.GetDefaultColumns(typeof(T)).Select(x => x.Property).ToArray();
  189. Columns<T> cols;
  190. if(defaultCols.Length == 0)
  191. {
  192. cols = IsDirectEditMode()
  193. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  194. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  195. }
  196. else
  197. {
  198. IEnumerable<IProperty> propList;
  199. if (IsDirectEditMode())
  200. {
  201. propList = defaultCols
  202. .Where(x => x.Parent is null || !x.HasParentEntityLink() || (x.IsForeignKey() && !x.Parent.HasParentEntityLink()));
  203. }
  204. else
  205. {
  206. // Ignore foreign keys.
  207. propList = defaultCols.Where(x => !x.IsForeignKey());
  208. }
  209. cols = Columns.None<T>().AddRange(propList.Select(x => new Column<T>(x)));
  210. }
  211. var columns = ExtractColumns(cols);
  212. OnGenerateColumns?.Invoke(this, new GenerateColumnsEventArgs(columns));
  213. return columns;
  214. }
  215. public event GenerateColumnsEvent? OnGenerateColumns;
  216. public event SaveColumnsEvent? OnSaveColumns;
  217. public event GetAvailableColumnsEvent? GetAvailableColumns;
  218. protected override void SaveColumns(DynamicGridColumns columns)
  219. {
  220. OnSaveColumns?.Invoke(this, new(columns));
  221. }
  222. #endregion
  223. #region Refresh / Reload
  224. protected abstract void Reload(
  225. Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort,
  226. CancellationToken token, Action<CoreTable?, Exception?> action);
  227. public Filter<T>? DefineFilter()
  228. {
  229. if (OnDefineFilter is null)
  230. return null;
  231. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  232. return result;
  233. }
  234. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  235. {
  236. var result = selection == Selection.None
  237. ? Enumerable.Empty<TType>()
  238. : selection == Selection.Selected
  239. ? SelectedRows.Select(r => r.Get(column))
  240. : Data.ExtractValues(column);
  241. return result;
  242. }
  243. protected sealed override void ReloadData(CancellationToken token, Action<CoreTable?, Exception?> action)
  244. {
  245. _lookupcache.Clear();
  246. var criteria = new Filters<T>();
  247. var filter = DefineFilter();
  248. if (filter != null)
  249. criteria.Add(filter);
  250. var columns = DataColumns();
  251. var sort = LookupFactory.DefineSort<T>();
  252. if (sort == null && IsSequenced)
  253. sort = new SortOrder<T>("Sequence");
  254. Reload(criteria, columns, ref sort, token, action);
  255. }
  256. public Columns<T> DataColumns()
  257. {
  258. var columns = Columns.None<T>();
  259. foreach (var column in VisibleColumns)
  260. columns.Add(column.ColumnName);
  261. foreach (var column in HiddenColumns.ColumnNames)
  262. columns.Add(new Column<T>(column));
  263. if (!Options.ReadOnly)
  264. {
  265. foreach (var column in LookupFactory.RequiredColumns<T>())
  266. {
  267. columns.Add(column);
  268. }
  269. }
  270. return columns;
  271. }
  272. public void UpdateRow(CoreRow row, T obj, bool invalidateRow = true)
  273. {
  274. ObjectToRow(obj, row);
  275. if (_recordmap.TryGetValue(row, out var _value))
  276. ObjectToRow(obj, _value);
  277. if (invalidateRow)
  278. InvalidateRow(row);
  279. }
  280. public void UpdateRows(CoreRow[] rows, T[] objs, bool invalidateRows = true)
  281. {
  282. for(var i = 0; i < objs.Length; ++i)
  283. {
  284. UpdateRow(rows[i], objs[i], invalidateRow: invalidateRows);
  285. }
  286. }
  287. public void AddRow(T data)
  288. {
  289. if (MasterData is null) return;
  290. MasterData.LoadRow(data);
  291. Refresh(false, false);
  292. }
  293. #endregion
  294. #region Item Manipulation
  295. #region Load/Save/Delete
  296. public virtual T[] LoadItems(IList<CoreRow> rows)
  297. {
  298. return rows.ToArray(LoadItem);
  299. }
  300. public abstract T LoadItem(CoreRow row);
  301. public abstract void SaveItem(T item);
  302. public virtual void SaveItems(IEnumerable<T> items)
  303. {
  304. foreach (var item in items)
  305. SaveItem(item);
  306. }
  307. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  308. {
  309. return true;
  310. }
  311. public abstract void DeleteItems(params CoreRow[] rows);
  312. protected override bool CanDeleteRows(params CoreRow[] rows) => CanDeleteItems(rows);
  313. public override void DeleteRows(params CoreRow[] rows) => DeleteItems(rows);
  314. #endregion
  315. #region Edit
  316. protected override void NewRow()
  317. {
  318. CreateItems(null);
  319. }
  320. protected void CreateItems(Func<IEnumerable<T>>? create)
  321. {
  322. var newRows = new List<CoreRow>();
  323. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  324. foreach (var item in items)
  325. {
  326. if (!AfterCreate(item))
  327. return;
  328. SaveItem(item);
  329. var datarow = Data.NewRow();
  330. ObjectToRow(item, datarow);
  331. Data.Rows.Add(datarow);
  332. newRows.Add(datarow);
  333. var masterrow = MasterData.NewRow();
  334. ObjectToRow(item, masterrow);
  335. MasterData.Rows.Add(masterrow);
  336. _recordmap[datarow] = masterrow;
  337. }
  338. InvalidateGrid();
  339. SelectedRows = newRows.ToArray();
  340. DoChanged();
  341. }
  342. public virtual DynamicEditorPages LoadEditorPages(T item)
  343. {
  344. DynamicEditorPages pages = new DynamicEditorPages();
  345. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  346. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  347. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  348. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  349. pages.RemoveAll(x => !x.Visible);
  350. foreach (var page in pages)
  351. page.Ready = false;
  352. return pages;
  353. }
  354. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  355. {
  356. buttons.Clear();
  357. buttons.Add(
  358. "",
  359. Wpf.Resources.help.AsBitmapImage(),
  360. item,
  361. (f, i) =>
  362. {
  363. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  364. { UseShellExecute = true });
  365. }
  366. );
  367. OnLoadEditorButtons?.Invoke(item, buttons);
  368. }
  369. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  370. {
  371. form.BeforeLoad();
  372. }
  373. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  374. {
  375. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  376. }
  377. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  378. {
  379. var values = items.Cast<T>().ToArray();
  380. return EditItems(values, PageDataHandler, PreloadPages);
  381. }
  382. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  383. {
  384. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  385. var buttons = new DynamicEditorButtons();
  386. if (items.Length == 1)
  387. LoadEditorButtons(items.First(), buttons);
  388. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  389. editor.OnCustomiseColumns = (sender, columns) =>
  390. {
  391. columns.Clear();
  392. columns.AddRange(MasterColumns);
  393. };
  394. editor.OnDefineEditor = (o, c) =>
  395. {
  396. var result = GetEditor(o, c);
  397. if (result != null)
  398. result = result.CloneEditor();
  399. return result;
  400. };
  401. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  402. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  403. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  404. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  405. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  406. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  407. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  408. editor.OnCreateEditorControl += OnCreateEditorControl;
  409. editor.OnValidateData += (o, i) => ValidateData(items);
  410. editor.OnSelectPage += SelectPage;
  411. editor.OnSaveItem = (o, e) =>
  412. {
  413. try
  414. {
  415. using var Wait = new WaitCursor();
  416. DoBeforeSave(editor, items);
  417. if (items.Length == 1)
  418. editor.UnloadEditorPages(false);
  419. foreach (var item in items)
  420. SaveItem(item);
  421. if (items.Length == 1)
  422. editor.UnloadEditorPages(true);
  423. DoAfterSave(editor, items);
  424. }
  425. catch (Exception err)
  426. {
  427. MessageBox.Show(err.Message);
  428. e.Cancel = true;
  429. }
  430. };
  431. BeforeLoad(editor, items);
  432. editor.Items = items;
  433. AfterLoad(editor, items);
  434. }
  435. protected virtual void OnCreateEditorControl(string column, BaseEditor editor, IDynamicEditorControl control)
  436. {
  437. }
  438. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  439. {
  440. CustomiseEditor(sender, (T[])items, column, editor);
  441. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  442. }
  443. protected virtual void CustomiseEditor(IDynamicEditorForm form, T[] items, DynamicGridColumn column, BaseEditor editor)
  444. {
  445. CustomiseEditor(column, editor);
  446. }
  447. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  448. {
  449. OnAfterSave?.Invoke(editor, items);
  450. }
  451. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  452. {
  453. OnBeforeSave?.Invoke(editor, items);
  454. }
  455. /// <summary>
  456. /// Edit the <paramref name="items"/> with a non-modal editor window, attaching them to the <paramref name="host"/> provided.
  457. /// </summary>
  458. /// <param name="items">List of objects to edit.</param>
  459. /// <param name="callback">A callback for when the items are finished being edited.</param>
  460. public virtual void EditItemsNonModal(ISubPanelHost host, T[] items, Action<T[], bool> callback, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  461. {
  462. if (!DynamicGridUtils.TryEdit(items, out var editLock))
  463. {
  464. if(editLock.Panel is Window window)
  465. {
  466. Task.Delay(100).ContinueWith(task =>
  467. {
  468. window.WindowState = WindowState.Normal;
  469. window.Activate();
  470. }, TaskScheduler.FromCurrentSynchronizationContext());
  471. }
  472. else
  473. {
  474. MessageWindow.ShowMessage("One or more items are already being edited in an open window. You cannot edit the same entity multiple times simultaneously.", "Simultaneous edit.");
  475. }
  476. return;
  477. }
  478. DynamicEditorForm editor;
  479. using (var cursor = new WaitCursor())
  480. {
  481. editor = new DynamicEditorForm();
  482. editor.SetValue(Panel.ZIndexProperty, 999);
  483. editor.Form.DisableOKIfUnchanged = true;
  484. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  485. OnEditorLoaded?.Invoke(editor, items);
  486. }
  487. editLock.Panel = editor;
  488. host.AddSubPanel(editor);
  489. editor.SubPanelClosed += o =>
  490. {
  491. try
  492. {
  493. DynamicGridUtils.FinishEdit(items);
  494. callback(items, editor.Result == true);
  495. }
  496. catch(Exception e)
  497. {
  498. MessageWindow.ShowError("Error occurred while closing editor.", e);
  499. }
  500. };
  501. editor.Show();
  502. }
  503. /// <summary>
  504. /// Edit the <paramref name="items"/> with a modal editor window.
  505. /// </summary>
  506. /// <param name="items">List of objects to edit.</param>
  507. /// <returns><see langword="true"/> if the items were saved.</returns>
  508. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  509. {
  510. DynamicEditorForm editor;
  511. using (var cursor = new WaitCursor())
  512. {
  513. editor = new DynamicEditorForm()
  514. {
  515. WindowStartupLocation = WindowStartupLocation.CenterScreen
  516. };
  517. editor.SetValue(Panel.ZIndexProperty, 999);
  518. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  519. OnEditorLoaded?.Invoke(editor, items);
  520. }
  521. return editor.ShowDialog() == true;
  522. }
  523. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  524. {
  525. var changes = new Dictionary<string, object?>();
  526. OnAfterEditorValueChanged(grid, items, args, changes);
  527. OnAfterEditorValueChangedEvent?.Invoke(grid, args);
  528. return changes;
  529. }
  530. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  531. {
  532. }
  533. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  534. {
  535. /*if (items.First() is IDimensioned dimensioned)
  536. {
  537. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  538. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  539. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  540. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  541. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  542. }*/
  543. }
  544. private List<string>? ValidateData(T[] items)
  545. {
  546. var errors = new List<string>();
  547. DoValidate(items, errors);
  548. OnValidate?.Invoke(this, items, errors);
  549. return errors.Count != 0 ? errors : null;
  550. }
  551. protected virtual void DoValidate(T[] items, List<string> errors)
  552. {
  553. }
  554. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  555. {
  556. editor.AfterLoad();
  557. }
  558. protected virtual void SelectPage(object sender, BaseObject[]? items)
  559. {
  560. }
  561. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  562. {
  563. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  564. if (OnEditorValueChanged != null)
  565. {
  566. var newchanges = OnEditorValueChanged(editor, name, value);
  567. foreach (var key in newchanges.Keys)
  568. result[key] = newchanges[key];
  569. }
  570. return result;
  571. }
  572. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  573. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  574. {
  575. if (sender.EditorDefinition is not ILookupEditor editor)
  576. return;
  577. var colname = sender.ColumnName;
  578. if (async)
  579. {
  580. Task.Run(() =>
  581. {
  582. try
  583. {
  584. var values = editor.Values(colname, items);
  585. Dispatcher.Invoke(
  586. () =>
  587. {
  588. try
  589. {
  590. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  591. sender.LoadLookups(values);
  592. }
  593. catch (Exception e2)
  594. {
  595. Logger.Send(LogType.Information, typeof(T).Name,
  596. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  597. }
  598. }
  599. );
  600. }
  601. catch (Exception e)
  602. {
  603. Logger.Send(LogType.Information, typeof(T).Name,
  604. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  605. }
  606. });
  607. }
  608. else
  609. {
  610. var values = editor.Values(colname, items);
  611. sender.LoadLookups(values);
  612. }
  613. }
  614. /// <summary>
  615. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  616. /// </summary>
  617. /// <param name="item">The object being edited.</param>
  618. /// <param name="column">The column of the editor.</param>
  619. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  620. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  621. {
  622. return column.Editor ?? DatabaseSchema.Property(item.GetType(), column.ColumnName)?.Editor;
  623. }
  624. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  625. {
  626. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  627. }
  628. protected virtual void SetEditorValue(object item, string name, object value)
  629. {
  630. try
  631. {
  632. CoreUtils.SetPropertyValue(item, name, value);
  633. }
  634. catch (Exception e)
  635. {
  636. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  637. }
  638. }
  639. protected virtual object? GetEditorValue(object item, string name)
  640. {
  641. return CoreUtils.GetPropertyValue(item, name);
  642. }
  643. protected override bool CanCreateRows() => CanCreateItems();
  644. protected virtual bool CanCreateItems()
  645. {
  646. return true;
  647. }
  648. protected override bool EditRows(CoreRow[]? rows)
  649. {
  650. if(rows is null)
  651. {
  652. if (!CanCreateItems())
  653. return false;
  654. var item = CreateItem();
  655. if (!AfterCreate(item))
  656. return false;
  657. if(Options.NonModalEditorHost is not null)
  658. {
  659. EditItemsNonModal(Options.NonModalEditorHost, [item], (items, result) =>
  660. {
  661. if (result)
  662. {
  663. var row = Data.NewRow();
  664. ObjectToRow(item, row);
  665. Data.Rows.Add(row);
  666. var masterrow = MasterData.NewRow();
  667. ObjectToRow(item, masterrow);
  668. MasterData.Rows.Add(masterrow);
  669. _recordmap[row] = masterrow;
  670. InvalidateGrid();
  671. SelectedRows = [row];
  672. DoChanged();
  673. }
  674. });
  675. return false;
  676. }
  677. else
  678. {
  679. if (EditItems([item]))
  680. {
  681. //_CurrentRow = Data.Rows.Count;
  682. var row = Data.NewRow();
  683. ObjectToRow(item, row);
  684. Data.Rows.Add(row);
  685. var masterrow = MasterData.NewRow();
  686. ObjectToRow(item, masterrow);
  687. MasterData.Rows.Add(masterrow);
  688. _recordmap[row] = masterrow;
  689. InvalidateGrid();
  690. SelectedRows = [row];
  691. DoChanged();
  692. return true;
  693. }
  694. return false;
  695. }
  696. }
  697. else
  698. {
  699. var items = Array.Empty<T>();
  700. using (new WaitCursor())
  701. {
  702. Stopwatch sw = new Stopwatch();
  703. sw.Start();
  704. items = LoadItems(rows);
  705. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  706. sw.Stop();
  707. }
  708. if (items.Length != 0)
  709. {
  710. var snaps = items.ToArray(x => x.TakeSnapshot());
  711. if(Options.NonModalEditorHost is not null)
  712. {
  713. EditItemsNonModal(Options.NonModalEditorHost, items, (items, result) =>
  714. {
  715. if (result)
  716. {
  717. var sel = SelectedRows;
  718. UpdateRows(rows, items, invalidateRows: false);
  719. InvalidateGrid();
  720. SelectedRows = sel;
  721. DoChanged();
  722. }
  723. else
  724. {
  725. foreach(var snap in snaps)
  726. {
  727. snap.ResetObject();
  728. }
  729. }
  730. });
  731. return false;
  732. }
  733. else
  734. {
  735. if (EditItems(items))
  736. {
  737. var sel = SelectedRows;
  738. UpdateRows(rows, items, invalidateRows: false);
  739. InvalidateGrid();
  740. SelectedRows = sel;
  741. DoChanged();
  742. return true;
  743. }
  744. else
  745. {
  746. foreach(var snap in snaps)
  747. {
  748. snap.ResetObject();
  749. }
  750. }
  751. }
  752. return false;
  753. }
  754. return false;
  755. }
  756. }
  757. #endregion
  758. #region Duplicate
  759. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  760. {
  761. return LoadItems(rows);
  762. }
  763. bool IDuplicateDynamicGrid.DoDuplicate(CoreRow[] rows) => DoDuplicate(rows);
  764. protected virtual bool DoDuplicate(CoreRow[] rows)
  765. {
  766. if (rows.Length == 0)
  767. {
  768. MessageBox.Show("Please select at least one record to duplicate!");
  769. return false;
  770. }
  771. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  772. if (!ids.Any())
  773. {
  774. MessageBox.Show("Please select at least one record to duplicate!");
  775. return false;
  776. }*/
  777. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  778. if (duplicator is null)
  779. {
  780. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  781. return false;
  782. }
  783. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  784. return true;
  785. }
  786. #endregion
  787. public virtual T CreateItem()
  788. {
  789. var result = new T();
  790. OnCreateItem?.Invoke(this, result);
  791. return result;
  792. }
  793. public virtual bool AfterCreate(T item)
  794. {
  795. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  796. }
  797. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  798. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  799. where TTargetType : Entity, new()
  800. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  801. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  802. {
  803. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  804. var page =
  805. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  806. if (page != null && item != null)
  807. {
  808. if (!page.Ready)
  809. page.Load(item, null);
  810. CoreTable table;
  811. if (sourceid == Guid.Empty)
  812. {
  813. table = new CoreTable();
  814. table.LoadColumns(typeof(TSourceForm));
  815. }
  816. else
  817. {
  818. table = new Client<TSourceForm>().Query(
  819. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  820. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  821. );
  822. }
  823. var newforms = new List<TTargetForm>();
  824. foreach (var row in table.Rows)
  825. {
  826. var sourceform = row.ToObject<TSourceForm>();
  827. var targetform = new TTargetForm();
  828. targetform.Form.ID = sourceform.Form.ID;
  829. targetform.Form.Synchronise(sourceform.Form);
  830. newforms.Add(targetform);
  831. }
  832. page.Items.Clear();
  833. page.LoadItems(newforms.ToArray());
  834. }
  835. }
  836. #region ClipBuffer
  837. protected virtual bool BeforeCopy(IList<T> items)
  838. {
  839. return true;
  840. }
  841. protected override void MoveRows(CoreRow[] rows, int index, bool isCopy = false)
  842. {
  843. if (!Options.ReorderRows || !IsSequenced) return;
  844. var items = LoadItems(rows);
  845. if (isCopy)
  846. {
  847. if (!BeforeCopy(items))
  848. {
  849. return;
  850. }
  851. }
  852. var sequence = index < Data.Rows.Count
  853. ? Data.Rows[index].Get<ISequenceable, long>(x => x.Sequence)
  854. : Data.Rows[^1].Get<ISequenceable, long>(x => x.Sequence) + 1;
  855. var postRows = Data.Rows.Where(r => !rows.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  856. var updates = items.Concatenate(LoadItems(postRows.ToArray()));
  857. foreach (var update in updates)
  858. {
  859. ((ISequenceable)update).Sequence = sequence;
  860. sequence++;
  861. }
  862. if (updates.Length != 0)
  863. {
  864. SaveItems(updates);
  865. DoChanged();
  866. Refresh(false, true);
  867. }
  868. }
  869. #endregion
  870. protected virtual void ObjectToRow(T obj, CoreRow row)
  871. {
  872. row.Table.FillRow(row, obj);
  873. }
  874. #region Import / Export
  875. protected virtual CoreTable LoadImportKeys(String[] fields)
  876. {
  877. var result = new CoreTable();
  878. result.LoadColumns(Columns.None<T>().Add(fields));
  879. return result;
  880. }
  881. protected virtual Guid GetImportID()
  882. {
  883. return Guid.Empty;
  884. }
  885. protected virtual bool CustomiseImportItem(T item)
  886. {
  887. if (IsSequenced)
  888. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  889. return true;
  890. }
  891. protected virtual string CustomiseImportFileName(string filename)
  892. {
  893. return filename;
  894. }
  895. void IImportDynamicGrid.DoImport() => DoImport();
  896. protected virtual void DoImport()
  897. {
  898. var list = new DynamicImportList(
  899. typeof(T),
  900. GetImportID()
  901. );
  902. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  903. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  904. list.OnSave += (sender, entity) => SaveItem(entity as T);
  905. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  906. list.ShowDialog();
  907. Refresh(false, true);
  908. }
  909. protected virtual void CustomiseExportColumns(List<string> columnnames)
  910. {
  911. }
  912. protected virtual string CustomiseExportFileName(string filename)
  913. {
  914. return filename;
  915. }
  916. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  917. {
  918. }
  919. protected virtual void ApplyExportFilter(CoreTable table, object data)
  920. {
  921. }
  922. void IExportDynamicGrid.DoExport() => DoExport();
  923. protected virtual void DoExport()
  924. {
  925. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  926. CustomiseExportColumns(columnnames);
  927. var form = new DynamicExportForm(typeof(T), columnnames);
  928. if (form.ShowDialog() != true)
  929. return;
  930. var filters = new Filters<T>();
  931. filters.Add(DefineFilter());
  932. var predicates = GetUIComponent().GetFilterPredicates();
  933. var visiblerows = GetVisibleRows();
  934. CustomiseExportFilters(filters, visiblerows);
  935. var columns = Columns.None<T>().Add(form.Fields);
  936. var otherColumns = form.GetChildFields()
  937. .Select(x => new Tuple<Type, IColumns>(
  938. x.Key,
  939. Columns.None(x.Key).Add(x.Value)))
  940. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  941. var reloadColumns = Columns.None<T>();
  942. foreach (var column in columns)
  943. {
  944. reloadColumns.Add(column);
  945. }
  946. foreach (var column in HiddenColumns.ColumnNames)
  947. {
  948. reloadColumns.Add(column);
  949. }
  950. foreach (var column in LookupFactory.RequiredColumns<T>())
  951. {
  952. columns.Add(column);
  953. }
  954. foreach (var (column, _) in predicates)
  955. {
  956. reloadColumns.Add(column);
  957. }
  958. CoreTable? data = null;
  959. void LoadExport()
  960. {
  961. var newData = new CoreTable();
  962. newData.LoadColumns(columns);
  963. FilterRows(data.Rows, newData, filter: row =>
  964. {
  965. foreach(var (_, predicate) in predicates)
  966. {
  967. if (!predicate(row))
  968. {
  969. return false;
  970. }
  971. }
  972. return true;
  973. });
  974. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  975. list.AddRange(LoadExportTables(filters, otherColumns));
  976. DoExportTables(list);
  977. }
  978. var sort = LookupFactory.DefineSort<T>();
  979. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (table, err) =>
  980. {
  981. if (table is not null)
  982. {
  983. if (table.Offset == 0 || data is null)
  984. {
  985. data = table;
  986. if (!IsPaging)
  987. {
  988. Dispatcher.Invoke(LoadExport);
  989. }
  990. }
  991. else
  992. {
  993. data.AddPage(table);
  994. if (!IsPaging)
  995. {
  996. Dispatcher.Invoke(LoadExport);
  997. }
  998. }
  999. }
  1000. else if (err is not null)
  1001. {
  1002. Dispatcher.Invoke(() =>
  1003. {
  1004. MessageWindow.ShowError("Error in export.", err);
  1005. });
  1006. }
  1007. });
  1008. }
  1009. /// <summary>
  1010. /// Loads the child tables for an export, based on the filter of the parent table.
  1011. /// </summary>
  1012. /// <remarks>
  1013. /// If not overriden, defaults to creating empty tables with no records.
  1014. /// </remarks>
  1015. /// <param name="filter">Filter for the parent table.</param>
  1016. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1017. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1018. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1019. {
  1020. return tableColumns.Select(x =>
  1021. {
  1022. var table = new CoreTable();
  1023. table.LoadColumns(x.Item2);
  1024. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1025. });
  1026. }
  1027. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1028. {
  1029. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1030. ExcelExporter.DoExport(data, filename);
  1031. }
  1032. #endregion
  1033. #endregion
  1034. #region Header Actions
  1035. protected override bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns)
  1036. {
  1037. var schema = new DynamicGridObjectColumnSchema(typeof(T));
  1038. var editor = new DynamicGridColumnsEditor(schema, typeof(T)) { WindowStartupLocation = WindowStartupLocation.CenterScreen };
  1039. editor.DirectEdit = IsDirectEditMode();
  1040. editor.Columns.AddRange(VisibleColumns);
  1041. schema.OnProcessColumns += args =>
  1042. {
  1043. GetAvailableColumns?.Invoke(args);
  1044. };
  1045. if (editor.ShowDialog().Equals(true))
  1046. {
  1047. columns = editor.Columns;
  1048. return true;
  1049. }
  1050. else
  1051. {
  1052. columns = null;
  1053. return false;
  1054. }
  1055. }
  1056. #endregion
  1057. #region Drag + Drop
  1058. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1059. {
  1060. Logger.Send(LogType.Information, "", "DragTable");
  1061. var data = new DataObject();
  1062. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1063. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1064. return effect;
  1065. }
  1066. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1067. {
  1068. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1069. var table = new CoreTable();
  1070. table.LoadColumns(Data.Columns);
  1071. table.LoadRows(rows);
  1072. return DragTable(typeof(T), table);
  1073. }
  1074. #endregion
  1075. }
  1076. #region Styling
  1077. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1078. {
  1079. public DynamicGridRowStyle() : base(null)
  1080. {
  1081. }
  1082. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1083. {
  1084. }
  1085. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1086. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1087. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1088. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1089. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1090. }
  1091. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1092. {
  1093. public DynamicGridCellStyle() : base(null)
  1094. {
  1095. }
  1096. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1097. {
  1098. }
  1099. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1100. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1101. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1102. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1103. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1104. }
  1105. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1106. // This should show nothing for false, and a tick in a box for true
  1107. public class BoolToImageConverter : AbstractConverter<bool, ImageSource?>
  1108. {
  1109. public ImageSource TrueValue { get; set; }
  1110. public ImageSource? FalseValue { get; set; }
  1111. public BoolToImageConverter()
  1112. {
  1113. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1114. }
  1115. public override ImageSource? Convert(bool value)
  1116. {
  1117. return value ? TrueValue : FalseValue;
  1118. }
  1119. public override bool Deconvert(ImageSource? value)
  1120. {
  1121. return ImageUtils.IsEqual(value as BitmapImage, TrueValue as BitmapImage);
  1122. }
  1123. }
  1124. public class StringToColorImageConverter : IValueConverter
  1125. {
  1126. private readonly int _height = 50;
  1127. private readonly int _width = 25;
  1128. private readonly Dictionary<string, BitmapImage> cache = new();
  1129. public StringToColorImageConverter(int width, int height)
  1130. {
  1131. _width = width;
  1132. _height = height;
  1133. }
  1134. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1135. {
  1136. var str = value?.ToString();
  1137. if (str is null)
  1138. return null;
  1139. var colorcode = str.TrimStart('#');
  1140. if (!cache.ContainsKey(colorcode))
  1141. {
  1142. var col = ImageUtils.StringToColor(colorcode);
  1143. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1144. cache[colorcode] = bmp.AsBitmapImage();
  1145. }
  1146. var result = cache[colorcode];
  1147. return result;
  1148. }
  1149. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1150. {
  1151. return null;
  1152. }
  1153. }
  1154. public class StringArrayConverter : IValueConverter
  1155. {
  1156. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1157. {
  1158. if (value is string[] strArray)
  1159. {
  1160. return string.Join("\n", strArray);
  1161. }
  1162. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1163. return null;
  1164. }
  1165. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1166. {
  1167. return value;
  1168. }
  1169. }
  1170. #endregion
  1171. [Serializable]
  1172. class DynamicGridDragFormat
  1173. {
  1174. private string entity;
  1175. public DataTable Table { get; set; }
  1176. public Type Entity
  1177. {
  1178. get => CoreUtils.GetEntity(entity);
  1179. [MemberNotNull(nameof(entity))]
  1180. set => entity = value.EntityName();
  1181. }
  1182. public DynamicGridDragFormat(DataTable table, Type entity)
  1183. {
  1184. Table = table;
  1185. Entity = entity;
  1186. }
  1187. }