From c603a817d9a44236cce2a823afd591eeea1427f1 Mon Sep 17 00:00:00 2001 From: Raphael Noeldner Date: Tue, 2 May 2023 19:38:14 +0200 Subject: [PATCH] Added more error handling --- Library/ClassLibraryCSV/CsvHelper.cs | 7 +- Library/ClassLibraryCSV/ImprovedStream.cs | 28 ++-- Library/SharedAssemblyInfo.cs | 6 +- .../WinFormControls/FilteredDataGridView.cs | 129 +++++++++++------- Library/WinFormControls/ViewSetting.cs | 101 ++++++++------ 5 files changed, 161 insertions(+), 110 deletions(-) diff --git a/Library/ClassLibraryCSV/CsvHelper.cs b/Library/ClassLibraryCSV/CsvHelper.cs index 6e6e4332..a1ce2dc6 100644 --- a/Library/ClassLibraryCSV/CsvHelper.cs +++ b/Library/ClassLibraryCSV/CsvHelper.cs @@ -70,10 +70,9 @@ FillGuessSettings fillGuessSettings , CancellationToken cancellationToken) { if (string.IsNullOrEmpty(fileName)) - throw new ArgumentException("File name can not be empty", nameof(fileName)); - - inspectionResult.FileName = fileName; - Logger.Information("Opening file"); + throw new ArgumentException("File name can not be empty", nameof(fileName)); + + inspectionResult.FileName = fileName; #if SupportPGP var sourceAccess = new SourceAccess(fileName, privateKey: privateKey); #else diff --git a/Library/ClassLibraryCSV/ImprovedStream.cs b/Library/ClassLibraryCSV/ImprovedStream.cs index 2ab27ba7..3fc472ac 100644 --- a/Library/ClassLibraryCSV/ImprovedStream.cs +++ b/Library/ClassLibraryCSV/ImprovedStream.cs @@ -13,8 +13,10 @@ */ #nullable enable using System; +using System.Collections.Generic; using System.IO; using System.IO.Compression; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ICSharpCode.SharpZipLib.Core; @@ -456,7 +458,7 @@ private void OpenZGipOverBase() cBufferSize); } } - + private void OpenZipOverBase() { if (m_SourceAccess.Reading) @@ -486,22 +488,28 @@ private void OpenZipOverBase() var hasFile = false; if (string.IsNullOrEmpty(m_SourceAccess.IdentifierInContainer)) { + var files = new List(); var entryEnumerator = m_ZipFile.GetEnumerator(); while (entryEnumerator.MoveNext()) { var entry = entryEnumerator.Current as ZipEntry; if (entry?.IsFile ?? false) { - m_SourceAccess.IdentifierInContainer = entry.Name; - Logger.Debug( - "Unzipping {filename} {container}", - m_SourceAccess.Identifier, - m_SourceAccess.IdentifierInContainer); - AccessStream = m_ZipFile.GetInputStream(entry); - hasFile = true; - break; + files.Add(entry); } } + // get csv with highest priority + // get txt with second priority + // the by index in file + var bestEntry = files.OrderBy(x => x.ZipFileIndex + + (x.Name.EndsWith(".csv", StringComparison.OrdinalIgnoreCase) ? 0 : + x.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) ? 500 : + 1000)).First(); + + m_SourceAccess.IdentifierInContainer = bestEntry.Name; + Logger.Information("Using {container}", m_SourceAccess.IdentifierInContainer); + AccessStream = m_ZipFile.GetInputStream(bestEntry); + hasFile = true; } else { @@ -510,7 +518,7 @@ private void OpenZipOverBase() throw new FileNotFoundException( $"Could not find {m_SourceAccess.IdentifierInContainer} in {m_SourceAccess.Identifier}"); - Logger.Debug("Unzipping {filename} {container}", m_SourceAccess.Identifier, m_SourceAccess.IdentifierInContainer); + Logger.Information("Using {container}", m_SourceAccess.IdentifierInContainer); AccessStream = m_ZipFile.GetInputStream(entryIndex); hasFile = true; } diff --git a/Library/SharedAssemblyInfo.cs b/Library/SharedAssemblyInfo.cs index df1263fc..178cd852 100644 --- a/Library/SharedAssemblyInfo.cs +++ b/Library/SharedAssemblyInfo.cs @@ -11,6 +11,6 @@ // Version information for an assembly consists of the following four values: Major Version Minor // Version Build Number Revision You can specify all the values or you can default the Build and.Json // Revision Numbers by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.7.5.581")] -[assembly: AssemblyFileVersion("1.7.5.581")] -[assembly: AssemblyInformationalVersion("1.7.5.581")] // a.k.a. "Product version" \ No newline at end of file +[assembly: AssemblyVersion("1.7.5.582")] +[assembly: AssemblyFileVersion("1.7.5.582")] +[assembly: AssemblyInformationalVersion("1.7.5.582")] // a.k.a. "Product version" \ No newline at end of file diff --git a/Library/WinFormControls/FilteredDataGridView.cs b/Library/WinFormControls/FilteredDataGridView.cs index f9b65e51..a8a5b951 100644 --- a/Library/WinFormControls/FilteredDataGridView.cs +++ b/Library/WinFormControls/FilteredDataGridView.cs @@ -83,7 +83,7 @@ public FilteredDataGridView() FontChanged += PassOnFontChanges; m_Filter = new List(); - Scroll += (_,_) => SetRowHeight(); + Scroll += (_, _) => SetRowHeight(); var resources = new ComponentResourceManager(typeof(FilteredDataGridView)); m_ImgFilterIndicator = (resources.GetObject("toolStripMenuItem2.Image") as Image) ?? throw new InvalidOperationException("Resource not found"); @@ -855,23 +855,29 @@ private void ContextMenuStripFilter_Opened(object? sender, EventArgs e) /// private void FilteredDataGridView_CellMouseClick(object? sender, DataGridViewCellMouseEventArgs e) { - SetToolStripMenu(e.ColumnIndex, e.RowIndex, e.Button); - if (e is { Button: MouseButtons.Left, RowIndex: >= 0 } && Columns[e.ColumnIndex] is DataGridViewButtonColumn) + try { - using var frm = new FormTextDisplay(CurrentCell.Value?.ToString() ?? string.Empty); - - // ReSharper disable once LocalizableElement - frm.Text = $"{Columns[e.ColumnIndex].DataPropertyName} - Row {e.RowIndex + 1:D}"; - frm.SaveAction = s => + SetToolStripMenu(e.ColumnIndex, e.RowIndex, e.Button); + if (e is { Button: MouseButtons.Left, RowIndex: >= 0 } && Columns[e.ColumnIndex] is DataGridViewButtonColumn) { - if (s.Equals(CurrentCell.Value)) - return; - CurrentCell.Value = s; - CurrentCell.ErrorText = CurrentCell.ErrorText.AddMessage( - "Value was modified".AddWarningId()); - }; - frm.ShowWithFont(this, true); + using var frm = new FormTextDisplay(CurrentCell.Value?.ToString() ?? string.Empty); + // ReSharper disable once LocalizableElement + frm.Text = $"{Columns[e.ColumnIndex].DataPropertyName} - Row {e.RowIndex + 1:D}"; + frm.SaveAction = s => + { + if (s.Equals(CurrentCell.Value)) + return; + CurrentCell.Value = s; + CurrentCell.ErrorText = CurrentCell.ErrorText.AddMessage( + "Value was modified".AddWarningId()); + }; + frm.ShowWithFont(this, true); + } + } + catch (Exception ex) + { + Logger.Error(ex, "FilteredDataGridView: Mouse Click {columnIndex} {rowIndex} {button}", e.ColumnIndex, e.RowIndex, e.Button); } } @@ -947,8 +953,7 @@ private void FilteredDataGridView_KeyDown(object? sender, KeyEventArgs e) { if (!e.Control || e.KeyCode != Keys.C) return; - var html = new DataGridViewCopyPaste(HtmlStyle); - html.SelectedDataIntoClipboard(this, !e.Alt, e.Shift, m_CancellationTokenSource.Token); + Copy(!e.Alt, e.Shift); e.Handled = true; } @@ -1288,13 +1293,20 @@ private void TimerColumnsFilter_Tick(object? sender, EventArgs e) /// The instance containing the event data. private void ToolStripMenuItemApply_Click(object? sender, EventArgs e) { - if (m_Filter[m_MenuItemColumnIndex] != null) + try + { + if (m_Filter[m_MenuItemColumnIndex] != null) m_Filter[m_MenuItemColumnIndex]!.ColumnFilterLogic.Active = true; ApplyFilters(); contextMenuStripCell.Close(); contextMenuStripHeader.Close(); contextMenuStripFilter.Close(); + } + catch (Exception ex) + { + Logger.Error(ex,"Apply Click"); + } } @@ -1320,27 +1332,32 @@ private void ToolStripMenuItemCF_Click(object? sender, EventArgs e) } } + private void Copy(bool addErrorInfo, bool cutLength) + { + try + { + var html = new DataGridViewCopyPaste(HtmlStyle); + html.SelectedDataIntoClipboard(this, addErrorInfo, cutLength, m_CancellationTokenSource.Token); + } + catch (Exception ex) + { + Logger.Error(ex, "Issue during Copy"); + } + } + /// /// Handles the Click event of the toolStripMenuItemCopy control. /// /// The source of the event. /// The instance containing the event data. - private void ToolStripMenuItemCopy_Click(object? sender, EventArgs e) - { - var html = new DataGridViewCopyPaste(HtmlStyle); - html.SelectedDataIntoClipboard(this, false, false, m_CancellationTokenSource.Token); - } + private void ToolStripMenuItemCopy_Click(object? sender, EventArgs e) => Copy(false, false); /// /// Handles the Click event of the toolStripMenuItemCopyError control. /// /// The source of the event. /// The instance containing the event data. - private void ToolStripMenuItemCopyError_Click(object? sender, EventArgs e) - { - var html = new DataGridViewCopyPaste(HtmlStyle); - html.SelectedDataIntoClipboard(this, true, false, m_CancellationTokenSource.Token); - } + private void ToolStripMenuItemCopyError_Click(object? sender, EventArgs e) => Copy(true, false); /// /// Handles the Click event of the toolStripMenuItemFilled control. @@ -1433,12 +1450,19 @@ private void ToolStripMenuItemLoadCol_Click(object? sender, EventArgs e) public void SetViewStatus(string newSetting) { - SuspendLayout(); - if (ViewSetting.ReStoreViewSetting(newSetting, Columns, m_Filter, GetColumnFilter, - Sort)) - ApplyFilters(); - ColumnVisibilityChanged(); - ResumeLayout(true); + try + { + SuspendLayout(); + if (ViewSetting.ReStoreViewSetting(newSetting, Columns, m_Filter, GetColumnFilter, + Sort)) + ApplyFilters(); + ColumnVisibilityChanged(); + ResumeLayout(true); + } + catch (Exception ex) + { + Logger.Error(ex, "SetViewStatus"); + } } private async void ToolStripMenuItemSaveCol_Click(object? sender, EventArgs e) @@ -1448,27 +1472,32 @@ private async void ToolStripMenuItemSaveCol_Click(object? sender, EventArgs e) try { toolStripMenuItemSaveCol.Enabled = false; - // Select Path - var fileName = WindowsAPICodePackWrapper.Save( - m_FileSetting is IFileSettingPhysicalFile phy ? phy.FullPath.GetDirectoryName() : ".", "Save Column Setting", - "Column Config|*.col;*.conf|All files|*.*", ".col", false, DefFileNameColSetting(m_FileSetting, ".col")); + var text = GetViewStatus; + if (!string.IsNullOrEmpty(text)) + { + // Select Path + var fileName = WindowsAPICodePackWrapper.Save( + m_FileSetting is IFileSettingPhysicalFile phy ? phy.FullPath.GetDirectoryName() : ".", "Save Column Setting", + "Column Config|*.col;*.conf|All files|*.*", ".col", false, DefFileNameColSetting(m_FileSetting, ".col")); + + if (fileName is null || fileName.Length == 0) + return; - if (fileName is null || fileName.Length == 0) - return; #if NET5_0_OR_GREATER - await -#endif - // ReSharper disable once UseAwaitUsing - using var stream = new ImprovedStream(new SourceAccess(fileName, false)); + await +#endif + using var stream = new ImprovedStream(new SourceAccess(fileName, false)); + #if NET5_0_OR_GREATER - await + await #endif - using var writer = new StreamWriter(stream, Encoding.UTF8, 1024); - await writer.WriteAsync(GetViewStatus); - await writer.FlushAsync(); + using var writer = new StreamWriter(stream, Encoding.UTF8, 1024); + await writer.WriteAsync(GetViewStatus); + await writer.FlushAsync(); - if (m_FileSetting is BaseSettingPhysicalFile basePhysical) - basePhysical.ColumnFile = fileName; + if (m_FileSetting is BaseSettingPhysicalFile basePhysical) + basePhysical.ColumnFile = fileName; + } } catch (Exception ex) { diff --git a/Library/WinFormControls/ViewSetting.cs b/Library/WinFormControls/ViewSetting.cs index e2218412..d7512452 100644 --- a/Library/WinFormControls/ViewSetting.cs +++ b/Library/WinFormControls/ViewSetting.cs @@ -62,29 +62,29 @@ public static class ViewSetting var displayIndex = 0; foreach (var storedColumn in (vst ?? throw new InvalidOperationException()).OrderBy(x => x.DisplayIndex)) - foreach (DataGridViewColumn col in columns) - if (col.DataPropertyName.Equals(storedColumn.DataPropertyName, StringComparison.OrdinalIgnoreCase)) - try - { - if (col.Visible != storedColumn.Visible) - col.Visible = storedColumn.Visible; - - if (col.Visible) + foreach (DataGridViewColumn col in columns) + if (col.DataPropertyName.Equals(storedColumn.DataPropertyName, StringComparison.OrdinalIgnoreCase)) + try { - col.Width = storedColumn.Width; - if (storedColumn.Sort == 1) - doSort?.Invoke(col, ListSortDirection.Ascending); - if (storedColumn.Sort == 2) - doSort?.Invoke(col, ListSortDirection.Descending); + if (col.Visible != storedColumn.Visible) + col.Visible = storedColumn.Visible; + + if (col.Visible) + { + col.Width = storedColumn.Width; + if (storedColumn.Sort == 1) + doSort?.Invoke(col, ListSortDirection.Ascending); + if (storedColumn.Sort == 2) + doSort?.Invoke(col, ListSortDirection.Descending); + } + + col.DisplayIndex = displayIndex++; + break; + } + catch (Exception ex) + { + Logger.Information(ex, "ReStoreViewSetting {text} {col}", text, col); } - - col.DisplayIndex = displayIndex++; - break; - } - catch (Exception ex) - { - Logger.Information(ex, "ReStoreViewSetting {text} {col}", text, col); - } var hasFilterSet = false; foreach (var storedFilterSetting in vst) @@ -134,40 +134,49 @@ public static class ViewSetting } } - public static ICollection GetViewSetting(DataGridViewColumnCollection columns, + public static ICollection? GetViewSetting(DataGridViewColumnCollection columns, IEnumerable columnFilters, DataGridViewColumn? sortedColumn, SortOrder sortOrder) { - var vst = columns.OfType() + try + { + var vst = columns.OfType() .Select(col => new ColumnSetting(col.DataPropertyName, col.Visible, ReferenceEquals(col, sortedColumn) ? (int) sortOrder : 0, col.DisplayIndex, col.Width)).ToList(); - var colIndex = 0; - foreach (var columnFilter in columnFilters) - { - if (columnFilter is null) - continue; - if (columnFilter.ColumnFilterLogic.Active) + var colIndex = 0; + foreach (var columnFilter in columnFilters) { - var hadValueFiler = false; - foreach (var value in columnFilter.ColumnFilterLogic.ValueClusterCollection.ValueClusters.Where(x => - !string.IsNullOrEmpty(x.SQLCondition) && x.Active)) + if (columnFilter is null) + continue; + if (columnFilter.ColumnFilterLogic.Active) { - vst[colIndex].ValueFilters.Add(new ColumnSetting.ValueFilter(value.SQLCondition, value.Display)); - hadValueFiler = true; - } + var hadValueFiler = false; + foreach (var value in columnFilter.ColumnFilterLogic.ValueClusterCollection.ValueClusters.Where(x => + !string.IsNullOrEmpty(x.SQLCondition) && x.Active)) + { + vst[colIndex].ValueFilters.Add(new ColumnSetting.ValueFilter(value.SQLCondition, value.Display)); + hadValueFiler = true; + } - if (!hadValueFiler) - { - vst[colIndex].Operator = columnFilter.ColumnFilterLogic.Operator; - vst[colIndex].ValueText = columnFilter.ColumnFilterLogic.ValueText; - vst[colIndex].ValueDate = columnFilter.ColumnFilterLogic.ValueDateTime; + if (!hadValueFiler) + { + vst[colIndex].Operator = columnFilter.ColumnFilterLogic.Operator; + vst[colIndex].ValueText = columnFilter.ColumnFilterLogic.ValueText; + vst[colIndex].ValueDate = columnFilter.ColumnFilterLogic.ValueDateTime; + } } + + colIndex++; } - colIndex++; + return vst; + } + catch (Exception ex) + { + Logger.Error(ex, "GetViewSetting"); + return null; } - return vst; } /// @@ -175,6 +184,12 @@ public static class ViewSetting /// public static string StoreViewSetting(DataGridViewColumnCollection columns, IEnumerable columnFilters, DataGridViewColumn? sortedColumn, - SortOrder sortOrder) => JsonConvert.SerializeObject(GetViewSetting(columns, columnFilters, sortedColumn, sortOrder), Formatting.None); + SortOrder sortOrder) + { + var res = GetViewSetting(columns, columnFilters, sortedColumn, sortOrder); + if (res == null) + return string.Empty; + return JsonConvert.SerializeObject(res, Formatting.None); + } } } \ No newline at end of file