| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886 |
- using Comal.Classes;
- using InABox.Clients;
- using InABox.Core;
- using InABox.Core.Postable;
- using InABox.DynamicGrid;
- using InABox.Wpf;
- using InABox.WPF;
- using Microsoft.CodeAnalysis.CSharp.Syntax;
- using Syncfusion.UI.Xaml.Diagram;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.Drawing;
- using System.Globalization;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media.Imaging;
- using System.Windows.Threading;
- namespace PRSDesktop;
- public class PullResultGrid<T> : DynamicItemsListGrid<T>
- where T : BaseObject, IPostable, new()
- {
- private static readonly BitmapImage tick = InABox.Wpf.Resources.tick.AsBitmapImage();
- private static readonly BitmapImage link = PRSDesktop.Resources.link.AsBitmapImage();
- private static readonly BitmapImage refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
- private class ResultItem(PullResultItem<T> item, bool selected)
- {
- public PullResultItem<T> Item { get; set; } = item;
- public bool Selected { get; set; } = selected;
- }
- public bool CanSave => _items.Any(x => x.Selected);
- private List<ResultItem> _items;
- public IEnumerable<PullResultItem<T>> Selected => _items.Where(x => x.Selected).Select(x => x.Item);
- protected DynamicGridCustomColumnsComponent<T> ColumnsComponent;
- public PullResultGrid(IPullResult<T> result)
- {
- _items = result.PulledEntities.Where(x => x.Item.PostedStatus != PostedStatus.PostFailed).Select(x => new ResultItem(x, false)).ToList();
- Items = _items.Select(x => x.Item.Item).ToList();
- ColumnsComponent = new DynamicGridCustomColumnsComponent<T>(this, typeof(T).Name);
- }
- protected override DynamicGridColumns LoadColumns()
- {
- return ColumnsComponent.LoadColumns();
- }
- protected override void SaveColumns(DynamicGridColumns columns)
- {
- ColumnsComponent.SaveColumns(columns);
- }
- protected override void LoadColumnsMenu(ContextMenu menu)
- {
- ColumnsComponent.LoadColumnsMenu(menu);
- }
- private ResultItem? GetItem(CoreRow? row)
- {
- return row is not null ? _items[_recordmap[row].Index] : null;
- }
- protected override void Init()
- {
- base.Init();
- ActionColumns.Add(new DynamicImageColumn(Selected_Image, Selected_Click) { Position = DynamicActionColumnPosition.Start });
- ActionColumns.Add(new DynamicImageColumn(Action_Image)
- {
- Position = DynamicActionColumnPosition.Start,
- ToolTip = Action_ToolTip
- });
- }
- private FrameworkElement? Action_ToolTip(DynamicActionColumn column, CoreRow? row)
- {
- var item = GetItem(row);
- if(item is null)
- {
- return column.TextToolTip("Item Import Action");
- }
- else if(item.Item.Type == PullResultType.Linked)
- {
- return column.TextToolTip("Existing PRS item linked to external item.");
- }
- else if(item.Item.Type == PullResultType.Updated)
- {
- return column.TextToolTip("Existing PRS item updated to external item.");
- }
- else if(item.Item.Type == PullResultType.New)
- {
- return column.TextToolTip("New item imported.");
- }
- else
- {
- return null;
- }
- }
- private BitmapImage? Action_Image(CoreRow? row)
- {
- var item = GetItem(row);
- if(item is null)
- {
- return null;
- }
- else if(item.Item.Type == PullResultType.Linked)
- {
- return link;
- }
- else if(item.Item.Type == PullResultType.Updated)
- {
- return refresh;
- }
- else
- {
- return null;
- }
- }
- private BitmapImage? Selected_Image(CoreRow? row)
- {
- var item = GetItem(row);
- return (item is null || item.Selected)
- ? tick
- : null;
- }
- private bool Selected_Click(CoreRow? row)
- {
- var item = GetItem(row);
- if(item is not null)
- {
- item.Selected = !item.Selected;
- DoChanged();
- InvalidateRow(row!);
- return false;
- }
- else
- {
- var menu = new ContextMenu();
- menu.AddItem("Select All", null, () =>
- {
- foreach (var item in _items)
- {
- item.Selected = true;
- }
- DoChanged();
- InvalidateGrid();
- });
- menu.AddItem("Deselect All", null, () =>
- {
- foreach (var item in _items)
- {
- item.Selected = false;
- }
- DoChanged();
- InvalidateGrid();
- });
- menu.IsOpen = true;
- return false;
- }
- }
- protected override void DoReconfigure(DynamicGridOptions options)
- {
- base.DoReconfigure(options);
- options.Clear();
- options.SelectColumns = true;
- options.FilterRows = true;
- }
- }
- internal class PosterProgressDispatcher : IPosterDispatcher
- {
- private string Message;
- private TaskCompletionSource _yield = new();
- private TaskCompletionSource? _continue = new();
- private Task? _queue;
- private string? _setMessage;
- public PosterProgressDispatcher(string? message = null)
- {
- Message = message ?? "Loading Data";
- }
- public Task ExecuteAsync(Action action)
- {
- var taskCompletionSource = new TaskCompletionSource();
- _queue = new Task(() =>
- {
- try
- {
- action();
- taskCompletionSource.SetResult();
- }
- catch(Exception e)
- {
- taskCompletionSource.SetException(e);
- }
- });
- _continue = new();
- _yield.TrySetResult();
- return Task.WhenAll(_continue.Task, taskCompletionSource.Task);
- }
- public Task<T> ExecuteAsync<T>(Func<T> func)
- {
- var taskCompletionSource = new TaskCompletionSource<T>();
- _queue = new Task(() =>
- {
- try
- {
- var result = func();
- taskCompletionSource.SetResult(result);
- }
- catch (Exception e)
- {
- taskCompletionSource.SetException(e);
- }
- });
- _continue = new();
- _yield.TrySetResult();
- return _continue.Task.ContinueWith(task => taskCompletionSource.Task.Result);
- }
- public void Report(string report)
- {
- Message = report;
- _setMessage = report;
- _continue = new();
- _yield.TrySetResult();
- _continue.Task.Wait();
- }
- public void WaitTask(Task task)
- {
- _yield = new();
- task.ContinueWith(t => _yield.TrySetResult());
- while (true)
- {
- Progress.ShowModal(Message, progress =>
- {
- while (true)
- {
- _yield.Task.Wait();
- if(_setMessage is not null)
- {
- progress.Report(_setMessage);
- _yield = new();
- _setMessage = null;
- _continue?.SetResult();
- _continue = null;
- }
- else
- {
- break;
- }
- }
- });
- if(_queue is not null)
- {
- _yield = new();
- _queue.RunSynchronously();
- _queue = null;
- _continue?.SetResult();
- _continue = null;
- }
- else
- {
- break;
- }
- }
- }
- }
- public static class PostUtils
- {
- private static readonly Inflector.Inflector inflector = new(new CultureInfo("en"));
- public static async Task PostEntitiesAsync<T>(IDataModel<T> model, Action refresh, Action? configurePost = null)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- bool retry;
- do
- {
- retry = false;
- try
- {
- var dispatcher = new PosterProgressDispatcher();
- var task = Task.Run(() =>
- {
- return PosterUtils.Process(model,
- engine =>
- {
- engine.Dispatcher = dispatcher;
- },
- engine =>
- {
- });
- });
- dispatcher.WaitTask(task);
- var result = await task;
- if (result is null)
- {
- MessageWindow.ShowMessage($"Processing failed", "Processing failed");
- refresh();
- }
- else
- {
- var failedMessages = new List<string>();
- var successCount = 0;
- foreach (var entity in result.PostedEntities)
- {
- if (entity.PostedStatus == PostedStatus.PostFailed)
- {
- failedMessages.Add(entity.PostedNote);
- }
- else
- {
- successCount++;
- }
- }
- if (successCount == 0)
- {
- MessageWindow.ShowMessage($"Processing failed:\n - {string.Join("\n - ", failedMessages)}", "Processing failed.");
- }
- else if (failedMessages.Count == 0)
- {
- MessageWindow.ShowMessage($"Processing successful; {successCount} items processed", "Processing successful.");
- }
- else
- {
- MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
- }
- refresh();
- }
- }
- catch (EmptyPostException)
- {
- MessageWindow.ShowMessage($"Please select at least one {typeof(T).Name}.", "Select items");
- }
- catch (PostFailedMessageException e)
- {
- MessageWindow.ShowMessage(e.Message, "Post failed");
- }
- catch (RepostedException)
- {
- MessageWindow.ShowMessage("At least one of the items you selected has already been processed. Processing cancelled.", "Already processed");
- }
- catch (PostCancelledException)
- {
- MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
- }
- catch (MissingSettingException e)
- {
- if (configurePost is not null && Security.CanConfigurePost<T>())
- {
- if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
- "Configure Processing?"))
- {
- bool success = false;
- if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
- {
- success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
- }
- else
- {
- success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
- }
- if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the post?", "Retry?"))
- {
- retry = true;
- }
- else
- {
- MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
- }
- }
- catch (MissingSettingsException)
- {
- if (configurePost is not null && Security.CanConfigurePost<T>())
- {
- if (MessageWindow.ShowYesNo($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
- "Configure Processing?"))
- {
- configurePost();
- }
- else
- {
- MessageWindow.ShowMessage("Processing cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage($"Processing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
- }
- }
- catch (Exception e)
- {
- MessageWindow.ShowError("Processing failed.", e);
- refresh();
- }
- } while (retry);
- }
- public static void PostEntities<T>(IDataModel<T> model, Action refresh, Action? configurePost = null)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- PostEntitiesAsync(model, refresh, configurePost).LogIfFail();
- }
- public static bool ShowPullResultGrid<T>(IPullResult<T> result, [NotNullWhen(true)] out List<PullResultItem<T>>? items)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- var resultGrid = new PullResultGrid<T>(result);
- var window = new DynamicContentDialog(resultGrid)
- {
- Title = "Select items to import:",
- CanSave = false
- };
- resultGrid.OnChanged += (o, e) => window.CanSave = resultGrid.CanSave;
- resultGrid.Refresh(true, true);
- if(window.ShowDialog() == true)
- {
- items = resultGrid.Selected.ToList();
- result.SavePull(items);
- return true;
- }
- else
- {
- items = null;
- return false;
- }
- }
- public static async Task PullEntitiesAsync<T>(Action refresh, Action? configurePost = null)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- bool retry;
- do
- {
- retry = false;
- try
- {
- var dispatcher = new PosterProgressDispatcher("Importing Data");
- var task = Task.Run(() =>
- {
- return PosterUtils.Pull<T>(
- engine =>
- {
- engine.Dispatcher = dispatcher;
- },
- engine =>
- {
- });
- });
- dispatcher.WaitTask(task);
- var result = await task;
- if (result is null)
- {
- MessageWindow.ShowMessage($"Import failed", "Import failed");
- refresh();
- }
- else
- {
- List<PullResultItem<T>>? items;
- if (!result.PulledEntities.Any(x => x.Item.PostedStatus != PostedStatus.PostFailed))
- {
- items = result.PulledEntities.ToList();
- }
- else
- {
- ShowPullResultGrid(result, out items);
- }
- if (items is null)
- {
- MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
- }
- else
- {
- var failedMessages = new List<string>();
- var successCount = 0;
- var importCount = 0;
- var updateCount = 0;
- var linkCount = 0;
- foreach (var item in items)
- {
- if (item.Item.PostedStatus == PostedStatus.PostFailed)
- {
- failedMessages.Add(item.Item.PostedNote);
- }
- else
- {
- successCount++;
- switch (item.Type)
- {
- case PullResultType.New:
- importCount++;
- break;
- case PullResultType.Linked:
- linkCount++;
- break;
- case PullResultType.Updated:
- default:
- updateCount++;
- break;
- }
- }
- }
- if (failedMessages.Count > 0 && successCount == 0)
- {
- MessageWindow.ShowMessage($"Import failed:\n - {string.Join("\n - ", failedMessages)}", "Import failed.");
- }
- else if (failedMessages.Count == 0)
- {
- if (successCount == 0)
- {
- MessageWindow.ShowMessage($"Nothing imported.", "Import successful.");
- }
- else
- {
- MessageWindow.ShowMessage($"Import successful; {importCount} items imported, {linkCount} items linked.", "Import successful.");
- }
- }
- else
- {
- MessageWindow.ShowMessage($"{successCount} items succeeded, but {failedMessages.Count} failed:\n - {string.Join("\n - ", failedMessages)}", "Partial success");
- }
- refresh();
- }
- }
- }
- catch (PullFailedMessageException e)
- {
- MessageWindow.ShowMessage(e.Message, "Import failed");
- }
- catch (PullCancelledException)
- {
- MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
- }
- catch (MissingSettingException e)
- {
- if (configurePost is not null && Security.CanConfigurePost<T>())
- {
- if (MessageWindow.ShowYesNo($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
- "Configure Import?"))
- {
- bool success = false;
- if (e.SettingsType.IsAssignableTo(typeof(IGlobalPosterSettings)))
- {
- success = PostableSettingsGrid.ConfigureGlobalPosterSettings(e.SettingsType);
- }
- else
- {
- success = PostableSettingsGrid.ConfigurePosterSettings<T>(e.SettingsType);
- }
- if (success && MessageWindow.ShowYesNo("Settings updated; Would you like to retry the import?", "Retry?"))
- {
- retry = true;
- }
- else
- {
- MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage($"'{e.Setting}' has not been set-up for {inflector.Pluralize(typeof(T).Name)}", "Unconfigured");
- }
- }
- catch (MissingSettingsException)
- {
- if (configurePost is not null && Security.CanConfigurePost<T>())
- {
- if (MessageWindow.ShowYesNo($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}. Would you like to configure this now?",
- "Configure Import?"))
- {
- configurePost();
- }
- else
- {
- MessageWindow.ShowMessage("Import cancelled.", "Cancelled");
- }
- }
- else
- {
- MessageWindow.ShowMessage($"Importing has not been configured for {inflector.Pluralize(typeof(T).Name)}!", "Unconfigured");
- }
- }
- catch (Exception e)
- {
- MessageWindow.ShowError("Import failed.", e);
- refresh();
- }
- } while (retry);
- }
- public static void PullEntities<T>(Action refresh, Action? configurePost = null)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- PullEntitiesAsync<T>(refresh, configurePost).LogIfFail();
- }
- public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, Action? configurePost = null)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- if (!Security.CanPost<T>()) return;
- var postSettings = PosterUtils.LoadPostableSettings<T>();
- Type? poster = null;
- if (!postSettings.PosterType.IsNullOrWhiteSpace())
- {
- var posterEngine = PosterUtils.GetEngine(typeof(T));
- poster = PosterUtils.GetPoster(postSettings.PosterType);
- Bitmap? image = null;
- if (postSettings.Thumbnail.ID != Guid.Empty)
- {
- var icon = new Client<Document>()
- .Load(Filter<Document>.Where(x => x.ID).IsEqualTo(postSettings.Thumbnail.ID)).FirstOrDefault();
- if (icon?.Data?.Any() == true)
- image = new ImageConverter().ConvertFrom(icon.Data) as Bitmap;
- }
- host.CreatePanelAction(new PanelAction
- {
- Caption = postSettings.ButtonName.NotWhiteSpaceOr($"Process {inflector.Pluralize(typeof(T).Name)}"),
- Image = image ?? PRSDesktop.Resources.edit,
- OnExecute = action =>
- {
- PostEntities(
- model(),
- refresh,
- configurePost);
- }
- });
- if(posterEngine.Get(out var posterEngineType, out var _) && posterEngineType.HasInterface(typeof(IPullerEngine<>)) && postSettings.ShowPullButton)
- {
- host.CreatePanelAction(new PanelAction($"Import {inflector.Pluralize(typeof(T).Name)}", image ?? PRSDesktop.Resources.doc_xls, action =>
- {
- PullEntities<T>(refresh);
- }));
- }
- if (postSettings.ShowClearButton)
- {
- host.CreatePanelAction(new PanelAction
- {
- Caption = "Clear Posted Flag",
- Image = image ?? PRSDesktop.Resources.refresh,
- OnExecute = action =>
- {
- var dataModel = model();
- foreach(var (key, table) in dataModel.ModelTables)
- {
- table.IsDefault = false;
- }
- dataModel.SetColumns<T>(Columns.Required<T>().Add(x => x.PostedStatus).Add(x => x.PostedReference).Add(x => x.PostedNote).Add(x => x.Posted));
- dataModel.SetIsDefault<T>(true);
- dataModel.LoadModel();
- var items = dataModel.GetTable<T>().ToArray<T>();
- foreach(var item in items)
- {
- item.PostedStatus = PostedStatus.NeverPosted;
- item.PostedReference = "";
- item.PostedNote = "";
- item.Posted = DateTime.MinValue;
- }
- Client.Save(items, "Cleared posted flag");
- refresh();
- }
- });
- }
- }
- if (configurePost is not null)
- {
- host.CreateSetupAction(new PanelAction
- {
- Caption = $"Configure {CoreUtils.Neatify(typeof(T).Name)} Processing",
- OnExecute = action =>
- {
- configurePost();
- }
- });
- var configures = poster?.GetInterfaces(typeof(IConfigureMapsPoster<,>)).ToArray() ?? [];
- if(configures.Length > 0)
- {
- host.CreateSetupAction(new PanelAction
- {
- Caption = $"Configure Post Maps...",
- OnPopulate = action =>
- {
- return configures.ToArray(x =>
- {
- var tConfigure = x.GenericTypeArguments[0];
- return new PanelActionEntry<Type>(tConfigure.Name, null, x.GenericTypeArguments[1], ConfigureMaps);
- });
- }
- });
- }
- }
- }
- private class ConfigureItem(object? value, string display, string reference)
- {
- public object? Value { get; } = value;
- public string Display { get; } = display;
- public string Reference { get; } = reference;
- }
- private static void ConfigureMaps(PanelActionEntry<Type> entry) // entry.Data is a definition of IPosterMapConfigurer
- {
- try
- {
- var configurerType = entry.Data!;
- var configurer = (Activator.CreateInstance(configurerType) as IPosterMapConfigurer)!;
- var dispatcher = new PosterProgressDispatcher("Loading Maps");
- var task = Task.Run(() => configurer.GetMaps(dispatcher));
- dispatcher.WaitTask(task);
- var allItems =
- CoreUtils.One(new ConfigureItem(null, "(Blank)", ""))
- .Concat(task.Result.OfType<object?>().Select(x => new ConfigureItem(x, configurer.MapDescriptor(x), configurer.Reference(x))))
- .ToArray();
- var tConfigure = configurerType.GetInterfaceDefinition(typeof(IPosterMapConfigurer<>))!.GenericTypeArguments[0];
- var grid = (DynamicGridUtils.CreateDynamicGrid(typeof(DynamicItemsListGrid<>), tConfigure) as IDynamicItemsListGrid)!;
- var window = new DynamicContentDialog((grid as FrameworkElement)!)
- {
- Title = $"Configure {tConfigure.Name} maps"
- };
- grid.AddHiddenColumn(CoreUtils.GetFullPropertyName<IPostableFragment, string>(x => x.PostedReference));
- grid.Reconfigure(options =>
- {
- options.Clear();
- });
- grid.ActionColumns.Add(new DynamicTemplateColumn(row =>
- {
- var item = (grid.LoadItem(row) as IPostableFragment);
- var value = item!.PostedReference;
- var comboBox = new ComboBox
- {
- ItemsSource = allItems,
- SelectedValuePath = "Reference",
- DisplayMemberPath = "Display",
- VerticalContentAlignment = VerticalAlignment.Center
- };
- comboBox.SelectedValue = value;
- comboBox.SelectionChanged += (o, e) =>
- {
- window.CanSave = true;
- item.PostedReference = (comboBox.SelectedValue as string)!;
- };
- return comboBox;
- })
- {
- HeaderText = "Maps To..."
- });
- grid.Refresh(true, false);
- var items = Client.Create(tConfigure)
- .Query(
- Filter.Create(tConfigure).All(),
- grid.DataColumns())
- .ToObjects(tConfigure);
- foreach(var item in items)
- {
- grid.Items.Add(item);
- }
- grid.Refresh(false, true);
- if(window.ShowDialog() == true)
- {
- Client.Create(tConfigure).Save(grid.Items.OfType<Entity>().Where(x => x.IsChanged()), "Updated poster mapping");
- }
- }
- catch(Exception e)
- {
- MessageWindow.ShowError("Configuration failed", e);
- }
- }
- public static void ConfigurePost<T>()
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- var postSettings = PosterUtils.LoadPostableSettings<T>();
- var grid = (DynamicGridUtils.CreateDynamicGrid(typeof(DynamicGrid<>), typeof(PostableSettings)) as DynamicGrid<PostableSettings>)!;
- if (grid.EditItems(new PostableSettings[] { postSettings }))
- {
- PosterUtils.SavePostableSettings<T>(postSettings);
- }
- }
- public static void CreateToolbarButtons<T>(IPanelHost host, Func<IDataModel<T>> model, Action refresh, bool allowConfig)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- CreateToolbarButtons(host, model, refresh, allowConfig ? ConfigurePost<T> : null);
- }
- #region PostColumn
- private static readonly BitmapImage? post = PRSDesktop.Resources.post.AsBitmapImage();
- private static readonly BitmapImage? tick = PRSDesktop.Resources.tick.AsBitmapImage();
- private static readonly BitmapImage? warning = PRSDesktop.Resources.warning.AsBitmapImage();
- private static readonly BitmapImage? refresh = PRSDesktop.Resources.refresh.AsBitmapImage();
- public static void AddPostColumn<T>(DynamicGrid<T> grid)
- where T : Entity, IPostable, IRemotable, IPersistent, new()
- {
- grid.HiddenColumns.Add(x => x.PostedStatus);
- grid.HiddenColumns.Add(x => x.PostedNote);
-
- grid.ActionColumns.Add(new DynamicImageColumn(
- row =>
- {
- if (row is null)
- return post;
- return row.Get<T, PostedStatus>(x => x.PostedStatus) switch
- {
- PostedStatus.PostFailed => warning,
- PostedStatus.Posted => tick,
- PostedStatus.RequiresRepost => refresh,
- PostedStatus.NeverPosted or _ => null,
- };
- },
- null)
- {
- ToolTip = (column, row) =>
- {
- if (row is null)
- {
- return column.TextToolTip($"{CoreUtils.Neatify(typeof(T).Name)} Processed Status");
- }
- return column.TextToolTip(row.Get<T, PostedStatus>(x => x.PostedStatus) switch
- {
- PostedStatus.PostFailed => "Post failed: " + row.Get<T, string>(x => x.PostedNote),
- PostedStatus.RequiresRepost => "Repost required: " + row.Get<T, string>(x => x.PostedNote),
- PostedStatus.Posted => "Processed",
- PostedStatus.NeverPosted or _ => "Not posted yet",
- });
- }
- });
- }
- #endregion
- }
|