diff --git a/.github/configs/codeql.yml b/.github/configs/codeql.yml index 9c211adfac..eedcdbcef7 100644 --- a/.github/configs/codeql.yml +++ b/.github/configs/codeql.yml @@ -6,7 +6,39 @@ paths-ignore: - "**/obj/**" - "**/bin/**" - "**/*.Designer.cs" + - "*.g.cs" query-filters: - exclude: - id: cs/catch-of-all-exceptions \ No newline at end of file + id: cs/catch-of-all-exceptions + - exclude: + id: cs/useless-assignment-to-local + - exclude: + id: cs/local-not-disposed + - exclude: + id: cs/missed-readonly-modifier + - exclude: + id: cs/dereferenced-value-may-be-null + - exclude: + id: cs/string-concatenation-in-loop + - exclude: + id: cs/useless-cast-to-self + - exclude: + id: cs/useless-upcast + - exclude: + id: cs/class-missing-equals + - exclude: + id: cs/reference-equality-with-object + - exclude: + id: cs/virtual-call-in-constructor + - exclude: + id: cs/linq/missed-where + - exclude: + id: cs/linq/missed-select + - exclude: + id: cs/nested-if-statements + - exclude: + id: cs/missed-ternary-operator + - exclude: + id: cs/call-to-gc + \ No newline at end of file diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 3f3fa860d4..3514e15c41 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -32,7 +32,6 @@ jobs: languages: ${{ matrix.language }} queries: +security-and-quality config-file: ./.github/configs/codeql.yml - - name: Build run: dotnet build diff --git a/Application/ResearchDataManagementPlatform/WindowManagement/TabNavigation.cs b/Application/ResearchDataManagementPlatform/WindowManagement/TabNavigation.cs index d598d51cb9..05d48972ac 100644 --- a/Application/ResearchDataManagementPlatform/WindowManagement/TabNavigation.cs +++ b/Application/ResearchDataManagementPlatform/WindowManagement/TabNavigation.cs @@ -35,9 +35,7 @@ public void Close() public override string ToString() => Tab.TabText; - public override bool Equals(object obj) => - obj is TabNavigation navigation && - EqualityComparer.Default.Equals(Tab, navigation.Tab); + public override bool Equals(object obj) => obj.GetType() == typeof(TabNavigation) && EqualityComparer.Default.Equals(Tab, ((TabNavigation)obj).Tab); public override int GetHashCode() { diff --git a/Rdmp.Core.Tests/Curation/Integration/CommitInProgressTests.cs b/Rdmp.Core.Tests/Curation/Integration/CommitInProgressTests.cs index a62049e88a..c7b04a568a 100644 --- a/Rdmp.Core.Tests/Curation/Integration/CommitInProgressTests.cs +++ b/Rdmp.Core.Tests/Curation/Integration/CommitInProgressTests.cs @@ -54,26 +54,24 @@ public void CommitInProgress_TestCancellation() Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.NoChanges), "We just created this Catalogue, how can db copy be different?!"); - var start = new CommitInProgress(RepositoryLocator, new CommitInProgressSettings(c) + using (var start = new CommitInProgress(RepositoryLocator, new CommitInProgressSettings(c) { UseTransactions = true - }); - - // there is a CommitInProgress on c so db should not have - c.Name = "abadaba"; - c.IsDeprecated = true; - - Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.DatabaseCopyDifferent), - "We have local changes"); + })) + { + // there is a CommitInProgress on c so db should not have + c.Name = "abadaba"; + c.IsDeprecated = true; - c.SaveToDatabase(); + Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.DatabaseCopyDifferent), + "We have local changes"); - Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.NoChanges), - "Should be saved inside the transaction"); + c.SaveToDatabase(); - // abandon the commit - start.Dispose(); + Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.NoChanges), + "Should be saved inside the transaction"); + } Assert.That(c.HasLocalChanges().Evaluation, Is.EqualTo(ChangeDescription.DatabaseCopyDifferent), "With transaction rolled back the Catalogue should now no longer match db state - i.e. be unsaved"); diff --git a/Rdmp.Core.Tests/Curation/Integration/LookupTest.cs b/Rdmp.Core.Tests/Curation/Integration/LookupTest.cs index 8ab485bd43..266f410827 100644 --- a/Rdmp.Core.Tests/Curation/Integration/LookupTest.cs +++ b/Rdmp.Core.Tests/Curation/Integration/LookupTest.cs @@ -81,6 +81,7 @@ public void CreateLookup_linkWithSelfThrowsException() } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -89,6 +90,7 @@ public void CreateLookup_linkWithSelfThrowsException() } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -97,6 +99,7 @@ public void CreateLookup_linkWithSelfThrowsException() } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -105,6 +108,7 @@ public void CreateLookup_linkWithSelfThrowsException() } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } } @@ -114,6 +118,7 @@ public void CreateLookup_linkWithSelfThrowsException() } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } } @@ -162,6 +167,7 @@ public void CreateLookup_linkWithOtherTable(bool memoryRepo) } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -170,6 +176,7 @@ public void CreateLookup_linkWithOtherTable(bool memoryRepo) } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -178,6 +185,7 @@ public void CreateLookup_linkWithOtherTable(bool memoryRepo) } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -186,6 +194,7 @@ public void CreateLookup_linkWithOtherTable(bool memoryRepo) } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } try @@ -194,6 +203,7 @@ public void CreateLookup_linkWithOtherTable(bool memoryRepo) } catch (Exception) { + Console.WriteLine("Unable To Delete child"); } } } diff --git a/Rdmp.Core.Tests/Curation/Unit/AggregateConfigurationTests.cs b/Rdmp.Core.Tests/Curation/Unit/AggregateConfigurationTests.cs index 35c785ce87..0e6d5c888a 100644 --- a/Rdmp.Core.Tests/Curation/Unit/AggregateConfigurationTests.cs +++ b/Rdmp.Core.Tests/Curation/Unit/AggregateConfigurationTests.cs @@ -17,47 +17,52 @@ internal class AggregateConfigurationTests : UnitTests [Test] public void TestStripZeroSeries_EmptyTable() { - var dt = new DataTable(); - dt.Columns.Add("col1"); - dt.Columns.Add("col2"); + using (var dt = new DataTable()) - UserSettings.IncludeZeroSeriesInGraphs = false; + { + dt.Columns.Add("col1"); + dt.Columns.Add("col2"); + + UserSettings.IncludeZeroSeriesInGraphs = false; - // empty tables should not get nuked - AggregateConfiguration.AdjustGraphDataTable(dt); - Assert.That(dt.Columns, Has.Count.EqualTo(2)); + // empty tables should not get nuked + AggregateConfiguration.AdjustGraphDataTable(dt); + Assert.That(dt.Columns, Has.Count.EqualTo(2)); + } - dt.Dispose(); } + [TestCase(true)] [TestCase(false)] public void TestStripZeroSeries_Nulls(bool includeZeroSeries) { - var dt = new DataTable(); - dt.Columns.Add("date"); - dt.Columns.Add("col1"); - dt.Columns.Add("col2"); + using (var dt = new DataTable()) + { + dt.Columns.Add("date"); + dt.Columns.Add("col1"); + dt.Columns.Add("col2"); - dt.Rows.Add("2001", 0, 12); - dt.Rows.Add("2002", null, 333); + dt.Rows.Add("2001", 0, 12); + dt.Rows.Add("2002", null, 333); - UserSettings.IncludeZeroSeriesInGraphs = includeZeroSeries; + UserSettings.IncludeZeroSeriesInGraphs = includeZeroSeries; - AggregateConfiguration.AdjustGraphDataTable(dt); + AggregateConfiguration.AdjustGraphDataTable(dt); - if (includeZeroSeries) - { - Assert.That(dt.Columns, Has.Count.EqualTo(3)); - } - else - { - // col1 should have been gotten rid of - Assert.That(dt.Columns, Has.Count.EqualTo(2)); - dt.Columns.Contains("date"); - dt.Columns.Contains("col2"); + if (includeZeroSeries) + { + Assert.That(dt.Columns, Has.Count.EqualTo(3)); + } + else + { + // col1 should have been gotten rid of + Assert.That(dt.Columns, Has.Count.EqualTo(2)); + dt.Columns.Contains("date"); + dt.Columns.Contains("col2"); + } } - dt.Dispose(); } + } \ No newline at end of file diff --git a/Rdmp.Core.Tests/DataExport/DataExtraction/ExecuteDatasetExtractionFlatFileDestinationTests.cs b/Rdmp.Core.Tests/DataExport/DataExtraction/ExecuteDatasetExtractionFlatFileDestinationTests.cs index 98ec316b49..e78f3c1379 100644 --- a/Rdmp.Core.Tests/DataExport/DataExtraction/ExecuteDatasetExtractionFlatFileDestinationTests.cs +++ b/Rdmp.Core.Tests/DataExport/DataExtraction/ExecuteDatasetExtractionFlatFileDestinationTests.cs @@ -26,35 +26,36 @@ public void ExtractionDestination_FloatRounding(bool lotsOfDecimalPlaces) { var dest = new ExecuteDatasetExtractionFlatFileDestination(); - var dt = new DataTable(); - dt.Columns.Add("Floats", typeof(decimal)); + using (var dt = new DataTable()) + { - dt.Rows.Add(Math.PI); + dt.Columns.Add("Floats", typeof(decimal)); - var lm = new LogManager(new DiscoveredServer(UnitTestLoggingConnectionString)); - lm.CreateNewLoggingTaskIfNotExists("ExtractionDestination_FloatRounding"); + dt.Rows.Add(Math.PI); - var dli = lm.CreateDataLoadInfo("ExtractionDestination_FloatRounding", - nameof(ExecuteDatasetExtractionFlatFileDestinationTests), "test", "", true); + var lm = new LogManager(new DiscoveredServer(UnitTestLoggingConnectionString)); + lm.CreateNewLoggingTaskIfNotExists("ExtractionDestination_FloatRounding"); - if (_request.QueryBuilder == null) _request.GenerateQueryBuilder(); - dest.RoundFloatsTo = lotsOfDecimalPlaces ? 10 : 2; + var dli = lm.CreateDataLoadInfo("ExtractionDestination_FloatRounding", + nameof(ExecuteDatasetExtractionFlatFileDestinationTests), "test", "", true); - dest.PreInitialize(_request, ThrowImmediatelyDataLoadEventListener.Quiet); - dest.PreInitialize(_project, ThrowImmediatelyDataLoadEventListener.Quiet); - dest.PreInitialize((DataLoadInfo)dli, ThrowImmediatelyDataLoadEventListener.Quiet); + if (_request.QueryBuilder == null) _request.GenerateQueryBuilder(); + dest.RoundFloatsTo = lotsOfDecimalPlaces ? 10 : 2; - dest.ProcessPipelineData(dt, ThrowImmediatelyDataLoadEventListener.Quiet, new GracefulCancellationToken()); - dest.Dispose(ThrowImmediatelyDataLoadEventListener.Quiet, null); + dest.PreInitialize(_request, ThrowImmediatelyDataLoadEventListener.Quiet); + dest.PreInitialize(_project, ThrowImmediatelyDataLoadEventListener.Quiet); + dest.PreInitialize((DataLoadInfo)dli, ThrowImmediatelyDataLoadEventListener.Quiet); - Assert.That(dest.OutputFile, Is.Not.Null); - FileAssert.Exists(dest.OutputFile); + dest.ProcessPipelineData(dt, ThrowImmediatelyDataLoadEventListener.Quiet, new GracefulCancellationToken()); + dest.Dispose(ThrowImmediatelyDataLoadEventListener.Quiet, null); - Assert.That( -File.ReadAllText(dest.OutputFile), Is.EqualTo(lotsOfDecimalPlaces - ? $"Floats{Environment.NewLine}3.1415926536{Environment.NewLine}" - : $"Floats{Environment.NewLine}3.14{Environment.NewLine}")); + Assert.That(dest.OutputFile, Is.Not.Null); + FileAssert.Exists(dest.OutputFile); - dt.Dispose(); + Assert.That( + File.ReadAllText(dest.OutputFile), Is.EqualTo(lotsOfDecimalPlaces + ? $"Floats{Environment.NewLine}3.1415926536{Environment.NewLine}" + : $"Floats{Environment.NewLine}3.14{Environment.NewLine}")); + } } } \ No newline at end of file diff --git a/Rdmp.Core.Tests/DataLoad/Engine/Integration/FlatFileAttacherTests.cs b/Rdmp.Core.Tests/DataLoad/Engine/Integration/FlatFileAttacherTests.cs index 488ccbf076..a9e7483b7f 100644 --- a/Rdmp.Core.Tests/DataLoad/Engine/Integration/FlatFileAttacherTests.cs +++ b/Rdmp.Core.Tests/DataLoad/Engine/Integration/FlatFileAttacherTests.cs @@ -69,26 +69,27 @@ protected override void SetUp() public void Test_CSV_Attachment(string separator, bool overrideHeaders) { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); + using (var sw = new StreamWriter(filename)) + { - sw.WriteLine("name,name2"); - sw.WriteLine("Bob,Munchousain"); - sw.WriteLine("Franky,Hollyw9ood"); + sw.WriteLine("name,name2"); + sw.WriteLine("Bob,Munchousain"); + sw.WriteLine("Franky,Hollyw9ood"); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } var filename2 = Path.Combine(_loadDirectory.ForLoading.FullName, "bob2.csv"); - var sw2 = new StreamWriter(filename2); - - sw2.WriteLine("name,name2"); - sw2.WriteLine("Manny2,Ok"); + using (var sw2 = new StreamWriter(filename2)) + { + sw2.WriteLine("name,name2"); + sw2.WriteLine("Manny2,Ok"); - sw2.Flush(); - sw2.Close(); - sw2.Dispose(); + sw2.Flush(); + sw2.Close(); + }; var attacher = new AnySeparatorFileAttacher(); attacher.Initialize(_loadDirectory, _database); @@ -159,15 +160,16 @@ public void Test_CSV_Attachment(string separator, bool overrideHeaders) public void Test_ExplicitDateTimeFormat_Attachment() { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); + using (var sw = new StreamWriter(filename)) + { - sw.WriteLine("name,name2"); - sw.WriteLine("Bob,20011301"); - sw.WriteLine("Franky,20021301"); + sw.WriteLine("name,name2"); + sw.WriteLine("Bob,20011301"); + sw.WriteLine("Franky,20021301"); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } var attacher = new AnySeparatorFileAttacher(); attacher.Initialize(_loadDirectory, _database); @@ -216,14 +218,15 @@ public void Test_ExplicitDateTimeFormat_Attachment() public void TabTestWithOverrideHeaders() { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); + using (var sw = new StreamWriter(filename)) + { - sw.WriteLine("Face\tBasher"); - sw.WriteLine("Candy\tCrusher"); + sw.WriteLine("Face\tBasher"); + sw.WriteLine("Candy\tCrusher"); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } var attacher = new AnySeparatorFileAttacher(); attacher.Initialize(_loadDirectory, _database); @@ -264,14 +267,15 @@ public void TabTestWithOverrideHeaders() public void TabTestWithOverrideHeaders_IncludePath(bool columnExistsInRaw) { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); + using (var sw = new StreamWriter(filename)) + { - sw.WriteLine("Face\tBasher"); - sw.WriteLine("Candy\tCrusher"); + sw.WriteLine("Face\tBasher"); + sw.WriteLine("Candy\tCrusher"); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } if (columnExistsInRaw) _table.AddColumn("FilePath", new DatabaseTypeRequest(typeof(string), 500), true, 30); @@ -329,16 +333,16 @@ public void TestTableInfo(bool username) #pragma warning restore VSSpell001 // Spell Check { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); - - sw.WriteLine("name,name2"); - sw.WriteLine("Bob,Munchousain"); - sw.WriteLine("Franky,Hollyw9ood"); + using (var sw = new StreamWriter(filename)) + { - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.WriteLine("name,name2"); + sw.WriteLine("Bob,Munchousain"); + sw.WriteLine("Franky,Hollyw9ood"); + sw.Flush(); + sw.Close(); + } Import(_table, out var ti, out _); var attacher = new AnySeparatorFileAttacher(); @@ -390,15 +394,16 @@ public void TestTableInfo(bool username) public void Test_FlatFileAttacher_IgnoreColumns() { var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); + using (var sw = new StreamWriter(filename)) + { - sw.WriteLine("name,name2,address"); - sw.WriteLine("Bob,Munchousain,\"67, franklin\""); - sw.WriteLine("Franky,Hollyw9ood,32 dodgery"); + sw.WriteLine("name,name2,address"); + sw.WriteLine("Bob,Munchousain,\"67, franklin\""); + sw.WriteLine("Franky,Hollyw9ood,32 dodgery"); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } Import(_table, out var ti, out _); var attacher = new AnySeparatorFileAttacher @@ -458,14 +463,14 @@ public void Test_FlatFileAttacher_AmbiguousDates(DatabaseType type, string val, Thread.CurrentThread.CurrentCulture = new CultureInfo(threadCulture); var filename = Path.Combine(_loadDirectory.ForLoading.FullName, "bob.csv"); - var sw = new StreamWriter(filename); - - sw.WriteLine("dob"); - sw.WriteLine(val); + using (var sw = new StreamWriter(filename)) + { + sw.WriteLine("dob"); + sw.WriteLine(val); - sw.Flush(); - sw.Close(); - sw.Dispose(); + sw.Flush(); + sw.Close(); + } var db = GetCleanedServer(type); diff --git a/Rdmp.Core.Tests/DataLoad/Engine/Integration/HICPipelineTests.cs b/Rdmp.Core.Tests/DataLoad/Engine/Integration/HICPipelineTests.cs index dc87c28ca8..2cea8de889 100644 --- a/Rdmp.Core.Tests/DataLoad/Engine/Integration/HICPipelineTests.cs +++ b/Rdmp.Core.Tests/DataLoad/Engine/Integration/HICPipelineTests.cs @@ -223,90 +223,91 @@ public void TestSingleJob(bool overrideRAW, bool sendDodgyCredentials) var testDir = Directory.CreateDirectory(testDirPath); var server = DiscoveredServerICanCreateRandomDatabasesAndTablesOn; - var catalogueEntities = new CatalogueEntities(); - var databaseHelper = new DatabaseHelper(); - ExternalDatabaseServer external = null; - - try + using (var catalogueEntities = new CatalogueEntities()) { - // Set SetUp the dataset's project directory and add the CSV file to ForLoading - var loadDirectory = LoadDirectory.CreateDirectoryStructure(testDir, "TestDataset"); - File.WriteAllText(Path.Combine(loadDirectory.ForLoading.FullName, "1.csv"), - "Col1\r\n1\r\n2\r\n3\r\n4"); - - databaseHelper.SetUp(server); - - // Create the Catalogue entities for the dataset - catalogueEntities.Create(CatalogueTableRepository, databaseHelper.DatabaseToLoad, loadDirectory); - - if (overrideRAW) + using (var databaseHelper = new DatabaseHelper()) { - external = new ExternalDatabaseServer(CatalogueRepository, "RAW Server", null); - external.SetProperties(DiscoveredServerICanCreateRandomDatabasesAndTablesOn.ExpectDatabase("master")); + ExternalDatabaseServer external = null; - if (sendDodgyCredentials) + try { - external.Username = "IveGotaLovely"; - external.Password = "BunchOfCoconuts"; + // Set SetUp the dataset's project directory and add the CSV file to ForLoading + var loadDirectory = LoadDirectory.CreateDirectoryStructure(testDir, "TestDataset"); + File.WriteAllText(Path.Combine(loadDirectory.ForLoading.FullName, "1.csv"), + "Col1\r\n1\r\n2\r\n3\r\n4"); + + databaseHelper.SetUp(server); + + // Create the Catalogue entities for the dataset + catalogueEntities.Create(CatalogueTableRepository, databaseHelper.DatabaseToLoad, loadDirectory); + + if (overrideRAW) + { + external = new ExternalDatabaseServer(CatalogueRepository, "RAW Server", null); + external.SetProperties(DiscoveredServerICanCreateRandomDatabasesAndTablesOn.ExpectDatabase("master")); + + if (sendDodgyCredentials) + { + external.Username = "IveGotaLovely"; + external.Password = "BunchOfCoconuts"; + } + + external.SaveToDatabase(); + + defaults.SetDefault(PermissableDefaults.RAWDataLoadServer, external); + } + + var options = new DleOptions + { + LoadMetadata = catalogueEntities.LoadMetadata.ID.ToString(), + Command = CommandLineActivity.check + }; + + //run checks (with ignore errors if we are sending dodgy credentials) + RunnerFactory.CreateRunner(new ThrowImmediatelyActivator(RepositoryLocator), options).Run(RepositoryLocator, + ThrowImmediatelyDataLoadEventListener.Quiet, + sendDodgyCredentials + ? (ICheckNotifier)IgnoreAllErrorsCheckNotifier.Instance + : new AcceptAllCheckNotifier(), new GracefulCancellationToken()); + + //run load + options.Command = CommandLineActivity.run; + var runner = RunnerFactory.CreateRunner(new ThrowImmediatelyActivator(RepositoryLocator), options); + + + if (sendDodgyCredentials) + { + var ex = Assert.Throws(() => runner.Run(RepositoryLocator, + ThrowImmediatelyDataLoadEventListener.Quiet, new AcceptAllCheckNotifier(), + new GracefulCancellationToken())); + Assert.That(ex.InnerException.Message, Does.Contain("Login failed for user 'IveGotaLovely'"), + "Error message did not contain expected text"); + return; + } + else + { + runner.Run(RepositoryLocator, ThrowImmediatelyDataLoadEventListener.Quiet, new AcceptAllCheckNotifier(), + new GracefulCancellationToken()); + } + + + var archiveFile = loadDirectory.ForArchiving.EnumerateFiles("*.zip").MaxBy(f => f.FullName); + Assert.Multiple(() => + { + Assert.That(archiveFile, Is.Not.Null, "Archive file has not been created by the load."); + Assert.That(loadDirectory.ForLoading.EnumerateFileSystemInfos().Any(), Is.False); + }); } + finally + { + //reset the original RAW server + defaults.SetDefault(PermissableDefaults.RAWDataLoadServer, oldDefault); - external.SaveToDatabase(); - - defaults.SetDefault(PermissableDefaults.RAWDataLoadServer, external); - } - - var options = new DleOptions - { - LoadMetadata = catalogueEntities.LoadMetadata.ID.ToString(), - Command = CommandLineActivity.check - }; - - //run checks (with ignore errors if we are sending dodgy credentials) - RunnerFactory.CreateRunner(new ThrowImmediatelyActivator(RepositoryLocator), options).Run(RepositoryLocator, - ThrowImmediatelyDataLoadEventListener.Quiet, - sendDodgyCredentials - ? (ICheckNotifier)IgnoreAllErrorsCheckNotifier.Instance - : new AcceptAllCheckNotifier(), new GracefulCancellationToken()); - - //run load - options.Command = CommandLineActivity.run; - var runner = RunnerFactory.CreateRunner(new ThrowImmediatelyActivator(RepositoryLocator), options); - + external?.DeleteInDatabase(); - if (sendDodgyCredentials) - { - var ex = Assert.Throws(() => runner.Run(RepositoryLocator, - ThrowImmediatelyDataLoadEventListener.Quiet, new AcceptAllCheckNotifier(), - new GracefulCancellationToken())); - Assert.That(ex.InnerException.Message, Does.Contain("Login failed for user 'IveGotaLovely'"), - "Error message did not contain expected text"); - return; - } - else - { - runner.Run(RepositoryLocator, ThrowImmediatelyDataLoadEventListener.Quiet, new AcceptAllCheckNotifier(), - new GracefulCancellationToken()); + testDir.Delete(true); + } } - - - var archiveFile = loadDirectory.ForArchiving.EnumerateFiles("*.zip").MaxBy(f => f.FullName); - Assert.Multiple(() => - { - Assert.That(archiveFile, Is.Not.Null, "Archive file has not been created by the load."); - Assert.That(loadDirectory.ForLoading.EnumerateFileSystemInfos().Any(), Is.False); - }); - } - finally - { - //reset the original RAW server - defaults.SetDefault(PermissableDefaults.RAWDataLoadServer, oldDefault); - - external?.DeleteInDatabase(); - - testDir.Delete(true); - - databaseHelper.Dispose(); - catalogueEntities.Dispose(); } } } diff --git a/Rdmp.Core.Tests/Logging/LogManagerTest.cs b/Rdmp.Core.Tests/Logging/LogManagerTest.cs index aa23f34db8..69d2cecd4b 100644 --- a/Rdmp.Core.Tests/Logging/LogManagerTest.cs +++ b/Rdmp.Core.Tests/Logging/LogManagerTest.cs @@ -226,7 +226,7 @@ public void LoggingDatabase_TestActuallyCreatingIt(DatabaseType type) Assert.That(archival.TableLoadInfos.Single().Updates, Is.EqualTo(0)); Assert.That(archival.TableLoadInfos.Single().Deletes, Is.EqualTo(0)); Assert.That(archival.StartTime.Date, Is.EqualTo(DateTime.Now.Date)); - Assert.That(archival.EndTime.Value.Date, Is.EqualTo(DateTime.Now.Date)); + Assert.That(archival?.EndTime.Value.Date, Is.EqualTo(DateTime.Now.Date)); Assert.That(archival.Errors.Single().Description, Is.EqualTo("it went bad")); Assert.That(archival.Errors.Single().Source, Is.EqualTo("bad.cs")); diff --git a/Rdmp.Core.Tests/Validation/Constraints/Primary/BoundsValidationDateTest.cs b/Rdmp.Core.Tests/Validation/Constraints/Primary/BoundsValidationDateTest.cs index 24b51ec5f0..a5ee2eae0e 100644 --- a/Rdmp.Core.Tests/Validation/Constraints/Primary/BoundsValidationDateTest.cs +++ b/Rdmp.Core.Tests/Validation/Constraints/Primary/BoundsValidationDateTest.cs @@ -221,7 +221,7 @@ public void must_occur_before_field_INVALID_violation_report() if (result == null) Assert.Fail(); - var l = result.GetExceptionList(); + var l = result?.GetExceptionList(); Assert.That(l[0].Message, Does.EndWith($"Expected a date less than [{b.UpperFieldName}].")); Console.WriteLine(result.Message); diff --git a/Rdmp.Core.Tests/Validation/Constraints/Secondary/BoundDateTest.cs b/Rdmp.Core.Tests/Validation/Constraints/Secondary/BoundDateTest.cs index dbc97e377d..d36784b94f 100644 --- a/Rdmp.Core.Tests/Validation/Constraints/Secondary/BoundDateTest.cs +++ b/Rdmp.Core.Tests/Validation/Constraints/Secondary/BoundDateTest.cs @@ -71,7 +71,7 @@ public void Validate_IsInvalid_ThrowsExceptionWithConsequence() Assert.Fail("Expected validation exception, but none came"); - Assert.That(result.SourceConstraint, Is.Not.Null); + Assert.That(result?.SourceConstraint, Is.Not.Null); Assert.That(result.SourceConstraint.Consequence, Is.EqualTo(Consequence.InvalidatesRow)); } diff --git a/Rdmp.Core/Caching/PermissionWindowCacheDownloader.cs b/Rdmp.Core/Caching/PermissionWindowCacheDownloader.cs index 2656b5c18c..cbbbd740a4 100644 --- a/Rdmp.Core/Caching/PermissionWindowCacheDownloader.cs +++ b/Rdmp.Core/Caching/PermissionWindowCacheDownloader.cs @@ -157,6 +157,7 @@ private RetrievalResult RunOnce(GracefulCancellationToken cancellationToken, } catch (AggregateException) { + Console.WriteLine("Unknown AggregateException"); } return RetrievalResult.Aborted; diff --git a/Rdmp.Core/Caching/Pipeline/Destinations/CacheFilesystemDestination.cs b/Rdmp.Core/Caching/Pipeline/Destinations/CacheFilesystemDestination.cs index 04511fd52a..b5fb2cc340 100644 --- a/Rdmp.Core/Caching/Pipeline/Destinations/CacheFilesystemDestination.cs +++ b/Rdmp.Core/Caching/Pipeline/Destinations/CacheFilesystemDestination.cs @@ -82,9 +82,10 @@ public virtual void Check(ICheckNotifier notifier) try { var tempFilename = Path.Combine(CacheDirectory.FullName, ".test.txt"); - var sw = File.CreateText(tempFilename); - sw.Close(); - sw.Dispose(); + using (var sw = File.CreateText(tempFilename)) + { + sw.Close(); + } File.Delete(tempFilename); notifier.OnCheckPerformed(new CheckEventArgs( $"Confirmed could write to/delete from the overridden CacheDirectory: {CacheDirectory.FullName}", diff --git a/Rdmp.Core/CommandExecution/AtomicCommands/CatalogueCreationCommands/CatalogueCreationCommandExecution.cs b/Rdmp.Core/CommandExecution/AtomicCommands/CatalogueCreationCommands/CatalogueCreationCommandExecution.cs index d14b3a0491..66840443dd 100644 --- a/Rdmp.Core/CommandExecution/AtomicCommands/CatalogueCreationCommands/CatalogueCreationCommandExecution.cs +++ b/Rdmp.Core/CommandExecution/AtomicCommands/CatalogueCreationCommands/CatalogueCreationCommandExecution.cs @@ -49,8 +49,7 @@ public override void Execute() { base.Execute(); - if (PromptForProject) - if (SelectOne(BasicActivator.RepositoryLocator.DataExportRepository, out Project p)) + if (PromptForProject && SelectOne(BasicActivator.RepositoryLocator.DataExportRepository, out Project p)) ProjectSpecific = p; } } \ No newline at end of file diff --git a/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandCreateNewCohortIdentificationConfiguration.cs b/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandCreateNewCohortIdentificationConfiguration.cs index 5ae6e3f082..077e2ffa20 100644 --- a/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandCreateNewCohortIdentificationConfiguration.cs +++ b/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandCreateNewCohortIdentificationConfiguration.cs @@ -136,14 +136,13 @@ private CohortIdentificationConfiguration GenerateBasicCohortIdentificationConfi { var name = _name; - if (name == null) - if (!BasicActivator.TypeText(new DialogArgs - { - WindowTitle = "New Cohort Builder Query", - TaskDescription = "Enter a name for the Cohort Builder Query.", - EntryLabel = "Name" - }, 255, null, out name, false)) - return null; + if (name == null && !BasicActivator.TypeText(new DialogArgs + { + WindowTitle = "New Cohort Builder Query", + TaskDescription = "Enter a name for the Cohort Builder Query.", + EntryLabel = "Name" + }, 255, null, out name, false)) + return null; var cic = new CohortIdentificationConfiguration(BasicActivator.RepositoryLocator.CatalogueRepository, name); cic.CreateRootContainerIfNotExists(); diff --git a/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandViewFilterMatchData.cs b/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandViewFilterMatchData.cs index c3b8d4ccc5..fea7379908 100644 --- a/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandViewFilterMatchData.cs +++ b/Rdmp.Core/CommandExecution/AtomicCommands/ExecuteCommandViewFilterMatchData.cs @@ -116,7 +116,7 @@ public override string GetCommandName() protected override IViewSQLAndResultsCollection GetCollection() { - _columnInfo ??= SelectOne(_candidates, _columnInfo != null ? _columnInfo.Name : ""); + _columnInfo = SelectOne(_candidates, _columnInfo != null ? _columnInfo.Name : ""); if (_columnInfo == null) return null; diff --git a/Rdmp.Core/CommandExecution/BasicCommandExecution.cs b/Rdmp.Core/CommandExecution/BasicCommandExecution.cs index c11048852d..1c703d4ac5 100644 --- a/Rdmp.Core/CommandExecution/BasicCommandExecution.cs +++ b/Rdmp.Core/CommandExecution/BasicCommandExecution.cs @@ -420,46 +420,45 @@ protected object Construct(Type toConstruct, Func constructorSe var constructorValues = new List(); - var pickerEnumerator = pickerArgsIfAny?.GetEnumerator(); - - foreach (var parameterInfo in constructor.GetParameters()) + using (var pickerEnumerator = pickerArgsIfAny?.GetEnumerator()) { - var required = new RequiredArgument(parameterInfo); - var parameterDelegate = invoker.GetDelegate(required); - - if (parameterDelegate.IsAuto) + foreach (var parameterInfo in constructor.GetParameters()) { - constructorValues.Add(parameterDelegate.Run(required)); - } - else - { - //it's not auto - if (pickerEnumerator != null) - { - pickerEnumerator.MoveNext(); + var required = new RequiredArgument(parameterInfo); + var parameterDelegate = invoker.GetDelegate(required); - if (pickerEnumerator.Current == null) - throw new ArgumentException( - $"Value needed for parameter '{required.Name}' (of type '{required.Type}')"); - - //construct with the picker arguments - if (!pickerEnumerator.Current.HasValueOfType(required.Type)) - throw new NotSupportedException( - $"Argument '{pickerEnumerator.Current.RawValue}' could not be converted to required Type '{required.Type}' for argument {required.Name}"); - - //it is a valid object yay! - constructorValues.Add(pickerEnumerator.Current.GetValueForParameterOfType(required.Type)); + if (parameterDelegate.IsAuto) + { + constructorValues.Add(parameterDelegate.Run(required)); } else { - //construct by prompting user for the values - constructorValues.Add(invoker.GetValueForParameterOfType(parameterInfo)); + //it's not auto + if (pickerEnumerator != null) + { + pickerEnumerator.MoveNext(); + + if (pickerEnumerator.Current == null) + throw new ArgumentException( + $"Value needed for parameter '{required.Name}' (of type '{required.Type}')"); + + //construct with the picker arguments + if (!pickerEnumerator.Current.HasValueOfType(required.Type)) + throw new NotSupportedException( + $"Argument '{pickerEnumerator.Current.RawValue}' could not be converted to required Type '{required.Type}' for argument {required.Name}"); + + //it is a valid object yay! + constructorValues.Add(pickerEnumerator.Current.GetValueForParameterOfType(required.Type)); + } + else + { + //construct by prompting user for the values + constructorValues.Add(invoker.GetValueForParameterOfType(parameterInfo)); + } } } } - pickerEnumerator?.Dispose(); - return constructor.Invoke(constructorValues.ToArray()); } diff --git a/Rdmp.Core/Curation/Data/Catalogue.cs b/Rdmp.Core/Curation/Data/Catalogue.cs index eca05444f2..b1850fa518 100644 --- a/Rdmp.Core/Curation/Data/Catalogue.cs +++ b/Rdmp.Core/Curation/Data/Catalogue.cs @@ -682,7 +682,7 @@ public Catalogue(ICatalogueRepository repository, string name) { "LiveLoggingServer_ID", loggingServer == null ? DBNull.Value : loggingServer.ID } }); - if (ID == 0 || string.IsNullOrWhiteSpace(Name) || Repository != repository) + if (ID == 0 || string.IsNullOrWhiteSpace(Name) || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); //if there is a default logging server @@ -847,6 +847,15 @@ public int CompareTo(object obj) throw new Exception($"Cannot compare {GetType().Name} to {obj.GetType().Name}"); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } + /// /// Checks that the Catalogue has a sensible Name (See ). Then checks that there are no missing ColumnInfos /// diff --git a/Rdmp.Core/Curation/Data/CatalogueItem.cs b/Rdmp.Core/Curation/Data/CatalogueItem.cs index a70059caca..a64cf2632c 100644 --- a/Rdmp.Core/Curation/Data/CatalogueItem.cs +++ b/Rdmp.Core/Curation/Data/CatalogueItem.cs @@ -317,6 +317,14 @@ public int CompareTo(object obj) throw new Exception($"Cannot compare {GetType().Name} to {obj.GetType().Name}"); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } /// /// Copies the descriptive metadata from one (this) into a new in the supplied diff --git a/Rdmp.Core/Curation/Data/ColumnInfo.cs b/Rdmp.Core/Curation/Data/ColumnInfo.cs index c0f192138f..eb2ac206ed 100644 --- a/Rdmp.Core/Curation/Data/ColumnInfo.cs +++ b/Rdmp.Core/Curation/Data/ColumnInfo.cs @@ -367,6 +367,14 @@ public int CompareTo(object obj) throw new Exception($"Cannot compare {GetType().Name} to {obj.GetType().Name}"); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } /// public string GetRuntimeName() => Name == null ? null : GetQuerySyntaxHelper().GetRuntimeName(Name); diff --git a/Rdmp.Core/Curation/Data/ConcreteColumn.cs b/Rdmp.Core/Curation/Data/ConcreteColumn.cs index f720d8df9d..eb3bb11f20 100644 --- a/Rdmp.Core/Curation/Data/ConcreteColumn.cs +++ b/Rdmp.Core/Curation/Data/ConcreteColumn.cs @@ -127,4 +127,13 @@ public void Check(ICheckNotifier notifier) /// /// public int CompareTo(object obj) => obj is IColumn ? Order - (obj as IColumn).Order : 0; + + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } } \ No newline at end of file diff --git a/Rdmp.Core/Curation/Data/ConnectionStringKeyword.cs b/Rdmp.Core/Curation/Data/ConnectionStringKeyword.cs index 388b7ab170..56cf035b72 100644 --- a/Rdmp.Core/Curation/Data/ConnectionStringKeyword.cs +++ b/Rdmp.Core/Curation/Data/ConnectionStringKeyword.cs @@ -82,7 +82,7 @@ public ConnectionStringKeyword(ICatalogueRepository repository, DatabaseType dat { "Value", value } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } diff --git a/Rdmp.Core/Curation/Data/ExtractionInformation.cs b/Rdmp.Core/Curation/Data/ExtractionInformation.cs index 705cfc42d8..b3e9ee49a2 100644 --- a/Rdmp.Core/Curation/Data/ExtractionInformation.cs +++ b/Rdmp.Core/Curation/Data/ExtractionInformation.cs @@ -219,6 +219,8 @@ public override string ToString() /// public override int GetHashCode() => ID.GetHashCode(); + public override bool Equals(Object obj ) => base.Equals(obj); + /// public IHasDependencies[] GetObjectsThisDependsOn() { diff --git a/Rdmp.Core/Curation/Data/FolderNode.cs b/Rdmp.Core/Curation/Data/FolderNode.cs index 9b3e1991dd..d08f27b49d 100644 --- a/Rdmp.Core/Curation/Data/FolderNode.cs +++ b/Rdmp.Core/Curation/Data/FolderNode.cs @@ -78,9 +78,7 @@ private FolderNode GetChild(string key) public override string ToString() => Name; - public override bool Equals(object obj) => - obj is FolderNode node && - FullName == node.FullName; + public override bool Equals(object obj) => obj.GetType() == typeof(FolderNode) && ((FolderNode)obj).Name == FullName; public override int GetHashCode() => HashCode.Combine(FullName); } \ No newline at end of file diff --git a/Rdmp.Core/Curation/Data/ImportExport/ObjectExport.cs b/Rdmp.Core/Curation/Data/ImportExport/ObjectExport.cs index 3eb531839f..fef7312db8 100644 --- a/Rdmp.Core/Curation/Data/ImportExport/ObjectExport.cs +++ b/Rdmp.Core/Curation/Data/ImportExport/ObjectExport.cs @@ -62,7 +62,7 @@ internal ObjectExport(ICatalogueRepository repository, IMapsDirectlyToDatabaseTa { "SharingUID", guid.ToString() } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); ClearAllInjections(); diff --git a/Rdmp.Core/Curation/Data/ImportExport/ObjectImport.cs b/Rdmp.Core/Curation/Data/ImportExport/ObjectImport.cs index 43d32b0230..6e5918d27e 100644 --- a/Rdmp.Core/Curation/Data/ImportExport/ObjectImport.cs +++ b/Rdmp.Core/Curation/Data/ImportExport/ObjectImport.cs @@ -65,7 +65,7 @@ internal ObjectImport(ICatalogueRepository repository, string sharingUID, IMapsD { "SharingUID", sharingUID } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } diff --git a/Rdmp.Core/Curation/Data/Remoting/RemoteRDMP.cs b/Rdmp.Core/Curation/Data/Remoting/RemoteRDMP.cs index b9dc1e7b1d..50c7128c85 100644 --- a/Rdmp.Core/Curation/Data/Remoting/RemoteRDMP.cs +++ b/Rdmp.Core/Curation/Data/Remoting/RemoteRDMP.cs @@ -106,7 +106,7 @@ public RemoteRDMP(ICatalogueRepository repository) : base() { "URL", "https://example.com" } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } diff --git a/Rdmp.Core/Curation/Data/TableInfo.cs b/Rdmp.Core/Curation/Data/TableInfo.cs index 1b9f64a9f2..048707f2c3 100644 --- a/Rdmp.Core/Curation/Data/TableInfo.cs +++ b/Rdmp.Core/Curation/Data/TableInfo.cs @@ -243,7 +243,10 @@ public int CompareTo(object obj) throw new Exception($"Cannot compare {GetType().Name} to {obj.GetType().Name}"); } - + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } /// public string GetRuntimeName() => GetQuerySyntaxHelper().GetRuntimeName(Name); @@ -505,4 +508,9 @@ public bool Is(DiscoveredTable discoveredTable, bool alsoCheckServer = false) => DatabaseType == discoveredTable.Database.Server.DatabaseType && (!alsoCheckServer || discoveredTable.Database.Server.Name.Equals(Server, StringComparison.CurrentCultureIgnoreCase)); + + public override int GetHashCode() + { + return base.GetHashCode(); + } } \ No newline at end of file diff --git a/Rdmp.Core/Curation/Data/WindowLayout.cs b/Rdmp.Core/Curation/Data/WindowLayout.cs index 4106c330ce..5575c6d7b1 100644 --- a/Rdmp.Core/Curation/Data/WindowLayout.cs +++ b/Rdmp.Core/Curation/Data/WindowLayout.cs @@ -62,7 +62,7 @@ public WindowLayout(ICatalogueRepository repository, string name, string layoutX { "LayoutData", layoutXml } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } diff --git a/Rdmp.Core/DataExport/Data/ExtractionProgress.cs b/Rdmp.Core/DataExport/Data/ExtractionProgress.cs index 7735d156c0..a0853459c3 100644 --- a/Rdmp.Core/DataExport/Data/ExtractionProgress.cs +++ b/Rdmp.Core/DataExport/Data/ExtractionProgress.cs @@ -151,7 +151,7 @@ public ExtractionProgress(IDataExportRepository repository, ISelectedDataSets sd { "Retry", RetryStrategy.NoRetry } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } @@ -176,7 +176,7 @@ public ExtractionProgress(IDataExportRepository repository, ISelectedDataSets sd { "Retry", RetryStrategy.NoRetry } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } diff --git a/Rdmp.Core/DataExport/Data/ProjectCohortIdentificationConfigurationAssociation.cs b/Rdmp.Core/DataExport/Data/ProjectCohortIdentificationConfigurationAssociation.cs index 4a462ff0ed..4e8981bb2b 100644 --- a/Rdmp.Core/DataExport/Data/ProjectCohortIdentificationConfigurationAssociation.cs +++ b/Rdmp.Core/DataExport/Data/ProjectCohortIdentificationConfigurationAssociation.cs @@ -81,7 +81,7 @@ public ProjectCohortIdentificationConfigurationAssociation(IDataExportRepository { "CohortIdentificationConfiguration_ID", cic.ID } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); ClearAllInjections(); diff --git a/Rdmp.Core/DataExport/Data/SelectedDataSetsForcedJoin.cs b/Rdmp.Core/DataExport/Data/SelectedDataSetsForcedJoin.cs index 82b779978a..860b225a4a 100644 --- a/Rdmp.Core/DataExport/Data/SelectedDataSetsForcedJoin.cs +++ b/Rdmp.Core/DataExport/Data/SelectedDataSetsForcedJoin.cs @@ -68,7 +68,7 @@ public SelectedDataSetsForcedJoin(IDataExportRepository repository, SelectedData { "TableInfo_ID", tableInfo.ID } }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); ClearAllInjections(); diff --git a/Rdmp.Core/DataExport/DataRelease/ReleaseEngine.cs b/Rdmp.Core/DataExport/DataRelease/ReleaseEngine.cs index 9034252799..9454c00e75 100644 --- a/Rdmp.Core/DataExport/DataRelease/ReleaseEngine.cs +++ b/Rdmp.Core/DataExport/DataRelease/ReleaseEngine.cs @@ -258,8 +258,7 @@ protected static IEnumerable GetAllFoldersCalled(string folderNam .Select(releasePotential => releasePotential.ExtractDirectory.Parent .EnumerateDirectories(folderName, SearchOption.TopDirectoryOnly) .SingleOrDefault()) - .Where(globalFolderForThisExtract => globalFolderForThisExtract != null) - .Select(globalFolderForThisExtract => globalFolderForThisExtract); + .Where(globalFolderForThisExtract => globalFolderForThisExtract != null); } protected static DirectoryInfo GetUniqueDirectoryFrom(List directoryInfos) diff --git a/Rdmp.Core/DataLoad/Engine/DataProvider/FromCache/ArchiveExtractor.cs b/Rdmp.Core/DataLoad/Engine/DataProvider/FromCache/ArchiveExtractor.cs index b6bc12ea57..d99c16eeba 100644 --- a/Rdmp.Core/DataLoad/Engine/DataProvider/FromCache/ArchiveExtractor.cs +++ b/Rdmp.Core/DataLoad/Engine/DataProvider/FromCache/ArchiveExtractor.cs @@ -63,8 +63,9 @@ public ZipExtractor() : base(".zip") protected override void DoExtraction(KeyValuePair job, DirectoryInfo destinationDirectory, IDataLoadEventListener dataLoadEventListener) { - var archive = new ZipArchive(new FileStream(job.Value.FullName, FileMode.Open)); - archive.ExtractToDirectory(destinationDirectory.FullName); - archive.Dispose(); + using (var archive = new ZipArchive(new FileStream(job.Value.FullName, FileMode.Open))) + { + archive.ExtractToDirectory(destinationDirectory.FullName); + } } } \ No newline at end of file diff --git a/Rdmp.Core/DataLoad/Engine/Pipeline/Components/Anonymisation/IdentifierDumper.cs b/Rdmp.Core/DataLoad/Engine/Pipeline/Components/Anonymisation/IdentifierDumper.cs index ea3738b850..fe2c5092a6 100644 --- a/Rdmp.Core/DataLoad/Engine/Pipeline/Components/Anonymisation/IdentifierDumper.cs +++ b/Rdmp.Core/DataLoad/Engine/Pipeline/Components/Anonymisation/IdentifierDumper.cs @@ -146,8 +146,7 @@ private void MergeStagingWithLive(string[] pks) con.Open(); var allColumns = - pks.Select(col => col) //get the primary keys - .Union( + pks.Union( ColumnsToRouteToSomewhereElse.Where( c => c.GoesIntoIdentifierDump()) //and the columns due to end up in the dump .Select(dump => dump.RuntimeColumnName)) diff --git a/Rdmp.Core/DataLoad/Engine/Pipeline/Sources/DbDataCommandDataFlowSource.cs b/Rdmp.Core/DataLoad/Engine/Pipeline/Sources/DbDataCommandDataFlowSource.cs index 67213043cc..168654113d 100644 --- a/Rdmp.Core/DataLoad/Engine/Pipeline/Sources/DbDataCommandDataFlowSource.cs +++ b/Rdmp.Core/DataLoad/Engine/Pipeline/Sources/DbDataCommandDataFlowSource.cs @@ -124,6 +124,7 @@ public DataTable GetChunk(IDataLoadEventListener job, GracefulCancellationToken } finally { + schema.Dispose(); _firstChunk = false; timer.Stop(); job.OnProgress(this, diff --git a/Rdmp.Core/DataLoad/Modules/DataFlowSources/ExcelDataFlowSource.cs b/Rdmp.Core/DataLoad/Modules/DataFlowSources/ExcelDataFlowSource.cs index 2e1a6f1fc5..b9b0742741 100644 --- a/Rdmp.Core/DataLoad/Modules/DataFlowSources/ExcelDataFlowSource.cs +++ b/Rdmp.Core/DataLoad/Modules/DataFlowSources/ExcelDataFlowSource.cs @@ -203,7 +203,7 @@ public DataTable GetAllData(ISheet worksheet, IDataLoadEventListener listener, i continue; //were we expecting this to be blank? - if (!nonBlankColumns.ContainsKey(cell.ColumnIndex)) + if (!nonBlankColumns.TryGetValue(cell.ColumnIndex, out _)) { listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, $"Discarded the following data (that was found in unnamed columns):{value}")); diff --git a/Rdmp.Core/DataLoad/Modules/DataProvider/FlatFileManipulation/ExcelToCSVFilesConverter.cs b/Rdmp.Core/DataLoad/Modules/DataProvider/FlatFileManipulation/ExcelToCSVFilesConverter.cs index 1b8e0a5494..b087d22c77 100644 --- a/Rdmp.Core/DataLoad/Modules/DataProvider/FlatFileManipulation/ExcelToCSVFilesConverter.cs +++ b/Rdmp.Core/DataLoad/Modules/DataProvider/FlatFileManipulation/ExcelToCSVFilesConverter.cs @@ -80,10 +80,7 @@ private void ProcessFile(FileInfo fileInfo, IDataLoadJob job) { using var fs = new FileStream(fileInfo.FullName, FileMode.Open); IWorkbook wb; - if (fileInfo.Extension == ".xls") - wb = new HSSFWorkbook(fs); - else - wb = new XSSFWorkbook(fs); + wb = fileInfo.Extension == ".xls" ? new HSSFWorkbook(fs) : new XSSFWorkbook(fs); try { diff --git a/Rdmp.Core/DataQualityEngine/Reports/DQEStateOverDataLoadRunId.cs b/Rdmp.Core/DataQualityEngine/Reports/DQEStateOverDataLoadRunId.cs index 7046a403f3..6c79a96380 100644 --- a/Rdmp.Core/DataQualityEngine/Reports/DQEStateOverDataLoadRunId.cs +++ b/Rdmp.Core/DataQualityEngine/Reports/DQEStateOverDataLoadRunId.cs @@ -56,12 +56,12 @@ public void AddKeyToDictionaries(int dataLoadRunID, Validator validator, QueryBu //column level //ensure validation failures contain it - if (!ColumnValidationFailuresByDataLoadRunID.ContainsKey(dataLoadRunID)) + if (!ColumnValidationFailuresByDataLoadRunID.TryGetValue(dataLoadRunID, out _)) ColumnValidationFailuresByDataLoadRunID.Add(dataLoadRunID, new VerboseValidationResults(validator.ItemValidators.ToArray())); //ensure unconstrained columns have it - if (!AllColumnStates.ContainsKey(dataLoadRunID)) + if (!AllColumnStates.TryGetValue(dataLoadRunID, out _)) { var allColumns = new List(); @@ -88,7 +88,7 @@ public void AddKeyToDictionaries(int dataLoadRunID, Validator validator, QueryBu //row level //ensure key exists in failing rows - if (!WorstConsequencesByDataLoadRunID.ContainsKey(dataLoadRunID)) + if (!WorstConsequencesByDataLoadRunID.TryGetValue(dataLoadRunID, out _)) { //add the data load run id key WorstConsequencesByDataLoadRunID.Add(dataLoadRunID, new Dictionary()); diff --git a/Rdmp.Core/Logging/LoggingDatabaseChecker.cs b/Rdmp.Core/Logging/LoggingDatabaseChecker.cs index 7f4eb4507d..953dceac73 100644 --- a/Rdmp.Core/Logging/LoggingDatabaseChecker.cs +++ b/Rdmp.Core/Logging/LoggingDatabaseChecker.cs @@ -20,7 +20,7 @@ namespace Rdmp.Core.Logging; /// public class LoggingDatabaseChecker : ICheckable { - private DiscoveredServer _server; + private readonly DiscoveredServer _server; public LoggingDatabaseChecker(DiscoveredServer server) @@ -179,7 +179,7 @@ private void CheckLookupTableIsCorrectlyPopulated(ICheckNotifier notifier, strin if (collisions.Any()) { notifier.OnCheckPerformed(new CheckEventArgs( - $"{tableName} there is a key collision between what we require and what is in the database, the mismatches are:{Environment.NewLine}{collisions.Aggregate("", (s, n) => $"{s}Desired:({n.Key},'{n.Value}') VS Found:({n.Key},'{actual[n.Key]}'){Environment.NewLine}")}{collisions}", + $"{tableName} there is a key collision between what we require and what is in the database, the mismatches are:{Environment.NewLine}{collisions.Aggregate("", (s, n) => $"{s}Desired:({n.Key},'{n.Value}') VS Found:({n.Key},'{actual[n.Key]}'){Environment.NewLine}")}", CheckResult.Fail, null)); return; } @@ -238,7 +238,7 @@ private static void ExpectedLookupsValuesArePresent(Dictionary expe //there is a required ID that does not exist e.g. 99,'MyFunkyStatus' - if (!actual.ContainsKey(kvp.Key)) + if (!actual.TryGetValue(kvp.Key, out _)) { missing.Add(kvp.Key, kvp.Value); continue; diff --git a/Rdmp.Core/Logging/PastEvents/ArchivalDataLoadInfo.cs b/Rdmp.Core/Logging/PastEvents/ArchivalDataLoadInfo.cs index b7a8942af8..11250ae5b5 100644 --- a/Rdmp.Core/Logging/PastEvents/ArchivalDataLoadInfo.cs +++ b/Rdmp.Core/Logging/PastEvents/ArchivalDataLoadInfo.cs @@ -108,6 +108,14 @@ public int CompareTo(object obj) return string.Compare(ToString(), obj.ToString(), StringComparison.Ordinal); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } private List GetTableInfos() { diff --git a/Rdmp.Core/Logging/PastEvents/ArchivalDataSource.cs b/Rdmp.Core/Logging/PastEvents/ArchivalDataSource.cs index 7839f2e63a..9e16f1f86c 100644 --- a/Rdmp.Core/Logging/PastEvents/ArchivalDataSource.cs +++ b/Rdmp.Core/Logging/PastEvents/ArchivalDataSource.cs @@ -63,4 +63,13 @@ public int CompareTo(object obj) return string.Compare(ToString(), obj.ToString(), StringComparison.Ordinal); } + + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } } \ No newline at end of file diff --git a/Rdmp.Core/Logging/PastEvents/ArchivalFatalError.cs b/Rdmp.Core/Logging/PastEvents/ArchivalFatalError.cs index 5dfe10e6e5..3feb414f45 100644 --- a/Rdmp.Core/Logging/PastEvents/ArchivalFatalError.cs +++ b/Rdmp.Core/Logging/PastEvents/ArchivalFatalError.cs @@ -49,6 +49,14 @@ public int CompareTo(object obj) return string.Compare(ToString(), obj.ToString(), StringComparison.Ordinal); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } public void GetSummary(out string title, out string body, out string stackTrace, out CheckResult level) { diff --git a/Rdmp.Core/Logging/PastEvents/ArchivalProgressLog.cs b/Rdmp.Core/Logging/PastEvents/ArchivalProgressLog.cs index 3fa2d3b813..3ec0f7c686 100644 --- a/Rdmp.Core/Logging/PastEvents/ArchivalProgressLog.cs +++ b/Rdmp.Core/Logging/PastEvents/ArchivalProgressLog.cs @@ -42,6 +42,15 @@ public int CompareTo(object obj) return Date == other.Date ? 0 : Date > other.Date ? 1 : -1; } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } + public void GetSummary(out string title, out string body, out string stackTrace, out CheckResult level) { level = EventType == "OnWarning" ? CheckResult.Warning : CheckResult.Success; diff --git a/Rdmp.Core/Logging/PastEvents/ArchivalTableLoadInfo.cs b/Rdmp.Core/Logging/PastEvents/ArchivalTableLoadInfo.cs index a591f3d556..2681402ce9 100644 --- a/Rdmp.Core/Logging/PastEvents/ArchivalTableLoadInfo.cs +++ b/Rdmp.Core/Logging/PastEvents/ArchivalTableLoadInfo.cs @@ -87,6 +87,15 @@ public int CompareTo(object obj) return string.Compare(ToString(), obj.ToString(), StringComparison.Ordinal); } + public override bool Equals(object obj) + { + return CompareTo(obj) == 1; + } + public override int GetHashCode() + { + return base.GetHashCode(); + } + public void GetSummary(out string title, out string body, out string stackTrace, out CheckResult level) { title = $"{TargetTable} ({Start})"; diff --git a/Rdmp.Core/Logging/TableLoadInfo.cs b/Rdmp.Core/Logging/TableLoadInfo.cs index a80491cebf..8de19ac32b 100644 --- a/Rdmp.Core/Logging/TableLoadInfo.cs +++ b/Rdmp.Core/Logging/TableLoadInfo.cs @@ -45,7 +45,9 @@ public class TableLoadInfo : ITableLoadInfo public DiscoveredServer DatabaseSettings { get; } #endregion - + /// + /// Load table info + /// /// /// Human readable text indicating how this load might be rolled back, may contain specific SQL or just general advice. /// diff --git a/Rdmp.Core/MapsDirectlyToDatabaseTable/Injection/Injection.md b/Rdmp.Core/MapsDirectlyToDatabaseTable/Injection/Injection.md index eeee84706e..c9d6f90498 100644 --- a/Rdmp.Core/MapsDirectlyToDatabaseTable/Injection/Injection.md +++ b/Rdmp.Core/MapsDirectlyToDatabaseTable/Injection/Injection.md @@ -57,7 +57,7 @@ public class AggregateTopX: DatabaseEntity {"AggregateConfiguration",config.ID} }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException("Repository failed to properly hydrate this class"); } @@ -144,7 +144,7 @@ public class AggregateTopX : DatabaseEntity, IInjectKnown(string whereSQL) where T : IMapsDirectlyToDatabaseTa var typename = Wrap(typeof(T).Name); //if there is whereSQL make sure it is a legit SQL where - if (!string.IsNullOrWhiteSpace(whereSQL)) - if (!whereSQL.Trim().ToUpper().StartsWith("WHERE")) - throw new ArgumentException($"whereSQL did not start with the word 'WHERE', it was:{whereSQL}"); + if (!string.IsNullOrWhiteSpace(whereSQL) && !whereSQL.Trim().ToUpper().StartsWith("WHERE")) + throw new ArgumentException($"whereSQL did not start with the word 'WHERE', it was:{whereSQL}"); var toReturn = new List(); @@ -382,7 +381,7 @@ public bool AreEqual(IMapsDirectlyToDatabaseTable obj1, object obj2) "Why are you comparing two null things against one another with this method?"); return obj1.GetType() == obj2.GetType() && obj1.ID == ((IMapsDirectlyToDatabaseTable)obj2).ID && - obj1.Repository == ((IMapsDirectlyToDatabaseTable)obj2).Repository; + ((IMapsDirectlyToDatabaseTable)obj1).Repository == ((IMapsDirectlyToDatabaseTable)obj2).Repository; } /// diff --git a/Rdmp.Core/Providers/CatalogueChildProvider.cs b/Rdmp.Core/Providers/CatalogueChildProvider.cs index daf3321216..773f122836 100644 --- a/Rdmp.Core/Providers/CatalogueChildProvider.cs +++ b/Rdmp.Core/Providers/CatalogueChildProvider.cs @@ -456,7 +456,7 @@ public CatalogueChildProvider(ICatalogueRepository repository, IChildProvider[] foreach (var e in AllExports) { - if (!searchables.ContainsKey(e.ReferencedObjectID)) + if (!searchables.TryGetValue(e.ReferencedObjectID, out _)) continue; var known = searchables[e.ReferencedObjectID] diff --git a/Rdmp.Core/Providers/Nodes/SingletonNode.cs b/Rdmp.Core/Providers/Nodes/SingletonNode.cs index 22ddbaeda0..d7cfa1e2eb 100644 --- a/Rdmp.Core/Providers/Nodes/SingletonNode.cs +++ b/Rdmp.Core/Providers/Nodes/SingletonNode.cs @@ -23,8 +23,8 @@ protected SingletonNode(string caption) public bool Equals(SingletonNode other) => string.Equals(_caption, other._caption); - public override bool Equals(object obj) => obj is SingletonNode sn && - Equals(sn); + public override bool Equals(object obj) => obj.GetType() == typeof(SingletonNode) && + Equals((SingletonNode)obj); public override int GetHashCode() => _caption.GetHashCode(); } \ No newline at end of file diff --git a/Rdmp.Core/QueryBuilding/QueryTimeColumn.cs b/Rdmp.Core/QueryBuilding/QueryTimeColumn.cs index 42bc7fd907..9cf225812a 100644 --- a/Rdmp.Core/QueryBuilding/QueryTimeColumn.cs +++ b/Rdmp.Core/QueryBuilding/QueryTimeColumn.cs @@ -80,10 +80,10 @@ public QueryTimeColumn(IColumn column) /// public override bool Equals(object obj) { - if (obj is QueryTimeColumn == false) + if (obj.GetType() != typeof(QueryTimeColumn)) throw new Exception(".Equals only works for objects of type QueryTimeColumn"); - var other = obj as QueryTimeColumn; + var other = (QueryTimeColumn)obj; return other.IColumn.Equals(IColumn); } diff --git a/Rdmp.Core/ReusableLibraryCode/AssemblyResolver.cs b/Rdmp.Core/ReusableLibraryCode/AssemblyResolver.cs index 2bb0d9b45d..22c3ee480f 100644 --- a/Rdmp.Core/ReusableLibraryCode/AssemblyResolver.cs +++ b/Rdmp.Core/ReusableLibraryCode/AssemblyResolver.cs @@ -35,11 +35,9 @@ public static void SetupAssemblyResolver(params DirectoryInfo[] dirs) //start out assuming we cannot load it assemblyResolveAttempts.Add(assemblyInfo, null); - foreach (var dir in dirs) + foreach (var dll in dirs.Select(dir => dir.EnumerateFiles($"{name}.dll").SingleOrDefault()).Where(dll => dll != null)) { - var dll = dir.EnumerateFiles($"{name}.dll").SingleOrDefault(); - if (dll != null) - return assemblyResolveAttempts[assemblyInfo] = LoadFile(dll); //cache and return answer + return assemblyResolveAttempts[assemblyInfo] = LoadFile(dll); //cache and return answer } var assembly = AppContext.BaseDirectory; diff --git a/Rdmp.Core/ReusableLibraryCode/Comments/CommentStore.cs b/Rdmp.Core/ReusableLibraryCode/Comments/CommentStore.cs index 8db6611acb..105180d0e7 100644 --- a/Rdmp.Core/ReusableLibraryCode/Comments/CommentStore.cs +++ b/Rdmp.Core/ReusableLibraryCode/Comments/CommentStore.cs @@ -41,10 +41,8 @@ public class CommentStore : IEnumerable> public virtual void ReadComments(params string[] locations) { - foreach (var location in locations) + foreach (var location in locations.Where(l => l is not null)) { - if (location is null) - continue; if (Directory.Exists(location)) foreach (var xml in Directory.EnumerateFiles(location, "*.xml", SearchOption.AllDirectories)) using (var content = File.OpenRead(xml)) diff --git a/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/DocumentationCrossExaminationTest.cs b/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/DocumentationCrossExaminationTest.cs index 0c116136cd..e77f318adb 100644 --- a/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/DocumentationCrossExaminationTest.cs +++ b/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/DocumentationCrossExaminationTest.cs @@ -351,8 +351,8 @@ public void FindProblems(List csFilesFound) var fileContents = File.ReadAllText(mdFile); foreach (Match m in MatchMdReferences.Matches(fileContents)) - foreach (Match word in Regex.Matches(m.Groups[1].Value, @"([A-Z]\w+){2,}")) - fileCommentTokens[mdFile].Add(word.Value); + foreach (Match word in Regex.Matches(m.Groups[1].Value, @"([A-Z]\w+){2,}")) + fileCommentTokens[mdFile].Add(word.Value); EnsureMaximumGlossaryUse(mdFile, problems); diff --git a/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/SuspiciousRelationshipPropertyUse.cs b/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/SuspiciousRelationshipPropertyUse.cs index 48f936f092..3d841833d2 100644 --- a/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/SuspiciousRelationshipPropertyUse.cs +++ b/Rdmp.UI.Tests/DesignPatternTests/ClassFileEvaluation/SuspiciousRelationshipPropertyUse.cs @@ -159,27 +159,6 @@ public void FindPropertyMisuse(List csFilesFound) suggestedMethodWrappers += $"\tset => SetField(ref {fieldName},value);{Environment.NewLine}"; suggestedMethodWrappers += $"}}{Environment.NewLine}"; } - - if (!setMethod.IsAbstract) - { - /*var instructions = setMethod.GetInstructions(); - - bool foundINotify = false; - - foreach (Instruction instruction in instructions) - { - MethodInfo methodInfo = instruction.Operand as MethodInfo; - - if (methodInfo != null) - if (methodInfo.Name.Equals("SetField") || methodInfo.Name.Equals("OnPropertyChanged")) - foundINotify = true; - } - - if(!foundINotify) - _fails.Add("FAIL:Set Method for property " + p.Name + " on Type " + type.Name + " does not include an Instruction calling method 'SetField' or 'OnPropertyChanged'"); - - */ - } } diff --git a/Rdmp.UI.Tests/UITests.cs b/Rdmp.UI.Tests/UITests.cs index 9e53bbc488..18c20c5292 100644 --- a/Rdmp.UI.Tests/UITests.cs +++ b/Rdmp.UI.Tests/UITests.cs @@ -349,36 +349,39 @@ protected void ForEachUI(Action action) foreach (var o in objectsToTest) //foreach compatible UI - foreach (var uiType in uiTypes.Where(a => a.BaseType.BaseType.GetGenericArguments()[0] == o.GetType())) - { - //todo - var methodAndLaunch = methods.Single(m => - m.Name.Equals("AndLaunch") && m.GetParameters().Length >= 1 && - m.GetParameters()[0].ParameterType == typeof(DatabaseEntity)); + foreach (var uiType in uiTypes.Where(a => a.BaseType.BaseType.GetGenericArguments()[0] == o.GetType())) + { + //todo + var methodAndLaunch = methods.Single(m => + m.Name.Equals("AndLaunch") && m.GetParameters().Length >= 1 && + m.GetParameters()[0].ParameterType == typeof(DatabaseEntity)); - //ensure that the method supports the Type - var genericAndLaunch = methodAndLaunch.MakeGenericMethod(uiType); + //ensure that the method supports the Type + var genericAndLaunch = methodAndLaunch.MakeGenericMethod(uiType); - IRDMPSingleDatabaseObjectControl ui; + IRDMPSingleDatabaseObjectControl ui; - try - { - ui = (IRDMPSingleDatabaseObjectControl)genericAndLaunch.Invoke(this, new object[] { o, true }); + try + { + ui = (IRDMPSingleDatabaseObjectControl)genericAndLaunch.Invoke(this, new object[] { o, true }); - if (ui is IDisposable d) - d.Dispose(); - } - catch (Exception ex) - { - throw new Exception( - $"Failed to construct '{uiType}'. Code to reproduce is:{Environment.NewLine}{ShowCode(o.GetType(), uiType)}", - ex); - } + if (ui is IDisposable d) + d.Dispose(); + } + catch (Exception ex) + { + throw new Exception( + $"Failed to construct '{uiType}'. Code to reproduce is:{Environment.NewLine}{ShowCode(o.GetType(), uiType)}", + ex); + } + finally + { + } - action(ui); - ClearResults(); - } + action(ui); + ClearResults(); + } } private static string ShowCode(Type t, Type uiType) diff --git a/Rdmp.UI/AggregationUIs/Advanced/AggregateEditorUI.cs b/Rdmp.UI/AggregationUIs/Advanced/AggregateEditorUI.cs index 4805116258..2d32d8dcc6 100644 --- a/Rdmp.UI/AggregationUIs/Advanced/AggregateEditorUI.cs +++ b/Rdmp.UI/AggregationUIs/Advanced/AggregateEditorUI.cs @@ -353,7 +353,7 @@ private void btnClearPivotDimension_Click(object sender, EventArgs e) _aggregate.PivotOnDimensionID = null; ddPivotDimension.SelectedItem = null; - if (sender != btnClearPivotDimension) return; + if (sender.GetType() != typeof(Button) && (Button)sender != btnClearPivotDimension) return; _aggregate.SaveToDatabase(); Publish(); diff --git a/Rdmp.UI/ChecksUI/ChecksUI.cs b/Rdmp.UI/ChecksUI/ChecksUI.cs index 6762b1490e..430e30a48a 100644 --- a/Rdmp.UI/ChecksUI/ChecksUI.cs +++ b/Rdmp.UI/ChecksUI/ChecksUI.cs @@ -249,9 +249,7 @@ private void olvChecks_ItemActivate(object sender, EventArgs e) public void TerminateWithExtremePrejudice() { if (_checkingThread is { IsAlive: true }) -#pragma warning disable SYSLIB0006 // Type or member is obsolete - _checkingThread.Abort(); -#pragma warning restore SYSLIB0006 // Type or member is obsolete + _checkingThread.Interrupt(); btnAbortChecking.Enabled = false; } diff --git a/Rdmp.UI/Collections/Providers/FavouriteColumnProvider.cs b/Rdmp.UI/Collections/Providers/FavouriteColumnProvider.cs index 09b4340672..e1cd54c68d 100644 --- a/Rdmp.UI/Collections/Providers/FavouriteColumnProvider.cs +++ b/Rdmp.UI/Collections/Providers/FavouriteColumnProvider.cs @@ -77,6 +77,7 @@ private void OnCellClick(object sender, CellClickEventArgs cellClickEventArgs) } catch (ArgumentException) { + Console.WriteLine("Unable to refresh favourite column"); } } } diff --git a/Rdmp.UI/DataLoadUIs/LoadMetadataUIs/ProcessTasks/SqlProcessTaskUI.cs b/Rdmp.UI/DataLoadUIs/LoadMetadataUIs/ProcessTasks/SqlProcessTaskUI.cs index f4d43b3089..439bbe2626 100644 --- a/Rdmp.UI/DataLoadUIs/LoadMetadataUIs/ProcessTasks/SqlProcessTaskUI.cs +++ b/Rdmp.UI/DataLoadUIs/LoadMetadataUIs/ProcessTasks/SqlProcessTaskUI.cs @@ -135,7 +135,7 @@ private void ScintillaOnSavePointLeft(object sender, EventArgs eventArgs) private void btnBrowse_Click(object sender, EventArgs e) { - var ofd = new OpenFileDialog + using var ofd = new OpenFileDialog { Filter = _processTask.ProcessTaskType == ProcessTaskType.SQLBakFile ? "BAK Files |*.bak" : "Sql Files|*.sql", CheckFileExists = true diff --git a/Rdmp.UI/Logging/LoggingTabUI.cs b/Rdmp.UI/Logging/LoggingTabUI.cs index 628a5487d9..fbc17ad627 100644 --- a/Rdmp.UI/Logging/LoggingTabUI.cs +++ b/Rdmp.UI/Logging/LoggingTabUI.cs @@ -170,9 +170,11 @@ private IEnumerable GetCommands(int rowIdnex) private static void AddFreeTextSearchColumn(DataTable dt) { var dcRowString = dt.Columns.Add("_RowString", typeof(string)); + var sb = new StringBuilder(); + foreach (DataRow dataRow in dt.Rows) { - var sb = new StringBuilder(); + sb.Clear(); for (var i = 0; i < dt.Columns.Count - 1; i++) { sb.Append(dataRow[i]); diff --git a/Rdmp.UI/Overview/DataLoadsGraph.cs b/Rdmp.UI/Overview/DataLoadsGraph.cs index b901c24641..c1e1ad7f27 100644 --- a/Rdmp.UI/Overview/DataLoadsGraph.cs +++ b/Rdmp.UI/Overview/DataLoadsGraph.cs @@ -203,7 +203,7 @@ public void RefreshChartAsync() return; } - var dt = new DataTable(); + using var dt = new DataTable(); dt.Columns.Add("Category"); dt.Columns.Add("NumberOfDataLoadsAtStatus"); diff --git a/Rdmp.UI/PluginManagement/CodeGeneration/MapsDirectlyToDatabaseTableClassCodeGenerator.cs b/Rdmp.UI/PluginManagement/CodeGeneration/MapsDirectlyToDatabaseTableClassCodeGenerator.cs index 96c8a5e35f..e158171d99 100644 --- a/Rdmp.UI/PluginManagement/CodeGeneration/MapsDirectlyToDatabaseTableClassCodeGenerator.cs +++ b/Rdmp.UI/PluginManagement/CodeGeneration/MapsDirectlyToDatabaseTableClassCodeGenerator.cs @@ -59,7 +59,7 @@ public string GetCode() //TODO Any parameters here as key value pairs }); - if (ID == 0 || Repository != repository) + if (ID == 0 || !repository.Equals(Repository)) throw new ArgumentException(""Repository failed to properly hydrate this class""); }"); diff --git a/Rdmp.UI/SimpleControls/RainbowColorPicker.cs b/Rdmp.UI/SimpleControls/RainbowColorPicker.cs index d936fbafe6..d1e6dbe0c2 100644 --- a/Rdmp.UI/SimpleControls/RainbowColorPicker.cs +++ b/Rdmp.UI/SimpleControls/RainbowColorPicker.cs @@ -56,19 +56,20 @@ private List interpolateColors(List stopColors, int count) using var bmp = new Bitmap(count, 1); using var G = Graphics.FromImage(bmp); var bmpCRect = new Rectangle(Point.Empty, bmp.Size); - var br = new LinearGradientBrush - (bmpCRect, Color.Empty, Color.Empty, 0, false); - var cb = new ColorBlend + using (var br = new LinearGradientBrush + (bmpCRect, Color.Empty, Color.Empty, 0, false)) { - Positions = new float[gradient.Count] - }; - for (var i = 0; i < gradient.Count; i++) - cb.Positions[i] = gradient.ElementAt(i).Key; - cb.Colors = gradient.Values.ToArray(); - br.InterpolationColors = cb; - G.FillRectangle(br, bmpCRect); - for (var i = 0; i < count; i++) ColorList.Add(bmp.GetPixel(i, 0)); - br.Dispose(); + var cb = new ColorBlend + { + Positions = new float[gradient.Count] + }; + for (var i = 0; i < gradient.Count; i++) + cb.Positions[i] = gradient.ElementAt(i).Key; + cb.Colors = gradient.Values.ToArray(); + br.InterpolationColors = cb; + G.FillRectangle(br, bmpCRect); + for (var i = 0; i < count; i++) ColorList.Add(bmp.GetPixel(i, 0)); + } return ColorList; } } \ No newline at end of file diff --git a/Rdmp.UI/SimpleDialogs/NavigateTo/RunUI.cs b/Rdmp.UI/SimpleDialogs/NavigateTo/RunUI.cs index 0c7409a95d..98102d939a 100644 --- a/Rdmp.UI/SimpleDialogs/NavigateTo/RunUI.cs +++ b/Rdmp.UI/SimpleDialogs/NavigateTo/RunUI.cs @@ -66,6 +66,7 @@ private void comboBox1_KeyUp(object sender, KeyEventArgs e) } catch (OperationCanceledException) { + Console.WriteLine("Operation Cancelled"); } catch (Exception ex) { diff --git a/Rdmp.UI/SimpleDialogs/SelectDialog.cs b/Rdmp.UI/SimpleDialogs/SelectDialog.cs index cb612ebb27..8bf562e505 100644 --- a/Rdmp.UI/SimpleDialogs/SelectDialog.cs +++ b/Rdmp.UI/SimpleDialogs/SelectDialog.cs @@ -656,6 +656,7 @@ private void tbFilter_TextChanged(object sender, EventArgs e) } catch (ObjectDisposedException) { + Console.WriteLine("Object already disposed"); } }, TaskScheduler.FromCurrentSynchronizationContext()); } diff --git a/Rdmp.UI/TestsAndSetup/StartupUI.cs b/Rdmp.UI/TestsAndSetup/StartupUI.cs index e8e89b4073..879a43ddcb 100644 --- a/Rdmp.UI/TestsAndSetup/StartupUI.cs +++ b/Rdmp.UI/TestsAndSetup/StartupUI.cs @@ -343,9 +343,8 @@ private void StartupUIMainForm_FormClosing(object sender, FormClosingEventArgs e if (_choosePlatformsUI is { ChangesMade: true }) DoNotContinue = true; - if (e.CloseReason == CloseReason.UserClosing) - if (ragSmiley1.IsFatal()) - DoNotContinue = true; + if (e.CloseReason == CloseReason.UserClosing && ragSmiley1.IsFatal()) + DoNotContinue = true; } private void BtnChoosePlatformDatabases_Click(object sender, EventArgs e) diff --git a/Tools/rdmp/CommandLine/Gui/ConsoleGuiBigListBox.cs b/Tools/rdmp/CommandLine/Gui/ConsoleGuiBigListBox.cs index 4586d0005c..f424bcc3f9 100644 --- a/Tools/rdmp/CommandLine/Gui/ConsoleGuiBigListBox.cs +++ b/Tools/rdmp/CommandLine/Gui/ConsoleGuiBigListBox.cs @@ -96,7 +96,7 @@ public ListViewObject(T2 o, Func displayFunc) public override int GetHashCode() => Object.GetHashCode(); - public override bool Equals(object obj) => obj is ListViewObject other && Object.Equals(other.Object); + public override bool Equals(object obj) => obj.GetType() == typeof(ListViewObject) && Object.Equals(((ListViewObject)obj).Object); } ///