DynamicGrid.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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));// Filter<T>.Where(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, Guid>> 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. Filter<TSourceForm>.Where(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 postItems = LoadItems(postRows.ToArray());
  857. postItems.SortBy(x => (x as ISequenceable)?.Sequence ?? 0);
  858. var updates = items.Concatenate(postItems);
  859. foreach (var update in updates)
  860. {
  861. ((ISequenceable)update).Sequence = sequence;
  862. sequence++;
  863. }
  864. if (updates.Length != 0)
  865. {
  866. SaveItems(updates);
  867. DoChanged();
  868. Refresh(false, true);
  869. }
  870. }
  871. #endregion
  872. protected virtual void ObjectToRow(T obj, CoreRow row)
  873. {
  874. row.Table.FillRow(row, obj);
  875. }
  876. #region Import / Export
  877. protected virtual CoreTable LoadImportKeys(String[] fields)
  878. {
  879. var result = new CoreTable();
  880. result.LoadColumns(Columns.None<T>().Add(fields));
  881. return result;
  882. }
  883. protected virtual Guid GetImportID()
  884. {
  885. return Guid.Empty;
  886. }
  887. protected virtual bool CustomiseImportItem(T item)
  888. {
  889. if (IsSequenced)
  890. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  891. return true;
  892. }
  893. protected virtual string CustomiseImportFileName(string filename)
  894. {
  895. return filename;
  896. }
  897. void IImportDynamicGrid.DoImport() => DoImport();
  898. protected virtual void DoImport()
  899. {
  900. var list = new DynamicImportList(
  901. typeof(T),
  902. GetImportID()
  903. );
  904. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  905. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  906. list.OnSave += (sender, entity) => SaveItem(entity as T);
  907. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  908. list.ShowDialog();
  909. Refresh(false, true);
  910. }
  911. protected virtual void CustomiseExportColumns(List<string> columnnames)
  912. {
  913. }
  914. protected virtual string CustomiseExportFileName(string filename)
  915. {
  916. return filename;
  917. }
  918. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  919. {
  920. }
  921. protected virtual void ApplyExportFilter(CoreTable table, object data)
  922. {
  923. }
  924. void IExportDynamicGrid.DoExport() => DoExport();
  925. protected virtual void DoExport()
  926. {
  927. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  928. CustomiseExportColumns(columnnames);
  929. var form = new DynamicExportForm(typeof(T), columnnames);
  930. if (form.ShowDialog() != true)
  931. return;
  932. var filters = new Filters<T>();
  933. filters.Add(DefineFilter());
  934. var predicates = GetUIComponent().GetFilterPredicates();
  935. var visiblerows = GetVisibleRows();
  936. CustomiseExportFilters(filters, visiblerows);
  937. var columns = Columns.None<T>().Add(form.Fields);
  938. var otherColumns = form.GetChildFields()
  939. .Select(x => new Tuple<Type, IColumns>(
  940. x.Key,
  941. Columns.None(x.Key).Add(x.Value)))
  942. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  943. var reloadColumns = Columns.None<T>();
  944. foreach (var column in columns)
  945. {
  946. reloadColumns.Add(column);
  947. }
  948. foreach (var column in HiddenColumns.ColumnNames)
  949. {
  950. reloadColumns.Add(column);
  951. }
  952. foreach (var column in LookupFactory.RequiredColumns<T>())
  953. {
  954. columns.Add(column);
  955. }
  956. foreach (var (column, _) in predicates)
  957. {
  958. reloadColumns.Add(column);
  959. }
  960. CoreTable? data = null;
  961. void LoadExport()
  962. {
  963. var newData = new CoreTable();
  964. newData.LoadColumns(columns);
  965. FilterRows(data.Rows, newData, filter: row =>
  966. {
  967. foreach(var (_, predicate) in predicates)
  968. {
  969. if (!predicate(row))
  970. {
  971. return false;
  972. }
  973. }
  974. return true;
  975. });
  976. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  977. list.AddRange(LoadExportTables(filters, otherColumns));
  978. DoExportTables(list);
  979. }
  980. var sort = LookupFactory.DefineSort<T>();
  981. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (table, err) =>
  982. {
  983. if (table is not null)
  984. {
  985. if (table.Offset == 0 || data is null)
  986. {
  987. data = table;
  988. if (!IsPaging)
  989. {
  990. Dispatcher.Invoke(LoadExport);
  991. }
  992. }
  993. else
  994. {
  995. data.AddPage(table);
  996. if (!IsPaging)
  997. {
  998. Dispatcher.Invoke(LoadExport);
  999. }
  1000. }
  1001. }
  1002. else if (err is not null)
  1003. {
  1004. Dispatcher.Invoke(() =>
  1005. {
  1006. MessageWindow.ShowError("Error in export.", err);
  1007. });
  1008. }
  1009. });
  1010. }
  1011. /// <summary>
  1012. /// Loads the child tables for an export, based on the filter of the parent table.
  1013. /// </summary>
  1014. /// <remarks>
  1015. /// If not overriden, defaults to creating empty tables with no records.
  1016. /// </remarks>
  1017. /// <param name="filter">Filter for the parent table.</param>
  1018. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1019. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1020. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1021. {
  1022. return tableColumns.Select(x =>
  1023. {
  1024. var table = new CoreTable();
  1025. table.LoadColumns(x.Item2);
  1026. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1027. });
  1028. }
  1029. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1030. {
  1031. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1032. ExcelExporter.DoExport(data, filename);
  1033. }
  1034. #endregion
  1035. #endregion
  1036. #region Header Actions
  1037. protected override bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns)
  1038. {
  1039. var schema = new DynamicGridObjectColumnSchema(typeof(T));
  1040. var editor = new DynamicGridColumnsEditor(schema, typeof(T)) { WindowStartupLocation = WindowStartupLocation.CenterScreen };
  1041. editor.DirectEdit = IsDirectEditMode();
  1042. editor.Columns.AddRange(VisibleColumns);
  1043. schema.OnProcessColumns += args =>
  1044. {
  1045. GetAvailableColumns?.Invoke(args);
  1046. };
  1047. if (editor.ShowDialog().Equals(true))
  1048. {
  1049. columns = editor.Columns;
  1050. return true;
  1051. }
  1052. else
  1053. {
  1054. columns = null;
  1055. return false;
  1056. }
  1057. }
  1058. #endregion
  1059. #region Drag + Drop
  1060. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1061. {
  1062. Logger.Send(LogType.Information, "", "DragTable");
  1063. var data = new DataObject();
  1064. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1065. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1066. return effect;
  1067. }
  1068. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1069. {
  1070. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1071. var table = new CoreTable();
  1072. table.LoadColumns(Data.Columns);
  1073. table.LoadRows(rows);
  1074. return DragTable(typeof(T), table);
  1075. }
  1076. #endregion
  1077. }
  1078. #region Styling
  1079. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1080. {
  1081. public DynamicGridRowStyle() : base(null)
  1082. {
  1083. }
  1084. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1085. {
  1086. }
  1087. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1088. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1089. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1090. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1091. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1092. }
  1093. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1094. {
  1095. public DynamicGridCellStyle() : base(null)
  1096. {
  1097. }
  1098. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1099. {
  1100. }
  1101. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1102. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1103. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1104. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1105. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1106. }
  1107. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1108. // This should show nothing for false, and a tick in a box for true
  1109. public class BoolToImageConverter : AbstractConverter<bool, ImageSource?>
  1110. {
  1111. public ImageSource TrueValue { get; set; }
  1112. public ImageSource? FalseValue { get; set; }
  1113. public BoolToImageConverter()
  1114. {
  1115. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1116. }
  1117. public override ImageSource? Convert(bool value)
  1118. {
  1119. return value ? TrueValue : FalseValue;
  1120. }
  1121. public override bool Deconvert(ImageSource? value)
  1122. {
  1123. return ImageUtils.IsEqual(value as BitmapImage, TrueValue as BitmapImage);
  1124. }
  1125. }
  1126. public class StringToColorImageConverter : IValueConverter
  1127. {
  1128. private readonly int _height = 50;
  1129. private readonly int _width = 25;
  1130. private readonly Dictionary<string, BitmapImage> cache = new();
  1131. public StringToColorImageConverter(int width, int height)
  1132. {
  1133. _width = width;
  1134. _height = height;
  1135. }
  1136. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1137. {
  1138. var str = value?.ToString();
  1139. if (str is null)
  1140. return null;
  1141. var colorcode = str.TrimStart('#');
  1142. if (!cache.ContainsKey(colorcode))
  1143. {
  1144. var col = ImageUtils.StringToColor(colorcode);
  1145. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1146. cache[colorcode] = bmp.AsBitmapImage();
  1147. }
  1148. var result = cache[colorcode];
  1149. return result;
  1150. }
  1151. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1152. {
  1153. return null;
  1154. }
  1155. }
  1156. public class StringArrayConverter : IValueConverter
  1157. {
  1158. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1159. {
  1160. if (value is string[] strArray)
  1161. {
  1162. return string.Join("\n", strArray);
  1163. }
  1164. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1165. return null;
  1166. }
  1167. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1168. {
  1169. return value;
  1170. }
  1171. }
  1172. #endregion
  1173. [Serializable]
  1174. class DynamicGridDragFormat
  1175. {
  1176. private string entity;
  1177. public DataTable Table { get; set; }
  1178. public Type Entity
  1179. {
  1180. get => CoreUtils.GetEntity(entity);
  1181. [MemberNotNull(nameof(entity))]
  1182. set => entity = value.EntityName();
  1183. }
  1184. public DynamicGridDragFormat(DataTable table, Type entity)
  1185. {
  1186. Table = table;
  1187. Entity = entity;
  1188. }
  1189. }