diff --git a/Elwig/App.xaml.cs b/Elwig/App.xaml.cs index b168787..e480289 100644 --- a/Elwig/App.xaml.cs +++ b/Elwig/App.xaml.cs @@ -24,8 +24,7 @@ using System.Windows.Threading; namespace Elwig { public partial class App : Application { - public static App CurrentApp; - public static int NumWindows => CurrentApp.Windows.Count; + public static new App Current => (App)Application.Current; public static bool ForceShutdown { get; set; } = false; private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) }; @@ -42,8 +41,8 @@ namespace Elwig { public static Version Version { get; private set; } = new(); public static int BranchNum { get; private set; } - public static string ZwstId { get; private set; } - public static string BranchName { get; private set; } + public static string ZwstId { get; private set; } = "?"; + public static string BranchName { get; private set; } = "Unbekannt"; public static int? BranchPlz { get; private set; } public static string? BranchLocation { get; private set; } public static string? BranchAddress { get; private set; } @@ -54,9 +53,8 @@ namespace Elwig { public static IList Scales { get; private set; } = []; public static IList CommandScales => [.. Scales.Where(s => s is ICommandScale).Cast()]; public static IList EventScales => [.. Scales.Where(s => s is IEventScale).Cast()]; - public static ClientParameters Client { get; set; } + public static ClientParameters Client { get; set; } = new(); - public static Dispatcher MainDispatcher { get; private set; } private DateTime LastChanged; private static DateTime CurrentLastWrite => File.GetLastWriteTime(Config.DatabaseFile); private readonly DispatcherTimer ContextTimer = new() { Interval = TimeSpan.FromSeconds(2) }; @@ -66,9 +64,7 @@ namespace Elwig { Directory.CreateDirectory(TempPath); Directory.CreateDirectory(DataPath); Directory.CreateDirectory(MailsPath); - MainDispatcher = Dispatcher; Scales = []; - CurrentApp = this; Utils.OverrideCulture(); var args = Environment.GetCommandLineArgs(); @@ -86,7 +82,7 @@ namespace Elwig { } private static void OnContextChanged() { - MainDispatcher.BeginInvoke(HintContextChange); + Current.Dispatcher.BeginInvoke(HintContextChange); } protected override async void OnStartup(StartupEventArgs evt) { @@ -259,21 +255,20 @@ namespace Elwig { } public static void HintContextChange() { - if (CurrentApp == null) return; var ch = CurrentLastWrite; - if (ch > CurrentApp.LastChanged) - CurrentApp.LastChanged = ch; - MainDispatcher.Invoke(() => { - foreach (Window w in CurrentApp.Windows) { + if (ch > Current.LastChanged) + Current.LastChanged = ch; + Current.Dispatcher.Invoke(() => { + foreach (Window w in Current.Windows) { if (w is not ContextWindow c) continue; - MainDispatcher.Invoke(c.HintContextChange); - MainDispatcher.BeginInvoke(c.TryContextReload); + Current.Dispatcher.Invoke(c.HintContextChange); + Current.Dispatcher.BeginInvoke(c.TryContextReload); } }); } private void OnAutoUpdateTimer(object? sender, EventArgs? evt) { - foreach (Window w in CurrentApp.Windows) { + foreach (Window w in Current.Windows) { if (w is UpdateDialog) return; } if (Utils.HasInternetConnectivity()) { @@ -330,7 +325,7 @@ namespace Elwig { } public static void UpdateScales() { - foreach (Window w in CurrentApp.Windows) { + foreach (Window w in Current.Windows) { if (w is DeliveryAdminWindow t && t.ViewModel.IsReceipt) { t.UpdateScales(); } @@ -342,7 +337,7 @@ namespace Elwig { try { var latest = await Utils.GetLatestInstallerUrl(Config.UpdateUrl); if (new Version(latest.Version) > Version) { - await MainDispatcher.BeginInvoke(() => { + await Current.Dispatcher.BeginInvoke(() => { var d = new UpdateDialog(latest.Version, latest.Url, latest.Size); if (d.ShowDialog() == true) { ShutdownNow(); @@ -370,7 +365,7 @@ namespace Elwig { } private static T FocusWindow(Func constructor, Predicate? selector = null) where T : Window { - foreach (Window w in CurrentApp.Windows) { + foreach (Window w in Current.Windows) { if (w is T t && (selector == null || selector(t))) { if (t.WindowState == WindowState.Minimized) t.WindowState = WindowState.Normal; diff --git a/Elwig/Controls/BoolToValueConverter.cs b/Elwig/Controls/BoolToValueConverter.cs index 82a1f92..03e9387 100644 --- a/Elwig/Controls/BoolToValueConverter.cs +++ b/Elwig/Controls/BoolToValueConverter.cs @@ -4,10 +4,10 @@ using System.Globalization; namespace Elwig.Controls { public class BoolToValueConverter : IValueConverter { - public T FalseValue { get; set; } - public T TrueValue { get; set; } + public required T FalseValue { get; set; } + public required T TrueValue { get; set; } - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (bool)value ? TrueValue : FalseValue; } diff --git a/Elwig/Controls/CheckComboBox.cs b/Elwig/Controls/CheckComboBox.cs index 659940e..db8a809 100644 --- a/Elwig/Controls/CheckComboBox.cs +++ b/Elwig/Controls/CheckComboBox.cs @@ -74,7 +74,7 @@ namespace Elwig.Controls { private bool _viewHandled; private bool _modelHandled; - private TextBlock _textBox; + private TextBlock? _textBox; public CheckComboBox() { SelectionMode = SelectionMode.Multiple; @@ -131,11 +131,11 @@ namespace Elwig.Controls { AllItemsSelected = null; } if (SelectedItems.Count > 1 && SelectedItems.Count == ItemsSource.Cast().Count() && AllItemsSelectedContent != null) { - _textBox.Text = AllItemsSelectedContent; + _textBox?.Text = AllItemsSelectedContent; } else if (SelectedItems.Count == 0) { - _textBox.Text = ""; + _textBox?.Text = ""; } else { - _textBox.Text = string.Join(Delimiter, + _textBox?.Text = string.Join(Delimiter, dmp == null ? SelectedItems.Cast() : SelectedItems.Cast() .Select(i => i.GetType().GetProperty(dmp)?.GetValue(i)) diff --git a/Elwig/Dialogs/DeliverySplittingDialog.xaml.cs b/Elwig/Dialogs/DeliverySplittingDialog.xaml.cs index 1f4fb14..4f28326 100644 --- a/Elwig/Dialogs/DeliverySplittingDialog.xaml.cs +++ b/Elwig/Dialogs/DeliverySplittingDialog.xaml.cs @@ -13,7 +13,7 @@ namespace Elwig.Dialogs { public partial class DeliverySplittingDialog : ContextWindow { public class Row { - public DeliveryPart Part { get; set; } + public required DeliveryPart Part { get; set; } public bool SplitCompletely { get; set; } public string? SplitWeightString { get; set; } public int? SplitWeight { @@ -27,18 +27,18 @@ namespace Elwig.Dialogs { public int? MgNr { get; set; } public string? LsNr { get; set; } - public int[]? Weights => DeliveryParts.Select(r => r.SplitCompletely ? r.Part.Weight : r.SplitWeight ?? 0).ToArray(); + public int[]? Weights => [.. DeliveryParts.Select(r => r.SplitCompletely ? r.Part.Weight : r.SplitWeight ?? 0)]; public ObservableCollection DeliveryParts { get; set; } public DeliverySplittingDialog(Delivery d) { _delivery = d; - DeliveryParts = new(d.Parts.Select(p => new Row { + DeliveryParts = [with([.. d.Parts.Select(p => new Row { Part = p, SplitCompletely = false, SplitWeight = null, SplitWeightEnabled = true, - }).ToList()); + })])]; InitializeComponent(); } diff --git a/Elwig/Documents/Document.cs b/Elwig/Documents/Document.cs index 282c7d0..e5811de 100644 --- a/Elwig/Documents/Document.cs +++ b/Elwig/Documents/Document.cs @@ -343,22 +343,17 @@ namespace Elwig.Documents { return t; } - private class EventHandler : AbstractPdfDocumentEventHandler { + private class EventHandler(Document doc) : AbstractPdfDocumentEventHandler { private const float _fontSize = 10; private const float _placeholderWidth = 50 * PtInMM; - private readonly Document _doc; - private readonly List _pageNumPlaceholders; + private readonly Document _doc = doc; + private readonly List _pageNumPlaceholders = []; public int NumberOfPages { get; private set; } - public EventHandler(Document doc) { - _doc = doc; - _pageNumPlaceholders = []; - } - protected override void OnAcceptedEvent(AbstractPdfDocumentEvent evt) { if (evt.GetType() == PdfDocumentEvent.START_PAGE) { OnPageStart((PdfDocumentEvent)evt); diff --git a/Elwig/Helpers/ActionCommand.cs b/Elwig/Helpers/ActionCommand.cs index 1d69b10..8858aee 100644 --- a/Elwig/Helpers/ActionCommand.cs +++ b/Elwig/Helpers/ActionCommand.cs @@ -2,14 +2,10 @@ using System; using System.Windows.Input; namespace Elwig.Helpers { - public class ActionCommand : ICommand { + public class ActionCommand(Action action) : ICommand { public event EventHandler? CanExecuteChanged; - private readonly Action Action; - - public ActionCommand(Action action) { - Action = action; - } + private readonly Action Action = action; public void Execute(object? parameter) { Action(); diff --git a/Elwig/Helpers/ClientParameters.cs b/Elwig/Helpers/ClientParameters.cs index b76910c..663fd23 100644 --- a/Elwig/Helpers/ClientParameters.cs +++ b/Elwig/Helpers/ClientParameters.cs @@ -83,7 +83,23 @@ namespace Elwig.Helpers { public (int? AllowanceKg, double? AllowanceShares, int? AllowanceKgPerShare, double? AllowancePercent, int? MinShares) AutoAdjustShares; - public ClientParameters(AppDbContext ctx) : this(ctx.ClientParameters.ToDictionary(e => e.Param, e => e.Value)) { } + public static readonly Dictionary DefaultParameters = new() { + { "CLIENT_NAME_TOKEN", "XXX" }, + { "CLIENT_NAME_SHORT", "Unbekannt" }, + { "CLIENT_NAME", "Unbekannt" }, + { "CLIENT_NAME_TYPE", "Unbekannt" }, + { "CLIENT_PLZ", "9999" }, + { "CLIENT_ORT", "Unbekannt" }, + { "CLIENT_ADDRESS", "Unbekannt" }, + }; + + public ClientParameters() : + this(DefaultParameters) { + } + + public ClientParameters(AppDbContext ctx) : + this(ctx.ClientParameters.ToDictionary(e => e.Param, e => e.Value)) { + } public ClientParameters(Dictionary parameters) { try { diff --git a/Elwig/Helpers/Extensions.cs b/Elwig/Helpers/Extensions.cs index 8df01f8..c6acce0 100644 --- a/Elwig/Helpers/Extensions.cs +++ b/Elwig/Helpers/Extensions.cs @@ -62,7 +62,7 @@ namespace Elwig.Helpers { var buf = new char[512]; int bufSize = 0; var tmpBuf = new char[1]; - while (!reader.EndOfStream && bufSize < buf.Length - 1) { + while (bufSize < buf.Length - 1) { if ((await reader.ReadAsync(tmpBuf, 0, 1)) != 1) return null; buf[bufSize++] = tmpBuf[0]; diff --git a/Elwig/Helpers/Printing/Pdf.cs b/Elwig/Helpers/Printing/Pdf.cs index 5ab672a..454bc1f 100644 --- a/Elwig/Helpers/Printing/Pdf.cs +++ b/Elwig/Helpers/Printing/Pdf.cs @@ -15,14 +15,14 @@ namespace Elwig.Helpers.Printing { } public static void Show(TempFile file, string title) { - App.MainDispatcher.BeginInvoke(() => { + App.Current.Dispatcher.BeginInvoke(() => { var w = new DocumentViewerWindow(title, file); w.Show(); }); } public static void Show(string path, string title) { - App.MainDispatcher.BeginInvoke(() => { + App.Current.Dispatcher.BeginInvoke(() => { var w = new DocumentViewerWindow(title, path); w.Show(); }); diff --git a/Elwig/Helpers/SerialPortWatcher.cs b/Elwig/Helpers/SerialPortWatcher.cs index 18ad3df..99f34b3 100644 --- a/Elwig/Helpers/SerialPortWatcher.cs +++ b/Elwig/Helpers/SerialPortWatcher.cs @@ -26,7 +26,7 @@ namespace Elwig.Helpers { } private void OnDeviceArrived(object sender, EventArrivedEventArgs evt) { - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { // "synchronized" string[] currentPorts = SerialPort.GetPortNames(); var newPorts = currentPorts.Except(_knownPorts).ToArray(); @@ -37,7 +37,7 @@ namespace Elwig.Helpers { } private void OnDeviceRemoved(object sender, EventArrivedEventArgs evt) { - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { // "synchronized" string[] currentPorts = SerialPort.GetPortNames(); var removedPorts = _knownPorts.Except(currentPorts).ToArray(); diff --git a/Elwig/Helpers/TempFile.cs b/Elwig/Helpers/TempFile.cs index 2d42e9d..76db1d4 100644 --- a/Elwig/Helpers/TempFile.cs +++ b/Elwig/Helpers/TempFile.cs @@ -38,9 +38,9 @@ namespace Elwig.Helpers { } private void Delete() { - if (FilePath == null) return; + if (Usages < 0) return; File.Delete(FilePath); - FilePath = null; + Usages = -1; } } } diff --git a/Elwig/Helpers/Utils.cs b/Elwig/Helpers/Utils.cs index 1047e76..7632593 100644 --- a/Elwig/Helpers/Utils.cs +++ b/Elwig/Helpers/Utils.cs @@ -74,6 +74,9 @@ namespace Elwig.Helpers { private static partial Regex GeneratedInvalidFileNamePartsRegex(); public static readonly Regex InvalidFileNamePartsRegex = GeneratedInvalidFileNamePartsRegex(); + [GeneratedRegex(".{4}")] + private static partial Regex IbanRegex { get; } + public static readonly string GroupSeparator = "\u202F"; public static readonly string UnitSeparator = "\u00A0"; @@ -206,7 +209,7 @@ namespace Elwig.Helpers { } public static string FormatIban(string iban) { - return Regex.Replace(iban.Trim(), ".{4}", "$0 ").Trim(); + return IbanRegex.Replace(iban.Trim(), "$0 ").Trim(); } public static void RunBackground(string title, Func function) { @@ -322,15 +325,10 @@ namespace Elwig.Helpers { return new Footer(lineBreak, separator); } - public class Footer { + public class Footer(string lineBreak, string separator) { private readonly List>> Items = [[[]]]; - private readonly string LineBreak; - private readonly string Separator; - - public Footer(string lineBreak, string separator) { - LineBreak = lineBreak; - Separator = separator; - } + private readonly string LineBreak = lineBreak; + private readonly string Separator = separator; public Footer Item(object? text) { if (text == null) return this; @@ -496,7 +494,7 @@ namespace Elwig.Helpers { Timeout = TimeSpan.FromSeconds(5), }; client.DefaultRequestHeaders.UserAgent.Clear(); - client.DefaultRequestHeaders.UserAgent.ParseAdd($"Elwig/{App.Version} ({App.Client?.NameToken}, {ReplaceUmlaute(App.BranchName)}, {Environment.MachineName}, {Environment.OSVersion})"); + client.DefaultRequestHeaders.UserAgent.ParseAdd($"Elwig/{App.Version} ({App.Client.NameToken}, {ReplaceUmlaute(App.BranchName)}, {Environment.MachineName}, {Environment.OSVersion})"); client.DefaultRequestHeaders.Accept.Clear(); if (accept != null) client.DefaultRequestHeaders.Accept.Add(new(accept)); @@ -657,7 +655,7 @@ namespace Elwig.Helpers { } else if (obj is IEnumerable list && obj is not string) { var arr = list.Cast().Select(GetEntityIdentifier).ToArray(); return ((IStructuralEquatable)arr).GetHashCode(EqualityComparer.Default); - } else if (obj.GetType().GetCustomAttribute(typeof(PrimaryKeyAttribute), true) is PrimaryKeyAttribute pkAttr) { + } else if (obj.GetType().GetCustomAttribute(true) is PrimaryKeyAttribute pkAttr) { var pk = pkAttr.PropertyNames.Select(name => obj.GetType().GetProperty(name)!.GetValue(obj)?.GetHashCode() ?? 0).ToArray(); return ((IStructuralEquatable)pk).GetHashCode(EqualityComparer.Default); } else { diff --git a/Elwig/Models/Dtos/DeliveryConfirmationDeliveryData.cs b/Elwig/Models/Dtos/DeliveryConfirmationDeliveryData.cs index 94357f5..142fdd2 100644 --- a/Elwig/Models/Dtos/DeliveryConfirmationDeliveryData.cs +++ b/Elwig/Models/Dtos/DeliveryConfirmationDeliveryData.cs @@ -45,8 +45,6 @@ namespace Elwig.Models.Dtos { } private static async Task> FromDbSet(DbSet table, int? year = null, int? mgnr = null) { - var y = year?.ToString() ?? "NULL"; - var m = mgnr?.ToString() ?? "NULL"; IQueryable q = table; if (year != null) q = q.Where(p => p.Year == year); if (mgnr != null) q = q.Where(p => p.Delivery.MgNr == mgnr); @@ -55,11 +53,11 @@ namespace Elwig.Models.Dtos { .Include(p => p.Buckets) .Include(p => p.PartModifiers).ThenInclude(m => m.Modifier) .LoadAsync(); - return await table.FromSqlRaw($""" + return await table.FromSql($""" SELECT p.* FROM v_delivery v JOIN delivery_part p ON (p.year, p.did, p.dpnr) = (v.year, v.did, v.dpnr) - WHERE (p.year = {y} OR {y} IS NULL) AND (v.mgnr = {m} OR {m} IS NULL) + WHERE (p.year = {year} OR {year} IS NULL) AND (v.mgnr = {mgnr} OR {mgnr} IS NULL) ORDER BY p.year, v.mgnr, v.sortid, v.abgewertet ASC, v.attribute_prio DESC, COALESCE(v.attrid, '~'), v.kmw DESC, v.lsnr, v.dpnr """).IgnoreAutoIncludes().ToListAsync(); } diff --git a/Elwig/Models/Dtos/WeightBreakdownData.cs b/Elwig/Models/Dtos/WeightBreakdownData.cs index 6f86d9f..eece8b6 100644 --- a/Elwig/Models/Dtos/WeightBreakdownData.cs +++ b/Elwig/Models/Dtos/WeightBreakdownData.cs @@ -26,8 +26,7 @@ namespace Elwig.Models.Dtos { } private static async Task> FromDbSet(DbSet table, int year, string? zwstid) { - zwstid = zwstid == null ? "NULL" : $"'{zwstid}'"; - return await table.FromSqlRaw($""" + return await table.FromSql($""" SELECT type, sortid, attrid, cultid, v.qualid, contracted, SUM(weight) AS weight FROM v_stat_total v LEFT JOIN wine_quality_level q ON q.qualid = v.qualid diff --git a/Elwig/Services/InteractionService.cs b/Elwig/Services/InteractionService.cs index 1e7efef..f0cc2c3 100644 --- a/Elwig/Services/InteractionService.cs +++ b/Elwig/Services/InteractionService.cs @@ -7,14 +7,14 @@ using System.Windows; namespace Elwig.Services { public static class InteractionService { - public static Func? Override; - public static Action? NextInformation; - public static Action? NextWarning; - public static Action? NextError; - public static Func? NextContinue; - public static Func? NextConfirmation; - public static Func? NextQuestion; - public static Func? NextSave; + public static Func? Override { get; set; } + public static Action? NextInformation { get; set; } + public static Action? NextWarning { get; set; } + public static Action? NextError { get; set; } + public static Func? NextContinue { get; set; } + public static Func? NextConfirmation { get; set; } + public static Func? NextQuestion { get; set; } + public static Func? NextSave { get; set; } public static readonly Dictionary ExtensionFilters = new() { ["pdf"] = "PDF-Datei (*.pdf)|*.pdf", diff --git a/Elwig/Services/MemberService.cs b/Elwig/Services/MemberService.cs index 192c012..415abfc 100644 --- a/Elwig/Services/MemberService.cs +++ b/Elwig/Services/MemberService.cs @@ -172,8 +172,6 @@ namespace Elwig.Services { vm.StatusAreaCommitmentToolTip = null; Utils.RunBackground("Mitgliederdaten laden", async () => { - if (App.MainDispatcher == null) - return; using var ctx = new AppDbContext(); var d1 = ctx.Deliveries.Where(d => d.Year == Utils.CurrentLastSeason - 1 && d.MgNr == m.MgNr); @@ -197,7 +195,7 @@ namespace Elwig.Services { .GroupBy(d => d.Year) .ToDictionaryAsync(g => g.Key, g => g.Any()); - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (m.MgNr != vm.MgNr) return; var (d1Grid, _) = DeliveryService.GenerateToolTip(d1GridData, []); @@ -224,9 +222,8 @@ namespace Elwig.Services { } else { vm.OrganicDetails = "..."; Utils.RunBackground("Bio-Zertifikatsdaten laden", async () => { - if (App.MainDispatcher == null) return; var certs = await OrganicService.GetTracesCertificates(m); - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (m.MgNr != vm.MgNr) return; vm.FillOrganicInputs(certs.FirstOrDefault(c => c.IsValidForWineProduction)); }); diff --git a/Elwig/Services/PaymentVariantService.cs b/Elwig/Services/PaymentVariantService.cs index a53d24c..2506fcb 100644 --- a/Elwig/Services/PaymentVariantService.cs +++ b/Elwig/Services/PaymentVariantService.cs @@ -112,8 +112,6 @@ namespace Elwig.Services { } private static async Task UpdateSums(this PaymentVariantsViewModel vm, PaymentVar v) { - if (App.MainDispatcher == null) - return; var modText = "-"; var totalText = "-"; var vatText = "-"; @@ -133,7 +131,7 @@ namespace Elwig.Services { .SumAsync(p => p.AmountValue); totalText = $"{v.Season.DecFromDb(totalSum):N2} {sym}"; - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (vm.SelectedPaymentVariant != v) return; vm.StatusModifierSum = modText; @@ -175,7 +173,7 @@ namespace Elwig.Services { paymentText = $"{Utils.DecFromDb(await credits.SumAsync(c => c.AmountValue), 2):N2} {sym}"; } - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (vm.SelectedPaymentVariant != v) return; vm.StatusModifierSum = modText; diff --git a/Elwig/Windows/DeliveryAdminWindow.xaml.cs b/Elwig/Windows/DeliveryAdminWindow.xaml.cs index 0af4704..424765a 100644 --- a/Elwig/Windows/DeliveryAdminWindow.xaml.cs +++ b/Elwig/Windows/DeliveryAdminWindow.xaml.cs @@ -695,7 +695,7 @@ namespace Elwig.Windows { private void Scale_Weighing(object sender, WeighingEventArgs evt) { if (sender is not IScale scale) return; - App.MainDispatcher.BeginInvoke(() => OnWeighingResult(scale, evt.Result)); + App.Current.Dispatcher.BeginInvoke(() => OnWeighingResult(scale, evt.Result)); } private async void SearchInput_TextChanged(object sender, RoutedEventArgs evt) { @@ -1307,7 +1307,7 @@ namespace Elwig.Windows { ViewModel.SortId = s.SortId; UpdateWineQualityLevels(); if (!ViewModel.WineVar?.IsQuw ?? false) { - App.MainDispatcher.BeginInvoke(() => { + App.Current.Dispatcher.BeginInvoke(() => { InteractionService.ShowWarning("Kein Qualitätswein", "Die eingegebene Sorte darf nicht als Qualitätswein\nübernommen werden!"); }); } @@ -1395,7 +1395,7 @@ namespace Elwig.Windows { if (App.Client.IsMatzen) { var kl = mod.Where(m => m.Name.StartsWith("Klasse ")); if (kl.Count() > 1) { - App.MainDispatcher.BeginInvoke(() => { + App.Current.Dispatcher.BeginInvoke(() => { foreach (var r in kl.Take(kl.Count() - 1)) ViewModel.Modifiers.Remove(r); }); diff --git a/Elwig/Windows/LogWindow.xaml.cs b/Elwig/Windows/LogWindow.xaml.cs index 3654cb2..f38a83b 100644 --- a/Elwig/Windows/LogWindow.xaml.cs +++ b/Elwig/Windows/LogWindow.xaml.cs @@ -35,7 +35,7 @@ namespace Elwig.Windows { }) .OrderByDescending(e => e.Event.TimeGenerated) .ToList(); - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { EventList.ItemsSource = list; EventList.SelectedIndex = 0; }); diff --git a/Elwig/Windows/MailWindow.xaml.cs b/Elwig/Windows/MailWindow.xaml.cs index 4b2226d..f21c392 100644 --- a/Elwig/Windows/MailWindow.xaml.cs +++ b/Elwig/Windows/MailWindow.xaml.cs @@ -443,7 +443,7 @@ namespace Elwig.Windows { private async Task UpdateRecipients(AppDbContext ctx) { if (RecipientsCustomInput.IsChecked == true) { - Recipients = MemberCustomInput.SelectedItems.Cast().ToList(); + Recipients = [.. MemberCustomInput.SelectedItems.Cast()]; } else { IQueryable query = ctx.Members; if (MemberBranchInput.SelectedItems.Count != MemberBranchInput.Items.Count) { @@ -653,32 +653,27 @@ namespace Elwig.Windows { IEnumerable recipients = Recipients; if (OrderMgNrInput.IsChecked == true) { - recipients = recipients - .OrderBy(m => m.MgNr) - .ToList(); + recipients = [.. recipients.OrderBy(m => m.MgNr)]; } else if (OrderNameInput.IsChecked == true) { - recipients = recipients + recipients = [.. recipients .OrderBy(m => m.Name) .ThenBy(m => m.GivenName) - .ThenBy(m => m.MgNr) - .ToList(); + .ThenBy(m => m.MgNr)]; } else if (OrderPlzInput.IsChecked == true) { if (docs.Any(d => d.Type == DocType.DeliveryConfirmation || d.Type == DocType.CreditNote)) { - recipients = recipients + recipients = [.. recipients .OrderBy(m => m.BillingAddress?.PostalDest.AtPlz?.Plz ?? m.PostalDest.AtPlz?.Plz) .ThenBy(m => m.BillingAddress?.PostalDest.AtPlz?.Ort.Name ?? m.PostalDest.AtPlz?.Ort.Name) .ThenBy(m => m.Name) .ThenBy(m => m.GivenName) - .ThenBy(m => m.MgNr) - .ToList(); + .ThenBy(m => m.MgNr)]; } else { - recipients = recipients + recipients = [.. recipients .OrderBy(m => m.PostalDest.AtPlz?.Plz) .ThenBy(m => m.PostalDest.AtPlz?.Ort.Name) .ThenBy(m => m.Name) .ThenBy(m => m.GivenName) - .ThenBy(m => m.MgNr) - .ToList(); + .ThenBy(m => m.MgNr)]; } } @@ -703,7 +698,7 @@ namespace Elwig.Windows { } private async Task GenerateDocuments(bool doublePaged, string location, List docs, IEnumerable recipients, DateOnly postalDate, int printMode, int emailMode) { - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = 0.0; }); using var ctx = new AppDbContext(); @@ -731,7 +726,7 @@ namespace Elwig.Windows { } } - var (printNum, emailNum) = App.MainDispatcher.Invoke(() => { + var (printNum, emailNum) = App.Current.Dispatcher.Invoke(() => { double printNum = printMode == 3 ? PostalAllCount : printMode == 2 ? PostalWishCount : printMode == 1 ? PostalNoEmailCount : 0; double emailNum = emailMode == 2 ? EmailAllCount : emailMode == 1 ? EmailWishCount : 0; return (printNum, emailNum); @@ -743,7 +738,7 @@ namespace Elwig.Windows { Member = m, Docs = docs.SelectMany(doc => { try { - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = offset + 100.0 * i / 2 / totalNum; }); if (doc.Type == DocType.Custom) { @@ -778,7 +773,7 @@ namespace Elwig.Windows { InteractionService.ShowException(exc); return []; } finally { - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = offset + 100.0 * (i + 1) / 2 / totalNum; }); } @@ -811,7 +806,7 @@ namespace Elwig.Windows { var emailRecipients = email.Select(d => d.Key.MgNr).ToHashSet(); foreach (var item1 in email.Select((e, i) => new { Index = i, e.Key, e.Value })) { foreach (var item2 in item1.Value.Select((d, i) => new { Index = i, Doc = d })) { - await item2.Doc.Generate(ctx, CancelGeneration?.Token, new Progress(v => App.MainDispatcher.Invoke(() => { + await item2.Doc.Generate(ctx, CancelGeneration?.Token, new Progress(v => App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = offset + v * (item2.Index + 1) / item1.Value.Count / totalNum + 100.0 * item1.Index / totalNum; }))); } @@ -845,7 +840,7 @@ namespace Elwig.Windows { if (printDocs.Count > 0) { var print = Document.Merge(printDocs); - await print.Generate(ctx, CancelGeneration?.Token, new Progress(v => App.MainDispatcher.Invoke(() => { + await print.Generate(ctx, CancelGeneration?.Token, new Progress(v => App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = offset + v * printNum / totalNum; }))); PrintDocument = print; @@ -854,7 +849,7 @@ namespace Elwig.Windows { PrintDocument = null; PrintMemberDocuments = null; } - App.MainDispatcher.Invoke(() => { + App.Current.Dispatcher.Invoke(() => { ProgressBar.Value = 100.0; }); return hasPreviewDocs; diff --git a/Elwig/Windows/MainWindow.xaml.cs b/Elwig/Windows/MainWindow.xaml.cs index ec18a8f..15d4c86 100644 --- a/Elwig/Windows/MainWindow.xaml.cs +++ b/Elwig/Windows/MainWindow.xaml.cs @@ -51,14 +51,14 @@ namespace Elwig.Windows { } private void Window_Closing(object sender, CancelEventArgs evt) { - if (App.NumWindows > 1 && !App.ForceShutdown) { + if (App.Current.Windows.Count > 1 && !App.ForceShutdown) { foreach (var w in Application.Current.Windows.Cast().Where(w => w is AdministrationWindow adm && (adm.IsEditing || adm.IsCreating))) { try { w.Close(); } catch { } } Thread.Sleep(100); - if (App.NumWindows > 1) { + if (App.Current.Windows.Count > 1) { var areAdminWindowsOpen = Application.Current.Windows.Cast().Any(w => w is AdministrationWindow adm && (adm.IsEditing || adm.IsCreating)); if (areAdminWindowsOpen && !InteractionService.AskConfirmation("Elwig beenden", "Es sind noch weitere Fenster geöffnet.\nSollen alle Fenster geschlossen werden?")) { evt.Cancel = true; @@ -66,7 +66,7 @@ namespace Elwig.Windows { } } } - App.CurrentApp.ShutdownGracefully(); + App.Current.ShutdownGracefully(); } private void Menu_Help_About_Click(object sender, RoutedEventArgs evt) { @@ -273,7 +273,7 @@ namespace Elwig.Windows { "Wenn Sie unsicher sind sprechen Sie sich mit dem Benutzer des Hauptgerätes ab!")) return; - await App.MainDispatcher.BeginInvoke(async () => { + await App.Current.Dispatcher.BeginInvoke(async () => { await App.ReplaceDatabase(filename); }); } catch (HttpRequestException exc) { @@ -373,7 +373,7 @@ namespace Elwig.Windows { ch = await SyncService.ChangesAvailable(ctx, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, default); } } - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (ch) { SyncButton_1.Text = "\uEA6A"; SyncButton_2.Text = "\uEA81"; @@ -419,7 +419,7 @@ namespace Elwig.Windows { var weightTotal = await ctx.DeliveryParts.Where(p => p.Year == year).SumAsync(p => p.Weight); var ctrdWeight = await ctx.DeliveryPartBuckets.Where(b => b.Year == year && b.Discr != "_").SumAsync(b => b.Value); var area = await areaCmts.SumAsync(c => c.Area); - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (year != SeasonInput.Value) return; SeasonStatMembersTotal.Text = $"{membersTotal:N0}"; SeasonStatMembersCtrd.Text = $"{membersCtrd:N0}"; diff --git a/Elwig/Windows/MemberAdminWindow.xaml.cs b/Elwig/Windows/MemberAdminWindow.xaml.cs index 30a1dcd..cdbf444 100644 --- a/Elwig/Windows/MemberAdminWindow.xaml.cs +++ b/Elwig/Windows/MemberAdminWindow.xaml.cs @@ -135,7 +135,7 @@ namespace Elwig.Windows { if (!m.IsActive) { ViewModel.ShowOnlyActiveMembers = false; } - App.MainDispatcher.BeginInvoke(async () => { + App.Current.Dispatcher.BeginInvoke(async () => { await Task.Delay(500); FocusMember(mgnr); }); @@ -450,7 +450,7 @@ namespace Elwig.Windows { private void MemberList_SelectionChanged(object sender, RoutedEventArgs evt) { RefreshInputs(); - if (MemberList.SelectedItem is Member m) { + if (MemberList.SelectedItem is Member) { Menu_Export_ExportSelected.IsEnabled = !IsEditing && !IsCreating; Menu_Export_UploadSelected.IsEnabled = !IsEditing && !IsCreating && App.Config.SyncUrl != null; Menu_Contacts_Selected.IsEnabled = !IsEditing && !IsCreating; @@ -1064,9 +1064,8 @@ namespace Elwig.Windows { ViewModel.OrganicDetails = "..."; var lfbisNr = ViewModel.LfbisNr; Utils.RunBackground("Bio-Zertifikatsdaten laden", async () => { - if (App.MainDispatcher == null) return; var certs = await OrganicService.FetchTracesCertificates(lfbisNr: lfbisNr); - await App.MainDispatcher.BeginInvoke(() => { + await App.Current.Dispatcher.BeginInvoke(() => { if (certs.Length == 0) { ViewModel.FillOrganicInputs(null); } else { diff --git a/Elwig/Windows/PaymentAdjustmentWindow.xaml.cs b/Elwig/Windows/PaymentAdjustmentWindow.xaml.cs index 8e1f7b9..9230129 100644 --- a/Elwig/Windows/PaymentAdjustmentWindow.xaml.cs +++ b/Elwig/Windows/PaymentAdjustmentWindow.xaml.cs @@ -62,7 +62,7 @@ namespace Elwig.Windows { var history = await ctx.MemberHistory .Where(h => h.DeductYear == Year) .GroupBy(h => h.ToMember) - .ToDictionaryAsync(h => h.Key.MgNr, h => h.Sum(g => g.Shares)); + .ToDictionaryAsync(h => h.Key!.MgNr, h => h.Sum(g => g.Shares)); var list = members .Select(m => new { @@ -79,7 +79,7 @@ namespace Elwig.Windows { Weight = weight.GetValueOrDefault(m.MgNr, 0), OverUnder = weight.TryGetValue(m.MgNr, out int v1) ? (v1 < m.DeliveryObligation ? (int?)v1 - m.DeliveryObligation : - v1 > m.DeliveryRight ? (int?)v1 - m.DeliveryRight : null) + v1 > m.DeliveryRight ? (int?)v1 - m.DeliveryRight : 0) : (m.IsActive ? -m.DeliveryObligation : null), m.Adjust, AdjustAmount = m.Adjust * -season.BusinessShareValue, @@ -93,10 +93,10 @@ namespace Elwig.Windows { (season.PenaltyPerShareAmount * Math.Floor(m.OverUnder / season.MinKgPerShare ?? 0m) ?? 0) + (m.Weight == 0 ? (-season.PenaltyNone ?? 0) + (-season.PenaltyPerShareNone * m.SharesActive ?? 0) : 0) : (decimal?)null, - PenaltyAc = areaCmts.TryGetValue(m.MgNr, out var c) ? c.Select(r => { + PenaltyAc = areaCmts.TryGetValue(m.MgNr, out var c) ? c.Sum(r => { var con = contracts[r.Key]; return (r.Value.Kg * con.PenaltyPerKg ?? 0) + (r.Value.Kg < 0 ? con.PenaltyAmount ?? 0 : 0) + (r.Value.Percent == -100 ? con.PenaltyNone ?? 0 : 0); - }).Sum() : (decimal?)null, + }) : (decimal?)null, m.Adjust, m.AdjustAmount, Custom = CustomPayments!.GetValueOrDefault(m.MgNr, null), diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index bb85cc1..a7fb939 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -2,6 +2,7 @@ net11.0-windows + x64 enable enable false