diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..f8ef5767 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,226 @@ +root = true + +[*] +end_of_line = crlf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 200 +tab_width = 4 +trim_trailing_whitespace = true +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = true +ij_smart_tabs = false +ij_wrap_on_typing = true + +[.editorconfig] +ij_editorconfig_align_group_field_declarations = false +ij_editorconfig_space_after_colon = false +ij_editorconfig_space_after_comma = true +ij_editorconfig_space_before_colon = false +ij_editorconfig_space_before_comma = false +ij_editorconfig_spaces_around_assignment_operators = true + +[{*.yaml,*.yml}] +indent_size = 2 +ij_yaml_align_values_properties = do_not_align +ij_yaml_autoinsert_sequence_marker = true +ij_yaml_block_mapping_on_new_line = false +ij_yaml_indent_sequence_value = true +ij_yaml_keep_indents_on_empty_lines = false +ij_yaml_keep_line_breaks = true +ij_yaml_line_comment_add_space = false +ij_yaml_line_comment_add_space_on_reformat = false +ij_yaml_line_comment_at_first_column = true +ij_yaml_sequence_on_new_line = false +ij_yaml_space_before_colon = false +ij_yaml_spaces_within_braces = true +ij_yaml_spaces_within_brackets = true + + +############################### +# C# Coding Conventions # +############################### + +[*.cs] +# Organize usings +dotnet_sort_system_directives_first = true +csharp_style_namespace_declarations = file_scoped:suggestion + +# this. preferences +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = true:error +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:error +dotnet_style_predefined_type_for_member_access = true:error + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:error +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:error +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:error +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:error + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:error +dotnet_style_readonly_field = true:error + +# Expression-level preferences +dotnet_style_object_initializer = true:error +dotnet_style_collection_initializer = true:error +dotnet_style_explicit_tuple_names = true:error +dotnet_style_null_propagation = true:error +dotnet_style_coalesce_expression = true:error +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error +dotnet_style_prefer_inferred_tuple_names = true:error +dotnet_style_prefer_inferred_anonymous_type_member_names = true:error +dotnet_style_prefer_auto_properties = true:error +dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion +dotnet_style_prefer_conditional_expression_over_return = false:suggestion + + +############################### +# Naming Conventions # +############################### + +# Style Definitions +dotnet_naming_style.pascal_case_style.capitalization = pascal_case +# Use PascalCase for constant fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.applicable_accessibilities = * +dotnet_naming_symbols.constant_fields.required_modifiers = const + +# var preferences +csharp_style_var_for_built_in_types = true:error +csharp_style_var_when_type_is_apparent = true:error +csharp_style_var_elsewhere = true:error + +# Expression-bodied members +csharp_style_expression_bodied_methods = false:error +csharp_style_expression_bodied_constructors = false:error +csharp_style_expression_bodied_operators = false:error +csharp_style_expression_bodied_properties = true:error +csharp_style_expression_bodied_indexers = true:error +csharp_style_expression_bodied_accessors = true:error + +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:error +csharp_style_pattern_matching_over_as_with_null_check = true:error + +# Null-checking preferences +csharp_style_throw_expression = true:error +csharp_style_conditional_delegate_call = true:error + +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:error + +# Expression-level preferences +csharp_prefer_braces = true:error +csharp_style_deconstructed_variable_declaration = true:error +csharp_prefer_simple_default_expression = true:error +csharp_style_pattern_local_over_anonymous_function = true:error +csharp_style_inlined_variable_declaration = true:error + +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false + +# Wrapping preferences +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true + + +# Other settings exported from Rider +dotnet_naming_rule.interfaces_rule.import_to_resharper = True +dotnet_naming_rule.interfaces_rule.resharper_description = Interfaces +dotnet_naming_rule.interfaces_rule.resharper_guid = a7a3339e-4e89-4319-9735-a9dc4cb74cc7 +dotnet_naming_rule.interfaces_rule.severity = error +dotnet_naming_rule.interfaces_rule.style = i_upper_camel_case_style +dotnet_naming_rule.interfaces_rule.symbols = interfaces_symbols +dotnet_naming_rule.private_constants_rule.import_to_resharper = True +dotnet_naming_rule.private_constants_rule.resharper_description = Constant fields (private) +dotnet_naming_rule.private_constants_rule.resharper_guid = 236f7aa5-7b06-43ca-bf2a-9b31bfcff09a +dotnet_naming_rule.private_constants_rule.severity = error +dotnet_naming_rule.private_constants_rule.style = upper_camel_case_style +dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols +dotnet_naming_rule.private_instance_fields_rule.import_to_resharper = True +dotnet_naming_rule.private_instance_fields_rule.resharper_description = Instance fields (private) +dotnet_naming_rule.private_instance_fields_rule.resharper_guid = 4a98fdf6-7d98-4f5a-afeb-ea44ad98c70c +dotnet_naming_rule.private_instance_fields_rule.severity = error +dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style +dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols +dotnet_naming_rule.private_static_fields_rule.import_to_resharper = True +dotnet_naming_rule.private_static_fields_rule.resharper_description = Static fields (private) +dotnet_naming_rule.private_static_fields_rule.resharper_guid = f9fce829-e6f4-4cb2-80f1-5497c44f51df +dotnet_naming_rule.private_static_fields_rule.severity = error +dotnet_naming_rule.private_static_fields_rule.style = upper_camel_case_style +dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols +dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = True +dotnet_naming_rule.private_static_readonly_rule.resharper_description = Static readonly fields (private) +dotnet_naming_rule.private_static_readonly_rule.resharper_guid = 15b5b1f1-457c-4ca6-b278-5615aedc07d3 +dotnet_naming_rule.private_static_readonly_rule.resharper_style = AaBb, id + AaBb +dotnet_naming_rule.private_static_readonly_rule.severity = error +dotnet_naming_rule.private_static_readonly_rule.style = upper_camel_case_style +dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols +dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True +dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field +dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef +dotnet_naming_style.i_upper_camel_case_style.capitalization = pascal_case +dotnet_naming_style.i_upper_camel_case_style.required_prefix = I +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case +dotnet_naming_symbols.interfaces_symbols.applicable_accessibilities = * +dotnet_naming_symbols.interfaces_symbols.applicable_kinds = interface +dotnet_naming_symbols.interfaces_symbols.resharper_applicable_kinds = interface +dotnet_naming_symbols.interfaces_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field +dotnet_naming_symbols.private_constants_symbols.required_modifiers = const +dotnet_naming_symbols.private_constants_symbols.resharper_applicable_kinds = constant_field +dotnet_naming_symbols.private_constants_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_instance_fields_symbols.resharper_applicable_kinds = field, readonly_field +dotnet_naming_symbols.private_instance_fields_symbols.resharper_required_modifiers = instance +dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static +dotnet_naming_symbols.private_static_fields_symbols.resharper_applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.resharper_required_modifiers = static +dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = readonly, static +dotnet_naming_symbols.private_static_readonly_symbols.resharper_applicable_kinds = readonly_field +dotnet_naming_symbols.private_static_readonly_symbols.resharper_required_modifiers = static + + diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 87670d3b..2f17d060 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -1,36 +1,3 @@ -# This workflow will build, test, sign and package a WPF or Windows Forms desktop application -# built on .NET Core. -# To learn how to migrate your existing application to .NET Core, -# refer to https://docs.microsoft.com/en-us/dotnet/desktop-wpf/migration/convert-project-from-net-framework -# -# To configure this workflow: -# -# 1. Configure environment variables -# GitHub sets default environment variables for every workflow run. -# Replace the variables relative to your project in the "env" section below. -# -# 2. Signing -# Generate a signing certificate in the Windows Application -# Packaging Project or add an existing signing certificate to the project. -# Next, use PowerShell to encode the .pfx file using Base64 encoding -# by running the following Powershell script to generate the output string: -# -# $pfx_cert = Get-Content '.\SigningCertificate.pfx' -Encoding Byte -# [System.Convert]::ToBase64String($pfx_cert) | Out-File 'SigningCertificate_Encoded.txt' -# -# Open the output file, SigningCertificate_Encoded.txt, and copy the -# string inside. Then, add the string to the repo as a GitHub secret -# and name it "Base64_Encoded_Pfx." -# For more information on how to configure your signing certificate for -# this workflow, refer to https://github.com/microsoft/github-actions-for-desktop-apps#signing -# -# Finally, add the signing certificate password to the repo as a secret and name it "Pfx_Key". -# See "Build the Windows Application Packaging project" below to see how the secret is used. -# -# For more information on GitHub Actions, refer to https://github.com/features/actions -# For a complete CI/CD sample to get started with GitHub Action workflows for Desktop Applications, -# refer to https://github.com/microsoft/github-actions-for-desktop-apps - name: .NET Core Desktop Build and Test on: @@ -47,7 +14,7 @@ jobs: # https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on env: - Solution_Name: BudgetAnalyser.sln # Replace with your solution name, i.e. MyWpfApp.sln. + Solution_Name: BudgetAnalyser.sln steps: - name: Checkout @@ -55,6 +22,16 @@ jobs: with: fetch-depth: 0 + - name: Cache .NET packages + uses: actions/cache@v3 + with: + path: | + ~/.nuget/packages + ~/.local/share/NuGet/Cache + key: ${{ runner.os }}-nuget-${{ hashFiles('**/obj/project.assets.json') }} + restore-keys: | + ${{ runner.os }}-nuget- + # Install the .NET Core workload - name: Install .NET Core uses: actions/setup-dotnet@v4 @@ -65,9 +42,12 @@ jobs: run: dotnet restore - name: Build - run: dotnet build --no-restore --configuration Debug - + run: dotnet build --no-restore --verbosity quiet --configuration Debug + # Execute all unit tests in the solution - name: Run unit tests run: dotnet test --no-build --verbosity minimal --configuration Debug + - name: Validate code style + run: dotnet format --no-restore --verify-no-changes --verbosity minimal + diff --git a/BudgetAnalyser.Encryption/EncryptedLocalDiskReaderWriter.cs b/BudgetAnalyser.Encryption/EncryptedLocalDiskReaderWriter.cs index 6eaf13b6..c23baca7 100644 --- a/BudgetAnalyser.Encryption/EncryptedLocalDiskReaderWriter.cs +++ b/BudgetAnalyser.Encryption/EncryptedLocalDiskReaderWriter.cs @@ -18,8 +18,16 @@ internal class EncryptedLocalDiskReaderWriter : IFileReaderWriter public EncryptedLocalDiskReaderWriter([NotNull] IFileEncryptor fileEncryptor, [NotNull] ICredentialStore credentialStore) { - if (fileEncryptor is null) throw new ArgumentNullException(nameof(fileEncryptor)); - if (credentialStore is null) throw new ArgumentNullException(nameof(credentialStore)); + if (fileEncryptor is null) + { + throw new ArgumentNullException(nameof(fileEncryptor)); + } + + if (credentialStore is null) + { + throw new ArgumentNullException(nameof(credentialStore)); + } + this.fileEncryptor = fileEncryptor; this.credentialStore = credentialStore; } @@ -44,16 +52,17 @@ public bool FileExists(string fileName) /// Full path and filename of the file. public async Task LoadFromDiskAsync(string fileName) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); - var password = RetrievePassword(); - var decryptedData = await this.fileEncryptor.LoadEncryptedFileAsync(fileName, password); - - if (IsValidAlphaNumericWithPunctuation(decryptedData)) + if (fileName.IsNothing()) { - return decryptedData; + throw new ArgumentNullException(nameof(fileName)); } - throw new EncryptionKeyIncorrectException("The provided encryption credential did not result in a valid decryption result."); + var password = RetrievePassword(); + var decryptedData = await this.fileEncryptor.LoadEncryptedFileAsync(fileName, password); + + return IsValidAlphaNumericWithPunctuation(decryptedData) + ? decryptedData + : throw new EncryptionKeyIncorrectException("The provided encryption credential did not result in a valid decryption result."); } /// @@ -63,14 +72,15 @@ public async Task LoadFromDiskAsync(string fileName) /// The number of lines to load. public async Task LoadFirstLinesFromDiskAsync(string fileName, int lineCount) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); - var decryptedData = await this.fileEncryptor.LoadFirstLinesFromDiskAsync(fileName, lineCount, RetrievePassword()); - if (IsValidAlphaNumericWithPunctuation(decryptedData)) + if (fileName.IsNothing()) { - return decryptedData; + throw new ArgumentNullException(nameof(fileName)); } - throw new EncryptionKeyIncorrectException("The provided encryption credential did not result in a valid decryption result."); + var decryptedData = await this.fileEncryptor.LoadFirstLinesFromDiskAsync(fileName, lineCount, RetrievePassword()); + return IsValidAlphaNumericWithPunctuation(decryptedData) + ? decryptedData + : throw new EncryptionKeyIncorrectException("The provided encryption credential did not result in a valid decryption result."); } /// @@ -78,8 +88,15 @@ public async Task LoadFirstLinesFromDiskAsync(string fileName, int lineC /// public async Task WriteToDiskAsync(string fileName, string data) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); - if (data.IsNothing()) throw new ArgumentNullException(nameof(data)); + if (fileName.IsNothing()) + { + throw new ArgumentNullException(nameof(fileName)); + } + + if (data.IsNothing()) + { + throw new ArgumentNullException(nameof(data)); + } var password = RetrievePassword(); await this.fileEncryptor.SaveStringDataToEncryptedFileAsync(fileName, data, password); @@ -87,7 +104,11 @@ public async Task WriteToDiskAsync(string fileName, string data) internal bool IsValidAlphaNumericWithPunctuation(string text) { - if (text is null) return false; + if (text is null) + { + return false; + } + var valid = text.ToCharArray().Take(16).All(IsValidUtf8AlphaNumericWithPunctuation); return valid; } @@ -103,9 +124,7 @@ private bool IsValidUtf8AlphaNumericWithPunctuation(char c) private SecureString RetrievePassword() { - var password = this.credentialStore.RetrievePasskey() as SecureString; - - if (password is null) + if (this.credentialStore.RetrievePasskey() is not SecureString password) { // This condition should be checked by the UI before calling into the Engine ideally. throw new EncryptionKeyNotProvidedException("Attempt to load an encrypted password protected file and no password has been set."); @@ -114,4 +133,4 @@ private SecureString RetrievePassword() return password; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Encryption/FileEncryptor.cs b/BudgetAnalyser.Encryption/FileEncryptor.cs index 87546b51..245896c5 100644 --- a/BudgetAnalyser.Encryption/FileEncryptor.cs +++ b/BudgetAnalyser.Encryption/FileEncryptor.cs @@ -21,9 +21,20 @@ public Stream CreateWritableEncryptedStream(string fileName, SecureString passph public async Task EncryptFileAsync(string sourceFile, string destinationFile, SecureString passphrase) { - if (sourceFile.IsNothing()) throw new ArgumentNullException(nameof(sourceFile)); - if (destinationFile.IsNothing()) throw new ArgumentNullException(nameof(destinationFile)); - if (passphrase is null) throw new ArgumentNullException(nameof(passphrase)); + if (sourceFile.IsNothing()) + { + throw new ArgumentNullException(nameof(sourceFile)); + } + + if (destinationFile.IsNothing()) + { + throw new ArgumentNullException(nameof(destinationFile)); + } + + if (passphrase is null) + { + throw new ArgumentNullException(nameof(passphrase)); + } if (!FileExists(sourceFile)) { @@ -52,7 +63,10 @@ public async Task LoadFirstLinesFromDiskAsync(string fileName, int lineC await outputStream.WriteAsync(buffer, 0, 4096); var chunk = Encoding.UTF8.GetChars(buffer); var occurrences = chunk.Count(c => c == '\n'); - if (occurrences >= lineCount) break; + if (occurrences >= lineCount) + { + break; + } } } @@ -72,4 +86,4 @@ protected virtual bool FileExists(string fileName) { return File.Exists(fileName); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Encryption/GlobalSuppressions.cs b/BudgetAnalyser.Encryption/GlobalSuppressions.cs index 1ea98ac0..9f008e64 100644 Binary files a/BudgetAnalyser.Encryption/GlobalSuppressions.cs and b/BudgetAnalyser.Encryption/GlobalSuppressions.cs differ diff --git a/BudgetAnalyser.Encryption/IFileEncryptor.cs b/BudgetAnalyser.Encryption/IFileEncryptor.cs index 741ac8a4..8752360c 100644 --- a/BudgetAnalyser.Encryption/IFileEncryptor.cs +++ b/BudgetAnalyser.Encryption/IFileEncryptor.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Security; using System.Threading.Tasks; using JetBrains.Annotations; @@ -52,4 +52,4 @@ public interface IFileEncryptor /// The pass phrase. Task SaveStringDataToEncryptedFileAsync([NotNull] string fileName, [NotNull] string data, [NotNull] SecureString passphrase); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Encryption/LocalDiskReaderWriterSelector.cs b/BudgetAnalyser.Encryption/LocalDiskReaderWriterSelector.cs index 7c33362c..98e5f949 100644 --- a/BudgetAnalyser.Encryption/LocalDiskReaderWriterSelector.cs +++ b/BudgetAnalyser.Encryption/LocalDiskReaderWriterSelector.cs @@ -15,7 +15,10 @@ internal class LocalDiskReaderWriterSelector : IReaderWriterSelector public LocalDiskReaderWriterSelector([NotNull] IEnumerable allReaderWriters) { - if (allReaderWriters is null) throw new ArgumentNullException(nameof(allReaderWriters)); + if (allReaderWriters is null) + { + throw new ArgumentNullException(nameof(allReaderWriters)); + } var fileReaderWriters = allReaderWriters.ToList(); this.encryptedReaderWriter = DefaultIoCRegistrations.GetNamedInstance(fileReaderWriters, StorageConstants.EncryptedInstanceName); @@ -35,14 +38,11 @@ public IFileReaderWriter SelectReaderWriter(bool isEncrypted) throw new InvalidOperationException("Code Bug: There are no instances of IFileReaderWriter registered."); } - var readerWriter = (isEncrypted ? this.encryptedReaderWriter : this.unprotectedRaderWriter); - - if (readerWriter is null) - { - throw new InvalidOperationException("Code Bug: There are no instances of IFileReaderWriter registered for the selected encryption mode. " + isEncrypted); - } + var readerWriter = isEncrypted ? this.encryptedReaderWriter : this.unprotectedRaderWriter; - return readerWriter; + return readerWriter is null + ? throw new InvalidOperationException("Code Bug: There are no instances of IFileReaderWriter registered for the selected encryption mode. " + isEncrypted) + : readerWriter; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Encryption/SecureStringCredentialStore.cs b/BudgetAnalyser.Encryption/SecureStringCredentialStore.cs index ba30c19c..2318a379 100644 --- a/BudgetAnalyser.Encryption/SecureStringCredentialStore.cs +++ b/BudgetAnalyser.Encryption/SecureStringCredentialStore.cs @@ -20,8 +20,7 @@ internal sealed class SecureStringCredentialStore : ICredentialStore, IDisposabl /// A credential object or null if no credentials have been provided by the user. public object RetrievePasskey() { - if (this.passPhrase is null || this.passPhrase.Length == 0) return null; - return this.passPhrase; + return this.passPhrase is null || this.passPhrase.Length == 0 ? null : (object)this.passPhrase; } /// @@ -30,7 +29,7 @@ public object RetrievePasskey() public void SetPasskey(object passkey) { this.passPhrase?.Dispose(); - this.passPhrase = (SecureString) passkey; + this.passPhrase = (SecureString)passkey; } /// @@ -73,8 +72,7 @@ public bool AreEqual(object compareTo) } var key1 = this.passPhrase; - var key2 = compareTo as SecureString; - if (key2 is null) + if (compareTo is not SecureString key2) { throw new NotSupportedException($"{nameof(SecureStringCredentialStore)} only supports use of SecureStrings."); } @@ -96,7 +94,7 @@ public bool AreEqual(object compareTo) unsafe { - for (char* ptr1 = (char*) bstr1.ToPointer(), ptr2 = (char*) bstr2.ToPointer(); + for (char* ptr1 = (char*)bstr1.ToPointer(), ptr2 = (char*)bstr2.ToPointer(); *ptr1 != 0 && *ptr2 != 0; ++ptr1, ++ptr2) { @@ -153,4 +151,4 @@ internal static string SecureStringToString(SecureString value) Dispose(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/.editorconfig b/BudgetAnalyser.Engine.UnitTest/.editorconfig new file mode 100644 index 00000000..e0e804a1 --- /dev/null +++ b/BudgetAnalyser.Engine.UnitTest/.editorconfig @@ -0,0 +1,3 @@ + +[*.cs] +resharper_inconsistent_naming_highlighting=hint diff --git a/BudgetAnalyser.Engine.UnitTest/Account/AccountTypeRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Account/AccountTypeRepositoryTest.cs index 60470d14..1dc46b46 100644 --- a/BudgetAnalyser.Engine.UnitTest/Account/AccountTypeRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Account/AccountTypeRepositoryTest.cs @@ -13,10 +13,10 @@ public class AccountTypeRepositoryTest [TestMethod] public void AddingDuplicateEntryShouldNotThrow() { - InMemoryAccountTypeRepository subject = CreateSubject(); - ChequeAccount data = CreateTestData2(); + var subject = CreateSubject(); + var data = CreateTestData2(); subject.Add(Key1, data); - ChequeAccount data2 = CreateTestData2(); + var data2 = CreateTestData2(); subject.Add(Key1, data2); Assert.AreEqual(data.Name, subject.GetByKey(Key1).Name); } @@ -25,7 +25,7 @@ public void AddingDuplicateEntryShouldNotThrow() [ExpectedException(typeof(ArgumentNullException))] public void AddingEmptyKeyEntryShouldThrow() { - InMemoryAccountTypeRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Add(string.Empty, CreateTestData()); Assert.Fail(); } @@ -33,8 +33,8 @@ public void AddingEmptyKeyEntryShouldThrow() [TestMethod] public void AddingNewEntryShouldBeRetrievableByKey() { - InMemoryAccountTypeRepository subject = CreateSubject(); - ChequeAccount data = CreateTestData2(); + var subject = CreateSubject(); + var data = CreateTestData2(); subject.Add(Key1, data); Assert.AreEqual(data.Name, subject.GetByKey(Key1).Name); } @@ -43,7 +43,7 @@ public void AddingNewEntryShouldBeRetrievableByKey() [ExpectedException(typeof(ArgumentNullException))] public void AddingNullEntryShouldThrow() { - InMemoryAccountTypeRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Add(Key1, null); Assert.Fail(); } @@ -52,7 +52,7 @@ public void AddingNullEntryShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void AddingNullKeyEntryShouldThrow() { - InMemoryAccountTypeRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Add(null, CreateTestData()); Assert.Fail(); } @@ -60,11 +60,11 @@ public void AddingNullKeyEntryShouldThrow() [TestMethod] public void FindExistingValueShouldSucceed() { - InMemoryAccountTypeRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Add(Key1, CreateTestData()); subject.Add(Key2, CreateTestData()); - Engine.BankAccount.Account result = subject.Find(a => a.Name == Key1); + var result = subject.Find(a => a.Name == Key1); Assert.IsNotNull(result); } @@ -72,11 +72,11 @@ public void FindExistingValueShouldSucceed() [TestMethod] public void FindNonExistentValueShouldFail() { - InMemoryAccountTypeRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Add(Key1, CreateTestData()); subject.Add(Key2, CreateTestData()); - Engine.BankAccount.Account result = subject.Find(a => a.Name == "Key99"); + var result = subject.Find(a => a.Name == "Key99"); Assert.IsNull(result); } @@ -84,9 +84,9 @@ public void FindNonExistentValueShouldFail() [TestMethod] public void GetOrCreateNewDuplicateEntryShouldNotThrow() { - InMemoryAccountTypeRepository subject = CreateSubject(); - Engine.BankAccount.Account result1 = subject.GetByKey(Key1); - Engine.BankAccount.Account result2 = subject.GetByKey(Key1); + var subject = CreateSubject(); + var result1 = subject.GetByKey(Key1); + var result2 = subject.GetByKey(Key1); Assert.AreSame(result1, result2); } @@ -106,4 +106,4 @@ private InMemoryAccountTypeRepository CreateSubject() return new InMemoryAccountTypeRepository(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Account/AmexAccountTest.cs b/BudgetAnalyser.Engine.UnitTest/Account/AmexAccountTest.cs index dc51697f..4b60f35b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Account/AmexAccountTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Account/AmexAccountTest.cs @@ -9,8 +9,8 @@ public class AmexAccountTest [TestMethod] public void CloneShouldGiveUseNameGiven() { - AmexAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneAmex"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneAmex"); Assert.AreEqual("CloneAmex", clone.Name); Assert.AreNotEqual("CloneAmex", subject.Name); @@ -19,8 +19,8 @@ public void CloneShouldGiveUseNameGiven() [TestMethod] public void CloneShouldNotJustCopyReference() { - AmexAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneAmex"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneAmex"); Assert.IsFalse(ReferenceEquals(subject, clone)); } @@ -28,7 +28,7 @@ public void CloneShouldNotJustCopyReference() [TestMethod] public void KeywordsShouldContainElements() { - AmexAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsTrue(subject.KeyWords.Length > 0); } @@ -36,7 +36,7 @@ public void KeywordsShouldContainElements() [TestMethod] public void KeywordsShouldNotBeNull() { - AmexAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNotNull(subject.KeyWords); } @@ -44,7 +44,7 @@ public void KeywordsShouldNotBeNull() [TestMethod] public void NameShouldBeSomething() { - AmexAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(string.IsNullOrWhiteSpace(subject.Name)); } @@ -53,4 +53,4 @@ private AmexAccount CreateSubject() return new AmexAccount("AmexTest"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Account/ChequeAccountTest.cs b/BudgetAnalyser.Engine.UnitTest/Account/ChequeAccountTest.cs index 0808c3f8..846530ef 100644 --- a/BudgetAnalyser.Engine.UnitTest/Account/ChequeAccountTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Account/ChequeAccountTest.cs @@ -9,8 +9,8 @@ public class ChequeAccountTest [TestMethod] public void CloneShouldGiveUseNameGiven() { - ChequeAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneCheque"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneCheque"); Assert.AreEqual("CloneCheque", clone.Name); Assert.AreNotEqual("CloneCheque", subject.Name); @@ -19,8 +19,8 @@ public void CloneShouldGiveUseNameGiven() [TestMethod] public void CloneShouldNotJustCopyReference() { - ChequeAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneCheque"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneCheque"); Assert.IsFalse(ReferenceEquals(subject, clone)); } @@ -28,7 +28,7 @@ public void CloneShouldNotJustCopyReference() [TestMethod] public void KeywordsShouldContainElements() { - ChequeAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsTrue(subject.KeyWords.Length > 0); } @@ -36,7 +36,7 @@ public void KeywordsShouldContainElements() [TestMethod] public void KeywordsShouldNotBeNull() { - ChequeAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNotNull(subject.KeyWords); } @@ -44,7 +44,7 @@ public void KeywordsShouldNotBeNull() [TestMethod] public void NameShouldBeSomething() { - ChequeAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(string.IsNullOrWhiteSpace(subject.Name)); } @@ -53,4 +53,4 @@ private ChequeAccount CreateSubject() return new ChequeAccount("ChequeTest"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Account/MastercardAccountTest.cs b/BudgetAnalyser.Engine.UnitTest/Account/MastercardAccountTest.cs index f87f7f35..3eea03e1 100644 --- a/BudgetAnalyser.Engine.UnitTest/Account/MastercardAccountTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Account/MastercardAccountTest.cs @@ -9,8 +9,8 @@ public class MastercardAccountTest [TestMethod] public void CloneShouldGiveUseNameGiven() { - MastercardAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneMastercard"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneMastercard"); Assert.AreEqual("CloneMastercard", clone.Name); Assert.AreNotEqual("CloneMastercard", subject.Name); @@ -19,8 +19,8 @@ public void CloneShouldGiveUseNameGiven() [TestMethod] public void CloneShouldNotJustCopyReference() { - MastercardAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneMastercard"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneMastercard"); Assert.IsFalse(ReferenceEquals(subject, clone)); } @@ -28,7 +28,7 @@ public void CloneShouldNotJustCopyReference() [TestMethod] public void KeywordsShouldContainElements() { - MastercardAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsTrue(subject.KeyWords.Length > 0); } @@ -36,7 +36,7 @@ public void KeywordsShouldContainElements() [TestMethod] public void KeywordsShouldNotBeNull() { - MastercardAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNotNull(subject.KeyWords); } @@ -44,7 +44,7 @@ public void KeywordsShouldNotBeNull() [TestMethod] public void NameShouldBeSomething() { - MastercardAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(string.IsNullOrWhiteSpace(subject.Name)); } @@ -53,4 +53,4 @@ private MastercardAccount CreateSubject() return new MastercardAccount("MastercardTest"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Account/VisaAccountTest.cs b/BudgetAnalyser.Engine.UnitTest/Account/VisaAccountTest.cs index dcf2efcb..48addbfb 100644 --- a/BudgetAnalyser.Engine.UnitTest/Account/VisaAccountTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Account/VisaAccountTest.cs @@ -9,8 +9,8 @@ public class VisaAccountTest [TestMethod] public void CloneShouldGiveUseNameGiven() { - VisaAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneVisa"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneVisa"); Assert.AreEqual("CloneVisa", clone.Name); Assert.AreNotEqual("CloneVisa", subject.Name); @@ -19,8 +19,8 @@ public void CloneShouldGiveUseNameGiven() [TestMethod] public void CloneShouldNotJustCopyReference() { - VisaAccount subject = CreateSubject(); - Engine.BankAccount.Account clone = subject.Clone("CloneVisa"); + var subject = CreateSubject(); + var clone = subject.Clone("CloneVisa"); Assert.IsFalse(ReferenceEquals(subject, clone)); } @@ -28,7 +28,7 @@ public void CloneShouldNotJustCopyReference() [TestMethod] public void KeywordsShouldContainElements() { - VisaAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsTrue(subject.KeyWords.Length > 0); } @@ -36,7 +36,7 @@ public void KeywordsShouldContainElements() [TestMethod] public void KeywordsShouldNotBeNull() { - VisaAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNotNull(subject.KeyWords); } @@ -44,7 +44,7 @@ public void KeywordsShouldNotBeNull() [TestMethod] public void NameShouldBeSomething() { - VisaAccount subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(string.IsNullOrWhiteSpace(subject.Name)); } @@ -53,4 +53,4 @@ private VisaAccount CreateSubject() return new VisaAccount("VisaTest"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/AutoRegisterWithIoCProcessorPropertyInjectionTestSource.cs b/BudgetAnalyser.Engine.UnitTest/AutoRegisterWithIoCProcessorPropertyInjectionTestSource.cs index 87e91bd0..66ef432e 100644 --- a/BudgetAnalyser.Engine.UnitTest/AutoRegisterWithIoCProcessorPropertyInjectionTestSource.cs +++ b/BudgetAnalyser.Engine.UnitTest/AutoRegisterWithIoCProcessorPropertyInjectionTestSource.cs @@ -11,4 +11,4 @@ public static class AutoRegisterWithIoCProcessorPropertyInjectionTestSource public static ILogger NotInjected { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketFactoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketFactoryTest.cs index cc961f9a..2308b12d 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketFactoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketFactoryTest.cs @@ -49,7 +49,7 @@ public void BuildShouldCreateSavedUpForExpenseBucket() { Assert.IsInstanceOfType( Subject.BuildModel( - new BudgetBucketDto {Type = BucketDtoType.SavedUpForExpense}), + new BudgetBucketDto { Type = BucketDtoType.SavedUpForExpense }), typeof(SavedUpForExpenseBucket)); } @@ -57,7 +57,7 @@ public void BuildShouldCreateSavedUpForExpenseBucket() public void BuildShouldCreateSpentMonthlyBucket() { Assert.IsInstanceOfType( - Subject.BuildModel(new BudgetBucketDto { Type = BucketDtoType.SpentPeriodicallyExpense }), + Subject.BuildModel(new BudgetBucketDto { Type = BucketDtoType.SpentPeriodicallyExpense }), typeof(SpentPerPeriodExpenseBucket)); } @@ -73,7 +73,7 @@ public void BuildShouldThrowGivenPayCreditCard() [ExpectedException(typeof(NotSupportedException))] public void BuildShouldThrowGivenSurplus() { - Subject.BuildModel(new BudgetBucketDto { Type = BucketDtoType.Surplus}); + Subject.BuildModel(new BudgetBucketDto { Type = BucketDtoType.Surplus }); Assert.Fail(); } @@ -132,4 +132,4 @@ private static BudgetBucketFactory Arrange() return new BudgetBucketFactory(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketTest.cs index ac363815..8f223d3d 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketTest.cs @@ -18,7 +18,7 @@ public class BudgetBucketTest [TestMethod] public void BudgetBucketPropertiesShouldBeMapped() { - IEnumerable properties = typeof(BudgetBucket).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); + var properties = typeof(BudgetBucket).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); Assert.AreEqual(3, properties.Count()); } @@ -34,8 +34,8 @@ public void Comparable_HairBucketIsLessThanPower() [TestMethod] public void Comparable_PhoneBucketIsEqualToAnotherInstance() { - SpentPerPeriodExpenseBucket phoneBucket = StatementModelTestData.PhoneBucket; - BudgetBucket phooneBucket2 = Arrange(TestDataConstants.PhoneBucketCode, "Foo"); + var phoneBucket = StatementModelTestData.PhoneBucket; + var phooneBucket2 = Arrange(TestDataConstants.PhoneBucketCode, "Foo"); Assert.IsTrue(phoneBucket.CompareTo(phooneBucket2) == 0); } @@ -44,7 +44,7 @@ public void Comparable_PhoneBucketIsEqualToAnotherInstance() public void Comparable_PhoneBucketIsGreaterThanHair() { var hairBucket = StatementModelTestData.HairBucket; - SpentPerPeriodExpenseBucket phoneBucket = StatementModelTestData.PhoneBucket; + var phoneBucket = StatementModelTestData.PhoneBucket; Assert.IsTrue(phoneBucket.CompareTo(hairBucket) > 0); } @@ -52,7 +52,7 @@ public void Comparable_PhoneBucketIsGreaterThanHair() [TestMethod] public void CtorShouldAllocateUpperCaseCode() { - BudgetBucket subject = Arrange("Foo", "Bar"); + var subject = Arrange("Foo", "Bar"); Assert.AreEqual("FOO", subject.Code); Assert.AreNotEqual("Foo", subject.Code); } @@ -76,7 +76,7 @@ public void CtorShouldThrowWhenNameIsNull() [TestMethod] public void SettingCodeShouldConvertToUpperCase() { - BudgetBucket subject = Arrange("Foo", "Bar"); + var subject = Arrange("Foo", "Bar"); subject.Code = "White"; Assert.AreNotEqual("White", subject.Code); Assert.AreEqual("WHITE", subject.Code); @@ -85,8 +85,8 @@ public void SettingCodeShouldConvertToUpperCase() [TestMethod] public void TwoBucketsAreDifferentIfCodesAreDifferent() { - BudgetBucket subject1 = Arrange("Foo1", "Name"); - BudgetBucket subject2 = Arrange("Foo2", "Name"); + var subject1 = Arrange("Foo1", "Name"); + var subject2 = Arrange("Foo2", "Name"); Assert.AreNotEqual(subject1, subject2); Assert.IsTrue(subject1 != subject2); Assert.AreNotEqual(subject1.GetHashCode(), subject2.GetHashCode()); @@ -95,8 +95,8 @@ public void TwoBucketsAreDifferentIfCodesAreDifferent() [TestMethod] public void TwoBucketsAreTheSameIfCodesAreEqual() { - BudgetBucket subject1 = Arrange("Foo", "Name"); - BudgetBucket subject2 = Arrange("Foo", "Name"); + var subject1 = Arrange("Foo", "Name"); + var subject2 = Arrange("Foo", "Name"); Assert.AreEqual(subject1, subject2); Assert.IsTrue(subject1 == subject2); Assert.AreEqual(subject1.GetHashCode(), subject2.GetHashCode()); @@ -105,8 +105,8 @@ public void TwoBucketsAreTheSameIfCodesAreEqual() [TestMethod] public void TwoReferencesToDifferentObjectsAreNotEqual() { - BudgetBucket subject1 = Arrange("Foo", "Name"); - BudgetBucket subject2 = Arrange("Ben", "Is Awesome"); + var subject1 = Arrange("Foo", "Name"); + var subject2 = Arrange("Ben", "Is Awesome"); Assert.AreNotEqual(subject1, subject2); Assert.IsTrue(subject1 != subject2); Assert.AreNotEqual(subject1.GetHashCode(), subject2.GetHashCode()); @@ -115,8 +115,8 @@ public void TwoReferencesToDifferentObjectsAreNotEqual() [TestMethod] public void TwoReferencesToTheSameObjectAreEqual() { - BudgetBucket subject1 = Arrange("Foo", "Name"); - BudgetBucket subject2 = subject1; + var subject1 = Arrange("Foo", "Name"); + var subject2 = subject1; Assert.AreEqual(subject1, subject2); Assert.IsTrue(subject1 == subject2); Assert.AreEqual(subject1.GetHashCode(), subject2.GetHashCode()); @@ -125,9 +125,9 @@ public void TwoReferencesToTheSameObjectAreEqual() [TestMethod] public void ValidateShouldRetrunFalseGivenLongCode() { - BudgetBucket subject = Arrange(); + var subject = Arrange(); subject.Code = "ABC345678"; - bool result = subject.Validate(new StringBuilder()); + var result = subject.Validate(new StringBuilder()); Assert.IsFalse(result); } @@ -135,7 +135,7 @@ public void ValidateShouldRetrunFalseGivenLongCode() [ExpectedException(typeof(ArgumentNullException))] public void ValidateShouldThrowGivenNullStringBuilder() { - BudgetBucket subject = Arrange(); + var subject = Arrange(); subject.Validate(null); Assert.Fail(); } @@ -143,7 +143,7 @@ public void ValidateShouldThrowGivenNullStringBuilder() [TestMethod] public void ValidateWillReturnFalseWhenCodeIsNull() { - BudgetBucket subject = Arrange(); + var subject = Arrange(); subject.Description = "Foo bar"; var builder = new StringBuilder(); Assert.IsFalse(subject.Validate(builder)); @@ -153,7 +153,7 @@ public void ValidateWillReturnFalseWhenCodeIsNull() [TestMethod] public void ValidateWillReturnFalseWhenCodeIsTooLong() { - BudgetBucket subject = Arrange(); + var subject = Arrange(); subject.Description = "FooBarHo"; var builder = new StringBuilder(); Assert.IsFalse(subject.Validate(builder)); @@ -163,7 +163,7 @@ public void ValidateWillReturnFalseWhenCodeIsTooLong() [TestMethod] public void ValidateWillReturnFalseWhenNameIsNull() { - BudgetBucket subject = Arrange(); + var subject = Arrange(); subject.Code = "Foo"; var builder = new StringBuilder(); Assert.IsFalse(subject.Validate(builder)); @@ -177,9 +177,9 @@ private BudgetBucket Arrange(string code = NotSpecified, string name = NotSpecif return new BudgetBucketTestHarness(); } - string code2 = code == NotSpecified ? null : code; - string name2 = name == NotSpecified ? null : name; + var code2 = code == NotSpecified ? null : code; + var name2 = name == NotSpecified ? null : name; return new BudgetBucketTestHarness(code2, name2); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketToDtoMapperTest.cs index 32d77851..dd839fad 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetBucketToDtoMapperTest.cs @@ -37,8 +37,8 @@ public void ShouldMapType() public void TestInitialise() { var testData = StatementModelTestData.CarMtcBucket; - var subject = new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()); + var subject = new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()); Result = subject.ToDto(testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionTest.cs index b5a749d3..b004a414 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionTest.cs @@ -16,9 +16,9 @@ public class BudgetCollectionTest [TestMethod] public void ForDate_1_1_2013_ShouldReturnBudget1() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); - BudgetModel result = subject.ForDate(new DateTime(2013, 1, 1)); + var result = subject.ForDate(new DateTime(2013, 1, 1)); Assert.AreSame(subject.First(b => b.Name == TestDataConstants.Budget1Name), result); } @@ -26,9 +26,9 @@ public void ForDate_1_1_2013_ShouldReturnBudget1() [TestMethod] public void ForDate_1_1_2014_ShouldReturnBudget1() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); - BudgetModel result = subject.ForDate(new DateTime(2014, 1, 1)); + var result = subject.ForDate(new DateTime(2014, 1, 1)); Assert.AreSame(subject.First(b => b.Name == TestDataConstants.Budget1Name), result); } @@ -36,9 +36,9 @@ public void ForDate_1_1_2014_ShouldReturnBudget1() [TestMethod] public void ForDate_25_1_2014_ShouldReturnBudget2() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); - BudgetModel result = subject.ForDate(new DateTime(2014, 1, 25)); + var result = subject.ForDate(new DateTime(2014, 1, 25)); Assert.AreSame(subject.First(b => b.Name == TestDataConstants.Budget2Name), result); } @@ -46,9 +46,9 @@ public void ForDate_25_1_2014_ShouldReturnBudget2() [TestMethod] public void ForDate_WithEarlierDateThanFirstBudget_ShouldReturnNull() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); - BudgetModel result = subject.ForDate(DateTime.MinValue); + var result = subject.ForDate(DateTime.MinValue); Assert.IsNull(result); } @@ -56,8 +56,8 @@ public void ForDate_WithEarlierDateThanFirstBudget_ShouldReturnNull() [TestMethod] public void ForDates_1_1_2013_to_20_1_2014_ShouldReturnBudget1And2() { - BudgetCollection subject = Arrange(); - IEnumerable result = subject.ForDates(new DateTime(2013, 1, 1), new DateTime(2014, 1, 20)); + var subject = Arrange(); + var result = subject.ForDates(new DateTime(2013, 1, 1), new DateTime(2014, 1, 20)); Assert.AreEqual(2, result.Count()); } @@ -65,7 +65,7 @@ public void ForDates_1_1_2013_to_20_1_2014_ShouldReturnBudget1And2() [ExpectedException(typeof(BudgetException))] public void ForDates_WithDatesOutsideBudgetCollection_ShouldThrow() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); subject.ForDates(DateTime.MinValue, DateTime.MaxValue); @@ -75,8 +75,8 @@ public void ForDates_WithDatesOutsideBudgetCollection_ShouldThrow() [TestMethod] public void OutputBudgetCollection() { - BudgetCollection subject = Arrange(); - foreach (BudgetModel budget in subject) + var subject = Arrange(); + foreach (var budget in subject) { Console.WriteLine("Budget: '{0}' EffectiveFrom: {1:d}", budget.Name, budget.EffectiveFrom); } @@ -86,14 +86,14 @@ public void OutputBudgetCollection() public void ShouldHaveAKnownNumberOfProperties() { // If this test breaks consider putting the new property into the Mappers and DTO's before updating the count. - IEnumerable properties = typeof(BudgetCollection).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); + var properties = typeof(BudgetCollection).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); Assert.AreEqual(1, properties.Count()); } [TestMethod] public void ValidateShouldFixGivenBudgetsWithDuplicateEffectiveDates() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); subject.Add( new BudgetModelFake { @@ -108,7 +108,7 @@ public void ValidateShouldFixGivenBudgetsWithDuplicateEffectiveDates() [TestMethod] public void ValidateShouldReturnFalseGivenOneBadBudget() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); subject.Add( new BudgetModelFake { @@ -118,7 +118,7 @@ public void ValidateShouldReturnFalseGivenOneBadBudget() ValidateOverride = msg => false }); - bool result = subject.Validate(new StringBuilder()); + var result = subject.Validate(new StringBuilder()); Assert.IsFalse(result); } @@ -126,7 +126,7 @@ public void ValidateShouldReturnFalseGivenOneBadBudget() [TestMethod] public void ValidateShouldReturnTrueGivenBudgetsWithDuplicateEffectiveDates() { - BudgetCollection subject = Arrange(); + var subject = Arrange(); subject.Add( new BudgetModelFake { @@ -140,8 +140,8 @@ public void ValidateShouldReturnTrueGivenBudgetsWithDuplicateEffectiveDates() [TestMethod] public void ValidateShouldReturnTrueGivenGoodBudgets() { - BudgetCollection subject = Arrange(); - bool result = subject.Validate(new StringBuilder()); + var subject = Arrange(); + var result = subject.Validate(new StringBuilder()); Assert.IsTrue(result); } @@ -155,4 +155,4 @@ private BudgetCollection Arrange() }); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest.cs index 20578ba6..5854afe8 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest.cs @@ -14,14 +14,14 @@ public class BudgetCollectionToDtoMapperTest [TestMethod] public void BudgetsCountShouldBeMapped() { - BudgetCollectionDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Count, result.Budgets.Count); } [TestMethod] public void EffectiveFromShouldBeMapped() { - BudgetCollectionDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.StorageKey, result.StorageKey); } @@ -29,7 +29,7 @@ public void EffectiveFromShouldBeMapped() [Description("A test designed to break when new propperties are added to the BudgetCollectionDto. This is a trigger to update the mappers.")] public void NumberOfBudgetCollectionDtoPropertiesShouldBe3() { - int dataProperties = typeof(BudgetCollectionDto).CountProperties(); + var dataProperties = typeof(BudgetCollectionDto).CountProperties(); Assert.AreEqual(3, dataProperties); } @@ -42,11 +42,11 @@ public void TestInitialise() private BudgetCollectionDto ArrangeAndAct() { var bucketRepo = new BucketBucketRepoAlwaysFind(); - var mapper = new Mapper_BudgetCollectionDto_BudgetCollection( - bucketRepo, - new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()), - new Mapper_BudgetModelDto_BudgetModel(bucketRepo)); + var mapper = new MapperBudgetCollectionDtoBudgetCollection( + bucketRepo, + new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()), + new MapperBudgetModelDtoBudgetModel(bucketRepo)); return mapper.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest2.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest2.cs index 73611faf..b2ebd891 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest2.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCollectionToDtoMapperTest2.cs @@ -21,10 +21,10 @@ public void OutputBudgetCollectionDtoResult() { decimal expensesTotal = 0; Console.WriteLine("TestData (BudgetCollection)"); - foreach (BudgetModel budget in TestData) + foreach (var budget in TestData) { Console.WriteLine("Budget: '{0}' Effective From: {1}", budget.Name, budget.EffectiveFrom); - foreach (Expense expense in budget.Expenses) + foreach (var expense in budget.Expenses) { Console.WriteLine(" Expense: {0} {1}", expense.Bucket.Code, expense.Amount); expensesTotal += expense.Amount; @@ -35,10 +35,10 @@ public void OutputBudgetCollectionDtoResult() expensesTotal = 0; Console.WriteLine("Result (BudgetCollectionDto)"); - foreach (BudgetModelDto budget in Result.Budgets) + foreach (var budget in Result.Budgets) { Console.WriteLine("Budget: '{0}' Effective From: {1}", budget.Name, budget.EffectiveFrom); - foreach (ExpenseDto expense in budget.Expenses) + foreach (var expense in budget.Expenses) { Console.WriteLine(" Expense: {0} {1}", expense.BudgetBucketCode, expense.Amount); expensesTotal += expense.Amount; @@ -61,7 +61,7 @@ public void ShouldMapCorrectNumberOfBuckets() Console.WriteLine("Result.Buckets.Count = " + Result.Buckets.Count()); Assert.IsTrue(Result.Buckets.Any()); - foreach (BudgetBucket bucket in TestDataBuckets) + foreach (var bucket in TestDataBuckets) { Assert.IsTrue(Result.Buckets.Any(b => b.Code == bucket.Code)); } @@ -92,16 +92,16 @@ public void TestInitialise() .Distinct(); // Preload the buckets into the bucket repo used by the Mapper. - foreach (BudgetBucket bucket in TestDataBuckets) + foreach (var bucket in TestDataBuckets) { bucketRepo.GetByCode(bucket.Code); } - var subject = new Mapper_BudgetCollectionDto_BudgetCollection( - bucketRepo, - new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()), - new Mapper_BudgetModelDto_BudgetModel(bucketRepo)); + var subject = new MapperBudgetCollectionDtoBudgetCollection( + bucketRepo, + new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()), + new MapperBudgetModelDtoBudgetModel(bucketRepo)); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCurrencyContextTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCurrencyContextTest.cs index 24eb6de1..bcd663df 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCurrencyContextTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetCurrencyContextTest.cs @@ -12,7 +12,7 @@ public class BudgetCurrencyContextTest [TestMethod] public void Budget1ShouldBeArchivedAfterConstruction() { - BudgetCurrencyContext subject = CreateSubject1(); + var subject = CreateSubject1(); Assert.IsFalse(subject.BudgetActive); Assert.IsTrue(subject.BudgetArchived); @@ -22,7 +22,7 @@ public void Budget1ShouldBeArchivedAfterConstruction() [TestMethod] public void Budget1ShouldBeEffectiveUntilBudget2EffectiveDate() { - BudgetCurrencyContext subject = CreateSubject1(); + var subject = CreateSubject1(); Assert.IsTrue(subject.BudgetArchived); Assert.AreEqual(new DateTime(2014, 01, 20), subject.EffectiveUntil); @@ -31,7 +31,7 @@ public void Budget1ShouldBeEffectiveUntilBudget2EffectiveDate() [TestMethod] public void Budget2ShouldBeCurrentAfterConstruction() { - BudgetCurrencyContext subject = CreateSubject2(); + var subject = CreateSubject2(); Assert.IsTrue(subject.BudgetActive); Assert.IsFalse(subject.BudgetArchived); @@ -65,7 +65,7 @@ public void CtorShouldThrowIfModelIsNull() [TestMethod] public void ModelShouldNotBeNullAfterConstruction() { - BudgetCurrencyContext subject = CreateSubject1(); + var subject = CreateSubject1(); Assert.IsNotNull(subject.Model); } @@ -92,16 +92,16 @@ public void ShouldIndicateFutureBudgetWhenOneIsGiven() private static BudgetCurrencyContext CreateSubject1() { - BudgetModel budget1 = BudgetModelTestData.CreateTestData1(); + var budget1 = BudgetModelTestData.CreateTestData1(); var subject = new BudgetCurrencyContext(new BudgetCollection(new[] { budget1, BudgetModelTestData.CreateTestData2() }), budget1); return subject; } private static BudgetCurrencyContext CreateSubject2() { - BudgetModel budget2 = BudgetModelTestData.CreateTestData2(); + var budget2 = BudgetModelTestData.CreateTestData2(); var subject = new BudgetCurrencyContext(new BudgetCollection(new[] { BudgetModelTestData.CreateTestData1(), budget2 }), budget2); return subject; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetItemTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetItemTest.cs index 5f7da03c..6375b7e1 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetItemTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetItemTest.cs @@ -13,15 +13,15 @@ public class BudgetItemTest [TestMethod] public void ShouldHaveAKnownNumberOfProperties() { - IEnumerable properties = typeof(BudgetItem).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); + var properties = typeof(BudgetItem).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite); Assert.AreEqual(2, properties.Count()); } [TestMethod] public void TwoBudgetItemsAreDifferentIfCodesAreDifferent() { - BudgetItem subject1 = CreateSubject1(); - BudgetItem subject2 = CreateSubject2(); + var subject1 = CreateSubject1(); + var subject2 = CreateSubject2(); Assert.AreNotEqual(subject1, subject2); Assert.IsTrue(subject1 != subject2); @@ -31,8 +31,8 @@ public void TwoBudgetItemsAreDifferentIfCodesAreDifferent() [TestMethod] public void TwoBudgetItemsAreDifferentIfCodesAreEqualButDifferentTypes() { - BudgetItem subject1 = CreateSubject1(); - BudgetItem subject3 = CreateSubject3(); + var subject1 = CreateSubject1(); + var subject3 = CreateSubject3(); Assert.AreNotEqual(subject1, subject3); Assert.IsTrue(subject1 != subject3); @@ -42,8 +42,8 @@ public void TwoBudgetItemsAreDifferentIfCodesAreEqualButDifferentTypes() [TestMethod] public void TwoBudgetItemsAreTheSameIfCodesAreEqualAndSameType() { - BudgetItem subject1 = CreateSubject1(); - BudgetItem subject2 = CreateSubject1(); + var subject1 = CreateSubject1(); + var subject2 = CreateSubject1(); Assert.AreEqual(subject1, subject2); Assert.IsTrue(subject1 == subject2); @@ -53,8 +53,8 @@ public void TwoBudgetItemsAreTheSameIfCodesAreEqualAndSameType() [TestMethod] public void TwoReferencesToTheSameObjectAreEqual() { - BudgetItem subject1 = CreateSubject1(); - BudgetItem subject2 = subject1; + var subject1 = CreateSubject1(); + var subject2 = subject1; Assert.AreEqual(subject1, subject2); Assert.IsTrue(subject1 == subject2); @@ -91,4 +91,4 @@ private BudgetItem CreateSubject3() return new Income { Amount = 0.01M, Bucket = CreateBucket3() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelTest.cs index a11c481c..14ef9886 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelTest.cs @@ -34,7 +34,7 @@ public void AfterConstructionLastModifiedDateIsValidDate() [TestMethod] public void AfterInitialiseExpensesShouldBeInDescendingOrder() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); EnsureDescendingOrder(subject.Expenses); } @@ -42,7 +42,7 @@ public void AfterInitialiseExpensesShouldBeInDescendingOrder() [TestMethod] public void AfterInitialiseIncomesShouldBeInDescendingOrder() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); EnsureDescendingOrder(subject.Incomes); } @@ -50,7 +50,7 @@ public void AfterInitialiseIncomesShouldBeInDescendingOrder() [TestMethod] public void AfterUpdateExpensesAreReplaced() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); var expenses = new List { @@ -66,7 +66,7 @@ public void AfterUpdateExpensesAreReplaced() [TestMethod] public void AfterUpdateExpensesAreStillInDescendingOrder() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); var expenses = new List { @@ -82,7 +82,7 @@ public void AfterUpdateExpensesAreStillInDescendingOrder() [TestMethod] public void AfterUpdateIncomesAreReplaced() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); var incomes = new List { @@ -98,7 +98,7 @@ public void AfterUpdateIncomesAreReplaced() [TestMethod] public void AfterUpdateIncomesAreStillInDescendingOrder() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); var incomes = new List { @@ -114,9 +114,9 @@ public void AfterUpdateIncomesAreStillInDescendingOrder() [TestMethod] public void AfterUpdateLastModifiedIsUpdated() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); - DateTime lastUpdated = subject.LastModified; + var lastUpdated = subject.LastModified; Thread.Sleep(10); subject.Update(subject.Incomes, subject.Expenses); @@ -127,7 +127,7 @@ public void AfterUpdateLastModifiedIsUpdated() [TestMethod] public void CalculatedSurplusShouldBeExpectedValue() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); Assert.AreEqual(1175M, subject.Surplus); } @@ -145,11 +145,11 @@ public void ListsAreInitialised() [ExpectedException(typeof(ValidationWarningException))] public void SurplusCannotBeUsedInTheExpenseList() { - BudgetModel subject = BudgetModelTestData.CreateTestData1(); + var subject = BudgetModelTestData.CreateTestData1(); - List myExpenses = subject.Expenses.ToList(); + var myExpenses = subject.Expenses.ToList(); myExpenses.Add(new Expense { Amount = 445M, Bucket = new SurplusBucket() }); - List myIncomes = subject.Incomes.ToList(); + var myIncomes = subject.Incomes.ToList(); subject.Update(myIncomes, myExpenses); @@ -164,10 +164,10 @@ public void TestInitialize() private static void EnsureDescendingOrder(IEnumerable items) { - decimal previousAmount = decimal.MaxValue; - foreach (BudgetItem item in items) + var previousAmount = decimal.MaxValue; + foreach (var item in items) { - decimal current = item.Amount; + var current = item.Amount; if (current > previousAmount) { Assert.Fail("Expenses are not in descending order."); @@ -177,4 +177,4 @@ private static void EnsureDescendingOrder(IEnumerable items) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelToDtoMapperTest.cs index 46686825..8a939f7e 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/BudgetModelToDtoMapperTest.cs @@ -15,70 +15,70 @@ public class BudgetModelToDtoMapperTest [TestMethod] public void EffectiveFromShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.EffectiveFrom, result.EffectiveFrom); } [TestMethod] public void ExpensesBucketsShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsTrue(result.Expenses.All(dto => !string.IsNullOrWhiteSpace(dto.BudgetBucketCode))); } [TestMethod] public void ExpensesCountShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Expenses.Count(), result.Expenses.Count); } [TestMethod] public void ExpensesSumShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Expenses.Sum(i => i.Amount), result.Expenses.Sum(i => i.Amount)); } [TestMethod] public void IncomesBucketsShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsTrue(result.Incomes.All(dto => !string.IsNullOrWhiteSpace(dto.BudgetBucketCode))); } [TestMethod] public void IncomesCountShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Incomes.Count(), result.Incomes.Count); } [TestMethod] public void IncomesSumShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Incomes.Sum(i => i.Amount), result.Incomes.Sum(i => i.Amount)); } [TestMethod] public void LastModifiedCommentShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.LastModifiedComment, result.LastModifiedComment); } [TestMethod] public void LastModifiedDateShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.LastModified, result.LastModified); } [TestMethod] public void NameShouldBeMapped() { - BudgetModelDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Name, result.Name); } @@ -86,7 +86,7 @@ public void NameShouldBeMapped() [Description("A test designed to break when new properties are added to the BudgetModelDto. This is a trigger to update the mappers.")] public void NumberOfDataBudgetModelPropertiesShouldBe7() { - int dataProperties = typeof(BudgetModelDto).CountProperties(); + var dataProperties = typeof(BudgetModelDto).CountProperties(); Assert.AreEqual(7, dataProperties); } @@ -98,8 +98,8 @@ public void TestInitialise() private BudgetModelDto ArrangeAndAct() { - var mapper = new Mapper_BudgetModelDto_BudgetModel(new BucketBucketRepoAlwaysFind()); + var mapper = new MapperBudgetModelDtoBudgetModel(new BucketBucketRepoAlwaysFind()); return mapper.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetBucketTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetBucketTest.cs index 55d88028..37f23a63 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetBucketTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetBucketTest.cs @@ -33,8 +33,8 @@ public void ShouldMapType() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()); + var subject = new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest.cs index 716cd94a..5baf3153 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest.cs @@ -1,6 +1,6 @@ -using Portable.Xaml; -using BudgetAnalyser.Engine.Budget.Data; +using BudgetAnalyser.Engine.Budget.Data; using BudgetAnalyser.Engine.UnitTest.TestData; +using Portable.Xaml; namespace BudgetAnalyser.Engine.UnitTest.Budget { @@ -74,8 +74,8 @@ public void OutputBudgetModelTestData1() StorageKey = "Foo.xml" }; - string serialised = XamlServices.Save(collection); + var serialised = XamlServices.Save(collection); Console.WriteLine(serialised); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest2.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest2.cs index bada2faa..ca4bafd7 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest2.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetCollectionMapperTest2.cs @@ -36,11 +36,11 @@ public void TestInitialise() { TestData = GetType().Assembly.ExtractEmbeddedResourceAsXamlObject("BudgetAnalyser.Engine.UnitTest.TestData.BudgetCollectionTestData.xml"); var bucketRepo = new BucketBucketRepoAlwaysFind(); - var subject = new Mapper_BudgetCollectionDto_BudgetCollection( + var subject = new MapperBudgetCollectionDtoBudgetCollection( bucketRepo, - new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()), - new Mapper_BudgetModelDto_BudgetModel(bucketRepo)); + new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()), + new MapperBudgetModelDtoBudgetModel(bucketRepo)); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetModelMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetModelMapperTest.cs index ef258b9a..8e640f7b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetModelMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToBudgetModelMapperTest.cs @@ -1,8 +1,8 @@ -using Portable.Xaml; -using BudgetAnalyser.Engine.Budget; +using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Budget.Data; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; +using Portable.Xaml; namespace BudgetAnalyser.Engine.UnitTest.Budget { @@ -11,18 +11,13 @@ public class DtoToBudgetModelMapperTest { private BudgetModel Result { get; set; } - private BudgetModelDto TestData + private BudgetModelDto TestData => new BudgetModelDto { - get - { - return - new BudgetModelDto - { - EffectiveFrom = new DateTime(2014, 4, 28), - LastModified = new DateTime(2014, 5, 2), - LastModifiedComment = "The quick brown fox jumped over the lazy dog.", - Name = "Foo data budget", - Incomes = new List + EffectiveFrom = new DateTime(2014, 4, 28), + LastModified = new DateTime(2014, 5, 2), + LastModifiedComment = "The quick brown fox jumped over the lazy dog.", + Name = "Foo data budget", + Incomes = new List { new IncomeDto { @@ -30,7 +25,7 @@ private BudgetModelDto TestData BudgetBucketCode = TestDataConstants.IncomeBucketCode } }, - Expenses = new List + Expenses = new List { new ExpenseDto { @@ -43,14 +38,12 @@ private BudgetModelDto TestData BudgetBucketCode = TestDataConstants.PowerBucketCode } } - }; - } - } + }; [TestMethod] public void OutputBudgetModelTestData1() { - string serialised = XamlServices.Save(TestData); + var serialised = XamlServices.Save(TestData); Console.WriteLine(serialised); } @@ -75,7 +68,7 @@ public void ShouldMapEffectiveFrom() [TestMethod] public void ShouldMapExpenses() { - foreach (Expense expense in Result.Expenses) + foreach (var expense in Result.Expenses) { Assert.AreEqual(TestData.Expenses.First(e => e.BudgetBucketCode == expense.Bucket.Code && expense.Amount == e.Amount).Amount, expense.Amount); } @@ -84,7 +77,7 @@ public void ShouldMapExpenses() [TestMethod] public void ShouldMapIncomes() { - foreach (Income incomes in Result.Incomes) + foreach (var incomes in Result.Incomes) { Assert.AreEqual(TestData.Incomes.First(e => e.BudgetBucketCode == incomes.Bucket.Code && incomes.Amount == e.Amount).Amount, incomes.Amount); } @@ -111,8 +104,8 @@ public void ShouldMapLastName() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_BudgetModelDto_BudgetModel(new BucketBucketRepoAlwaysFind()); + var subject = new MapperBudgetModelDtoBudgetModel(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToExpenseMapper.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToExpenseMapper.cs index b52c59ca..38309bd7 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToExpenseMapper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToExpenseMapper.cs @@ -11,17 +11,11 @@ public class DtoToExpenseMapper { private Expense Result { get; set; } - private ExpenseDto TestData + private ExpenseDto TestData => new ExpenseDto { - get - { - return new ExpenseDto - { - Amount = 1444.22M, - BudgetBucketCode = TestDataConstants.DoctorBucketCode - }; - } - } + Amount = 1444.22M, + BudgetBucketCode = TestDataConstants.DoctorBucketCode + }; [TestMethod] public void ShouldMapAmount() @@ -38,8 +32,8 @@ public void ShouldMapCode() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_ExpenseDto_Expense(new BucketBucketRepoAlwaysFind()); + var subject = new MapperExpenseDto2Expense(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToFixedBudgetProjectBucketTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToFixedBudgetProjectBucketTest.cs index c2bfc4ff..ac125cac 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToFixedBudgetProjectBucketTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToFixedBudgetProjectBucketTest.cs @@ -50,8 +50,8 @@ public void TestInitialise() Description = "Foo bar tiddle-de-dum", FixedBudgetAmount = 2000 }; - var subject = new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()); + var subject = new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()); this.result = subject.ToModel(this.testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToIncomeMapper.cs b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToIncomeMapper.cs index dde8bec7..c8706999 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/DtoToIncomeMapper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/DtoToIncomeMapper.cs @@ -11,17 +11,11 @@ public class DtoToIncomeMapper { private Income Result { get; set; } - private IncomeDto TestData + private IncomeDto TestData => new IncomeDto { - get - { - return new IncomeDto - { - Amount = 1444.22M, - BudgetBucketCode = TestDataConstants.IncomeBucketCode - }; - } - } + Amount = 1444.22M, + BudgetBucketCode = TestDataConstants.IncomeBucketCode + }; [TestMethod] public void ShouldMapAmount() @@ -38,8 +32,8 @@ public void ShouldMapCode() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_IncomeDto_Income(new BucketBucketRepoAlwaysFind()); + var subject = new MapperIncomeDto2Income(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseTest.cs index 34fe48d1..fc76c305 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseTest.cs @@ -13,10 +13,10 @@ public class ExpenseTest [TestMethod] public void BucketMustHaveADescription() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Bucket.Description = null; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -25,10 +25,10 @@ public void BucketMustHaveADescription() [TestMethod] public void MaxDeciamlIsValidAmount() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = decimal.MaxValue; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); Assert.IsTrue(Logs.Length == 0); @@ -37,10 +37,10 @@ public void MaxDeciamlIsValidAmount() [TestMethod] public void MustBeAnExpenseBucket() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Bucket = new IncomeBudgetBucket("Foo", "Bar"); - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -49,10 +49,10 @@ public void MustBeAnExpenseBucket() [TestMethod] public void NegativeAmountIsNotValid() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = -5; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -61,11 +61,11 @@ public void NegativeAmountIsNotValid() [TestMethod] public void NegativeAmountIsNotValidEvenWhenInactive() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = -5; subject.Bucket.Active = false; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -74,9 +74,9 @@ public void NegativeAmountIsNotValidEvenWhenInactive() [TestMethod] public void OneCentIsValidAmount() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); Assert.IsTrue(Logs.Length == 0); @@ -91,11 +91,11 @@ public void TestInitialize() [TestMethod] public void ZeroAmountIsNotValidWhenActive() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = 0; subject.Bucket.Active = true; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -104,11 +104,11 @@ public void ZeroAmountIsNotValidWhenActive() [TestMethod] public void ZeroAmountIsValidWhenInActive() { - Expense subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = 0; subject.Bucket.Active = false; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); } @@ -118,4 +118,4 @@ private Expense CreateSubject() return new Expense { Amount = 0.01M, Bucket = new SpentPerPeriodExpenseBucket(TestDataConstants.CarMtcBucketCode, "Foo Bar") }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseToDtoMapperTest.cs index 9554678a..b4fcc029 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/ExpenseToDtoMapperTest.cs @@ -28,8 +28,8 @@ public void ShouldMapCode() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_ExpenseDto_Expense(new BucketBucketRepoAlwaysFind()); + var subject = new MapperExpenseDto2Expense(new BucketBucketRepoAlwaysFind()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/FixedBudgetProjectBucketToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/FixedBudgetProjectBucketToDtoMapperTest.cs index ed79a551..f2d99834 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/FixedBudgetProjectBucketToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/FixedBudgetProjectBucketToDtoMapperTest.cs @@ -56,8 +56,8 @@ public void TestInitialise() this.testData = new FixedBudgetProjectBucket(FixedProjectCode, "Foo bar dum-de-dum", 1000); PrivateAccessor.SetProperty(this.testData, "Created", this.testDataCreatedDate); - var subject = new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()); + var subject = new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()); this.result = subject.ToDto(this.testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/InMemoryBudgetBucketRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/InMemoryBudgetBucketRepositoryTest.cs index 595cb8c8..deb10ab2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/InMemoryBudgetBucketRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/InMemoryBudgetBucketRepositoryTest.cs @@ -18,7 +18,7 @@ public class InMemoryBudgetBucketRepositoryTest [TestMethod] public void AfterInitialisePayCreditCardBucketShouldExist() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Initialise(new List()); Assert.IsTrue(subject.IsValidCode(PayCreditCardBucket.PayCreditCardCode)); @@ -28,7 +28,7 @@ public void AfterInitialisePayCreditCardBucketShouldExist() [TestMethod] public void AfterInitialiseSurplusBucketShouldExist() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Initialise(new List()); Assert.IsTrue(subject.IsValidCode(SurplusBucket.SurplusCode)); @@ -38,8 +38,8 @@ public void AfterInitialiseSurplusBucketShouldExist() [TestMethod] public void CreateNewFixedBudgetProjectShouldReturnNewBucket() { - InMemoryBudgetBucketRepository subject = CreateSubject(); - FixedBudgetProjectBucket result = subject.CreateNewFixedBudgetProject("Foo", "Foo var", 1000); + var subject = CreateSubject(); + var result = subject.CreateNewFixedBudgetProject("Foo", "Foo var", 1000); Assert.IsNotNull(result); Assert.IsTrue(subject.IsValidCode(result.Code)); } @@ -48,7 +48,7 @@ public void CreateNewFixedBudgetProjectShouldReturnNewBucket() [ExpectedException(typeof(ArgumentException))] public void CreateNewFixedBudgetProjectShouldThrowGivenAmountLessThanZero() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.CreateNewFixedBudgetProject("Foo", "Foo bvar", 0); Assert.Fail(); } @@ -57,7 +57,7 @@ public void CreateNewFixedBudgetProjectShouldThrowGivenAmountLessThanZero() [ExpectedException(typeof(ArgumentException))] public void CreateNewFixedBudgetProjectShouldThrowGivenCodeAlreadyExists() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.GetOrCreateNew(FixedBudgetProjectBucket.CreateCode("Foo"), () => new FixedBudgetProjectBucket("Foo", "Foo bajh", 2000)); subject.CreateNewFixedBudgetProject("Foo", "Foo var", 1000); Assert.Fail(); @@ -67,7 +67,7 @@ public void CreateNewFixedBudgetProjectShouldThrowGivenCodeAlreadyExists() [ExpectedException(typeof(ArgumentNullException))] public void CreateNewFixedBudgetProjectShouldThrowGivenEmptyCode() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.CreateNewFixedBudgetProject(string.Empty, "foo bar", 1000); Assert.Fail(); } @@ -76,7 +76,7 @@ public void CreateNewFixedBudgetProjectShouldThrowGivenEmptyCode() [ExpectedException(typeof(ArgumentNullException))] public void CreateNewFixedBudgetProjectShouldThrowGivenEmptyDescription() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.CreateNewFixedBudgetProject("Foo", string.Empty, 1000); Assert.Fail(); } @@ -85,7 +85,7 @@ public void CreateNewFixedBudgetProjectShouldThrowGivenEmptyDescription() [ExpectedException(typeof(ArgumentNullException))] public void CreateNewFixedBudgetProjectShouldThrowGivenNullCode() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.CreateNewFixedBudgetProject(null, "foo bar", 1000); Assert.Fail(); } @@ -94,7 +94,7 @@ public void CreateNewFixedBudgetProjectShouldThrowGivenNullCode() [ExpectedException(typeof(ArgumentNullException))] public void CreateNewFixedBudgetProjectShouldThrowGivenNullDescription() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.CreateNewFixedBudgetProject("Foo", null, 1000); Assert.Fail(); } @@ -111,7 +111,7 @@ public void CtorShouldThrowGivenNullMapper() [ExpectedException(typeof(ArgumentNullException))] public void GetByCodeShouldThrowGivenNullCode() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); subject.GetByCode(null); @@ -122,7 +122,7 @@ public void GetByCodeShouldThrowGivenNullCode() [ExpectedException(typeof(ArgumentNullException))] public void GetByOrCreateNewShouldThrowGivenNullCode() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); subject.GetOrCreateNew(null, () => new PayCreditCardBucket()); @@ -133,7 +133,7 @@ public void GetByOrCreateNewShouldThrowGivenNullCode() [ExpectedException(typeof(ArgumentNullException))] public void GetByOrCreateNewShouldThrowGivenNullFactory() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); subject.GetOrCreateNew("CODE", null); @@ -143,7 +143,7 @@ public void GetByOrCreateNewShouldThrowGivenNullFactory() [TestMethod] public void GetOrAddShouldAddWhenItemDoesntExist() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); subject.GetOrCreateNew("Foo", () => new IncomeBudgetBucket("Foo", "Bar")); @@ -153,9 +153,9 @@ public void GetOrAddShouldAddWhenItemDoesntExist() [TestMethod] public void GetOrAddShouldNotAddWhenItemDoesExist() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); - int count = subject.Buckets.Count(); + var count = subject.Buckets.Count(); subject.GetOrCreateNew( TestDataConstants.HairBucketCode, () => @@ -170,15 +170,15 @@ public void GetOrAddShouldNotAddWhenItemDoesExist() [TestMethod] public void InitialiseShouldPopulate9Buckets() { - InMemoryBudgetBucketRepository subject = Arrange(); - int expected = CreateBudgetBucketDtoTestData().Count() + 2; // Surplus and PayCreditCard are added automatically. + var subject = Arrange(); + var expected = CreateBudgetBucketDtoTestData().Count() + 2; // Surplus and PayCreditCard are added automatically. Assert.AreEqual(expected, subject.Buckets.Count()); } [TestMethod] public void InitialiseShouldPopulateKnownBuckets() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); Assert.IsTrue(subject.IsValidCode(TestDataConstants.CarMtcBucketCode)); Assert.IsTrue(subject.IsValidCode(TestDataConstants.HairBucketCode)); @@ -190,7 +190,7 @@ public void InitialiseShouldPopulateKnownBuckets() [ExpectedException(typeof(ArgumentNullException))] public void InitialiseShouldThrowGivenNullBucketsArgument() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Initialise(null); Assert.Fail(); @@ -199,7 +199,7 @@ public void InitialiseShouldThrowGivenNullBucketsArgument() [TestMethod] public void IsValidCodeShouldReturnFalseWhenRepositoryIsEmpty() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(subject.IsValidCode(SurplusBucket.SurplusCode)); } @@ -207,7 +207,7 @@ public void IsValidCodeShouldReturnFalseWhenRepositoryIsEmpty() [ExpectedException(typeof(ArgumentNullException))] public void IsValidCodeShouldThrowGivenNullCode() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); subject.IsValidCode(null); @@ -217,26 +217,26 @@ public void IsValidCodeShouldThrowGivenNullCode() [TestMethod] public void NewRepositoryShouldBeEmpty() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(subject.Buckets.Any()); } [TestMethod] public void NewRepositoryShouldNotContainDefaultBuckets() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNull(subject.GetByCode(SurplusBucket.SurplusCode)); } [TestMethod] public void ThreadSafetyCheckOnGetOrAdd() { - InMemoryBudgetBucketRepository subject = Arrange(); + var subject = Arrange(); var threads = new List(); var concurrency = 50; var options = new ParallelOptions { MaxDegreeOfParallelism = 20 }; - ParallelLoopResult result = Parallel.For( + var result = Parallel.For( 1, concurrency, options, @@ -253,7 +253,7 @@ public void ThreadSafetyCheckOnGetOrAdd() Thread.Sleep(10); } - foreach (Thread thread in threads) + foreach (var thread in threads) { thread.Join(); Console.WriteLine("Thread finished "); @@ -264,7 +264,7 @@ public void ThreadSafetyCheckOnGetOrAdd() private InMemoryBudgetBucketRepository Arrange() { - InMemoryBudgetBucketRepository subject = CreateSubject(); + var subject = CreateSubject(); subject.Initialise(CreateBudgetBucketDtoTestData()); return subject; } @@ -281,7 +281,7 @@ private BudgetCollection CreateBudgetCollectionModel() private InMemoryBudgetBucketRepository CreateSubject() { - return new InMemoryBudgetBucketRepository(new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory())); + return new InMemoryBudgetBucketRepository(new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory())); } private void ThreadSafetyCheckOneThread(object subject) @@ -303,4 +303,4 @@ private void ThreadSafetyCheckOneThread(object subject) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/IncomeTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/IncomeTest.cs index ce47ded4..6692f222 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/IncomeTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/IncomeTest.cs @@ -13,10 +13,10 @@ public class IncomeTest [TestMethod] public void BucketMustHaveADescription() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Bucket.Description = null; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -25,10 +25,10 @@ public void BucketMustHaveADescription() [TestMethod] public void MaxDeciamlIsValidIncome() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = decimal.MaxValue; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); Assert.IsTrue(Logs.Length == 0); @@ -37,10 +37,10 @@ public void MaxDeciamlIsValidIncome() [TestMethod] public void MustBeAnIncomeBucket() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Bucket = new SavedUpForExpenseBucket("Foo", "Bar"); - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -49,10 +49,10 @@ public void MustBeAnIncomeBucket() [TestMethod] public void NegativeAmountIsNotValid() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = -5; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -61,11 +61,11 @@ public void NegativeAmountIsNotValid() [TestMethod] public void NegativeAmountIsNotValidEvenWhenInActive() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = -5; subject.Bucket.Active = false; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsFalse(result); Assert.IsTrue(Logs.Length > 0); @@ -74,9 +74,9 @@ public void NegativeAmountIsNotValidEvenWhenInActive() [TestMethod] public void OneCentIsValidIncome() { - Income subject = CreateSubject(); + var subject = CreateSubject(); - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); Assert.IsTrue(Logs.Length == 0); @@ -91,10 +91,10 @@ public void TestInitialize() [TestMethod] public void ZeroAmountIsValid() { - Income subject = CreateSubject(); + var subject = CreateSubject(); subject.Amount = 0; - bool result = subject.Validate(Logs); + var result = subject.Validate(Logs); Assert.IsTrue(result); } @@ -104,4 +104,4 @@ private Income CreateSubject() return new Income { Amount = 0.01M, Bucket = new IncomeBudgetBucket(TestDataConstants.IncomeBucketCode, "Foo Bar") }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/IncomeToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/IncomeToDtoMapperTest.cs index 6f1ab2cb..a259dd97 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/IncomeToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/IncomeToDtoMapperTest.cs @@ -28,8 +28,8 @@ public void ShouldMapCode() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_IncomeDto_Income(new BucketBucketRepoAlwaysFind()); + var subject = new MapperIncomeDto2Income(new BucketBucketRepoAlwaysFind()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Budget/XamlOnDiskBudgetRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Budget/XamlOnDiskBudgetRepositoryTest.cs index e8b91d6f..e5fc314a 100644 --- a/BudgetAnalyser.Engine.UnitTest/Budget/XamlOnDiskBudgetRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Budget/XamlOnDiskBudgetRepositoryTest.cs @@ -1,11 +1,11 @@ -using Portable.Xaml; -using BudgetAnalyser.Engine.Budget; +using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Budget.Data; using BudgetAnalyser.Engine.Persistence; using BudgetAnalyser.Engine.UnitTest.Helper; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; using Moq; +using Portable.Xaml; using Rees.UnitTestUtilities; namespace BudgetAnalyser.Engine.UnitTest.Budget @@ -230,15 +230,15 @@ private XamlOnDiskBudgetRepository Arrange(IBudgetBucketRepository bucketRepo = { if (bucketRepo is null) { - bucketRepo = new InMemoryBudgetBucketRepository(new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory())); + bucketRepo = new InMemoryBudgetBucketRepository(new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory())); } return new XamlOnDiskBudgetRepository( bucketRepo, - new Mapper_BudgetCollectionDto_BudgetCollection( + new MapperBudgetCollectionDtoBudgetCollection( bucketRepo, - new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory()), - new Mapper_BudgetModelDto_BudgetModel(bucketRepo)), + new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory()), + new MapperBudgetModelDtoBudgetModel(bucketRepo)), this.mockFileSelector.Object); } @@ -252,4 +252,4 @@ private static void SetPrivateBudgetCollection(XamlOnDiskBudgetRepository subjec PrivateAccessor.SetField(subject, "currentBudgetCollection", BudgetModelTestData.CreateCollectionWith1And2()); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/DateTimeExtensionTest.cs b/BudgetAnalyser.Engine.UnitTest/DateTimeExtensionTest.cs index 1e855e67..8201039e 100644 --- a/BudgetAnalyser.Engine.UnitTest/DateTimeExtensionTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/DateTimeExtensionTest.cs @@ -111,4 +111,4 @@ public void OneStandardPayMonthIsOneMonth2() Assert.AreEqual(1, new DateTime(2014, 1, 15).DurationInMonths(new DateTime(2014, 2, 14))); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/DebugLoggerTest.cs b/BudgetAnalyser.Engine.UnitTest/DebugLoggerTest.cs index a67b422f..27512afe 100644 --- a/BudgetAnalyser.Engine.UnitTest/DebugLoggerTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/DebugLoggerTest.cs @@ -9,7 +9,7 @@ public class DebugLoggerTest public void NoLoggingShouldOccurWhenDebuggerNotAttached() { var logger = new DebugLogger(false); - bool didLog = false; + var didLog = false; logger.LogError(l => (didLog = true).ToString()); logger.LogWarning(l => (didLog = true).ToString()); logger.LogInfo(l => (didLog = true).ToString()); @@ -37,7 +37,7 @@ public void ShouldRememberLogFilterChanges() [DataRow(LogLevel.Always, true)] public void ShouldLogExceptionWhenFilteredToError(LogLevel filter, bool expected) { - bool didLog = false; + var didLog = false; this.debugLogger.LogLevelFilter = filter; this.debugLogger.LogError(new Exception("Test Exception"), l => (didLog = true).ToString()); Assert.AreEqual(expected, didLog); @@ -50,7 +50,7 @@ public void ShouldLogExceptionWhenFilteredToError(LogLevel filter, bool expected [DataRow(LogLevel.Always, true)] public void ShouldLogError(LogLevel filter, bool expected) { - bool didLog = false; + var didLog = false; this.debugLogger.LogLevelFilter = filter; this.debugLogger.LogError(l => (didLog = true).ToString()); Assert.AreEqual(expected, didLog); @@ -63,7 +63,7 @@ public void ShouldLogError(LogLevel filter, bool expected) [DataRow(LogLevel.Always, true)] public void ShouldLogWarning(LogLevel filter, bool expected) { - bool didLog = false; + var didLog = false; this.debugLogger.LogLevelFilter = filter; this.debugLogger.LogWarning(l => (didLog = true).ToString()); Assert.AreEqual(expected, didLog); @@ -76,7 +76,7 @@ public void ShouldLogWarning(LogLevel filter, bool expected) [DataRow(LogLevel.Always, true)] public void ShouldLogInfo(LogLevel filter, bool expected) { - bool didLog = false; + var didLog = false; this.debugLogger.LogLevelFilter = filter; this.debugLogger.LogInfo(l => (didLog = true).ToString()); Assert.AreEqual(expected, didLog); @@ -89,7 +89,7 @@ public void ShouldLogInfo(LogLevel filter, bool expected) [DataRow(LogLevel.Always, true)] public void ShouldLogAlways(LogLevel filter, bool expected) { - bool didLog = false; + var didLog = false; this.debugLogger.LogLevelFilter = filter; this.debugLogger.LogAlways(l => (didLog = true).ToString()); Assert.AreEqual(expected, didLog); diff --git a/BudgetAnalyser.Engine.UnitTest/DefaultIoCRegistrationsTest.cs b/BudgetAnalyser.Engine.UnitTest/DefaultIoCRegistrationsTest.cs index e470a8c0..41a76f63 100644 --- a/BudgetAnalyser.Engine.UnitTest/DefaultIoCRegistrationsTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/DefaultIoCRegistrationsTest.cs @@ -21,11 +21,7 @@ public class DefaultIoCRegistrationsTest /// The interface exclude list. /// This is used to exclude interfaces that do not need to be registered with the IoC container. /// - private List ExemptionList - { - get - { - return new List + private List ExemptionList => new List { typeof(ILogger), // Logger is instantiated with a custom registration. typeof(IModelValidate), // Used to indicate support for standard validation. @@ -39,8 +35,6 @@ private List ExemptionList typeof(IEnvironmentFolders), // Must be implemented in the UI project as it is platform dependent. typeof(IPersistentApplicationStateObject) // Used to consistently implement a grain or persistent application data. This does not need to be registered with an IoC container. }; - } - } [TestMethod] [Description("This test is not a functional test, but is designed to detect new interfaces that have not been assigned to a concrete type with the AutoRegisterWithIoCAttribute or added to" + @@ -49,16 +43,20 @@ public void EnsureAllInterfacesAreRegisteredWithIoC() { try { - List dependencies = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(typeof(StatementModel).Assembly).ToList(); + var dependencies = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(typeof(StatementModel).Assembly).ToList(); dependencies.AddRange(DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(typeof(SecureStringCredentialStore).Assembly)); - IEnumerable interfaces = typeof(StatementModel).Assembly.GetTypes().Where(t => t.IsInterface); + var interfaces = typeof(StatementModel).Assembly.GetTypes().Where(t => t.IsInterface); - List exemptionListNames = ExemptionList.Select(e => e.FullName).ToList(); + var exemptionListNames = ExemptionList.Select(e => e.FullName).ToList(); foreach (var interfaceType in interfaces.Except(ExemptionList)) { Console.Write("Interface: {0}", interfaceType.Name); - if (exemptionListNames.Contains(interfaceType.FullName)) continue; + if (exemptionListNames.Contains(interfaceType.FullName)) + { + continue; + } + if (!dependencies.Any(d => d.AdditionalRegistrationType == interfaceType || IsSelfRegistered(interfaceType, d))) { Assert.Fail($"Interface: {interfaceType.FullName} is not registered."); @@ -81,7 +79,7 @@ public void EnsureAllInterfacesAreRegisteredWithIoC() public void ProcessPropertyInjection_ShouldBeAbleToAssignLoggerToProperty() { var logger = new FakeLogger(); - IEnumerable result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); + var result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); result.First().PropertyInjectionAssignment(logger); Assert.AreSame(logger, AutoRegisterWithIoCProcessorPropertyInjectionTestSource.Logger); @@ -90,14 +88,14 @@ public void ProcessPropertyInjection_ShouldBeAbleToAssignLoggerToProperty() [TestMethod] public void ProcessPropertyInjection_ShouldFindOnePropertyInjectionDependency() { - IEnumerable result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); + var result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); Assert.AreEqual(1, result.Count()); } [TestMethod] public void ProcessPropertyInjection_ShouldFindStaticClassWithILoggerProperty() { - IEnumerable result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); + var result = DefaultIoCRegistrations.ProcessPropertyInjection(GetType().Assembly); Assert.AreEqual(typeof(ILogger), result.First().DependencyRequired); } @@ -105,7 +103,7 @@ public void ProcessPropertyInjection_ShouldFindStaticClassWithILoggerProperty() [ExpectedException(typeof(ArgumentNullException))] public void ProcessPropertyInjectionShouldThrowGivenNullAssembly() { - IEnumerable result = DefaultIoCRegistrations.ProcessPropertyInjection(null); + var result = DefaultIoCRegistrations.ProcessPropertyInjection(null); result.Any(); Assert.Fail(); } @@ -113,7 +111,7 @@ public void ProcessPropertyInjectionShouldThrowGivenNullAssembly() [TestMethod] public void RegisterAutoMappings_ShouldReturnFakeLoggerRegistration() { - IEnumerable result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(GetType().Assembly); + var result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(GetType().Assembly); var loggerRegistration = result.Last(); Assert.AreEqual(typeof(FakeLogger), loggerRegistration.DependencyRequired); Assert.IsTrue(loggerRegistration.IsSingleInstance); @@ -123,7 +121,7 @@ public void RegisterAutoMappings_ShouldReturnFakeLoggerRegistration() [TestMethod] public void RegisterAutoMappings_ShouldReturnTwoGivenThisAssembly() { - IEnumerable result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(GetType().Assembly); + var result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(GetType().Assembly); Assert.AreEqual(2, result.Count()); } @@ -131,7 +129,7 @@ public void RegisterAutoMappings_ShouldReturnTwoGivenThisAssembly() [ExpectedException(typeof(ArgumentNullException))] public void RegisterAutoMappings_ShouldThrowGivenNullAssembly() { - IEnumerable result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(null); + var result = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(null); result.ToList(); @@ -145,10 +143,13 @@ public void TestInitialise() private bool IsSelfRegistered(Type interfaceType, DependencyRegistrationRequirement d) { - if (interfaceType == d.DependencyRequired) return true; + if (interfaceType == d.DependencyRequired) + { + return true; + } - Type[] implementedInterfaces = d.DependencyRequired.GetInterfaces(); + var implementedInterfaces = d.DependencyRequired.GetInterfaces(); return implementedInterfaces.Contains(interfaceType); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Encryption/CredentialStoreTest.cs b/BudgetAnalyser.Engine.UnitTest/Encryption/CredentialStoreTest.cs index 9a82ee46..2716da20 100644 --- a/BudgetAnalyser.Engine.UnitTest/Encryption/CredentialStoreTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Encryption/CredentialStoreTest.cs @@ -29,7 +29,7 @@ public void RetrievePasskey_ShouldReturnNull_GivenEmptyWasStored() { this.subject.SetPasskey(CreateSecureString("")); - var result = (SecureString) this.subject.RetrievePasskey(); + var result = (SecureString)this.subject.RetrievePasskey(); Assert.IsNull(result); } @@ -37,7 +37,7 @@ public void RetrievePasskey_ShouldReturnNull_GivenEmptyWasStored() [TestMethod] public void RetrievePasskey_ShouldReturnNull_GivenNullWasStored() { - var result = (SecureString) this.subject.RetrievePasskey(); + var result = (SecureString)this.subject.RetrievePasskey(); Assert.IsNull(result); } @@ -57,7 +57,7 @@ public void RetrievePasskey_ShouldStoreForRetrieval_GivenTextValue() { this.subject.SetPasskey(CreateSecureString("Foo")); - var result = (SecureString) this.subject.RetrievePasskey(); + var result = (SecureString)this.subject.RetrievePasskey(); Assert.AreEqual(3, result.Length); } @@ -93,4 +93,4 @@ internal static SecureString CreateSecureString(string text) return securedText; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Encryption/EncryptedLocalDiskReaderWriterTest.cs b/BudgetAnalyser.Engine.UnitTest/Encryption/EncryptedLocalDiskReaderWriterTest.cs index c1a76c4a..b7a25dc2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Encryption/EncryptedLocalDiskReaderWriterTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Encryption/EncryptedLocalDiskReaderWriterTest.cs @@ -30,7 +30,7 @@ public void IsValidAlphaNumericWithPunctuation_ShouldBeFalse_GivenNull() public void IsValidAlphaNumericWithPunctuation_ShouldBeFalse_GivenTextStartsWithNull() { var bytes = new byte[] { 0x00000000, 0x00000000 }; - char[] chars = Encoding.UTF8.GetChars(bytes); + var chars = Encoding.UTF8.GetChars(bytes); var result = this.subject.IsValidAlphaNumericWithPunctuation(new string(chars)); Assert.IsFalse(result); } @@ -45,7 +45,7 @@ public void IsValidAlphaNumericWithPunctuation_ShouldBeTrue_Given1Char() [TestMethod] public void IsValidAlphaNumericWithPunctuation_ShouldBeTrue_GivenAnyNumber() { - IEnumerable number = Enumerable.Range(0, 10); + var number = Enumerable.Range(0, 10); var text = string.Concat(number); var result = this.subject.IsValidAlphaNumericWithPunctuation(text); Assert.IsTrue(result); @@ -204,4 +204,4 @@ public async Task WriteToDiskAsync_ShouldThrow_GivenNullFileName() Assert.Fail(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Encryption/LocalDiskReaderWriterSelectorTest.cs b/BudgetAnalyser.Engine.UnitTest/Encryption/LocalDiskReaderWriterSelectorTest.cs index 1f4c3bf5..0ad3bf4a 100644 --- a/BudgetAnalyser.Engine.UnitTest/Encryption/LocalDiskReaderWriterSelectorTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Encryption/LocalDiskReaderWriterSelectorTest.cs @@ -78,4 +78,4 @@ public void SelectReaderWriter_ShouldThrow_GivenOnlyUnprotectedRegisteredAndTrue Assert.Fail(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Global.cs b/BudgetAnalyser.Engine.UnitTest/Global.cs index d87b1abf..84e3f79d 100644 --- a/BudgetAnalyser.Engine.UnitTest/Global.cs +++ b/BudgetAnalyser.Engine.UnitTest/Global.cs @@ -10,4 +10,4 @@ public static void AssemblyInitialise(TestContext context) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/GlobalFilterCriteriaTest.cs b/BudgetAnalyser.Engine.UnitTest/GlobalFilterCriteriaTest.cs index 6df8f6e0..f3c780b9 100644 --- a/BudgetAnalyser.Engine.UnitTest/GlobalFilterCriteriaTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/GlobalFilterCriteriaTest.cs @@ -13,8 +13,8 @@ public class GlobalFilterCriteriaTest [TestMethod] public void CheckReferenceEquality() { - GlobalFilterCriteria subject1 = CreateSubject_StandardPayMonth(); - GlobalFilterCriteria subject2 = subject1; + var subject1 = CreateSubject_StandardPayMonth(); + var subject2 = subject1; Assert.AreEqual(subject1, subject2); Assert.IsFalse(subject1 != subject2); @@ -27,8 +27,8 @@ public void CheckReferenceEquality() [TestMethod] public void CheckReferenceInequality() { - GlobalFilterCriteria subject1 = CreateSubject_StandardPayMonth(); - GlobalFilterCriteria subject2 = CreateSubject_NotFiltered(); + var subject1 = CreateSubject_StandardPayMonth(); + var subject2 = CreateSubject_NotFiltered(); Assert.AreNotEqual(subject1, subject2); Assert.IsTrue(subject1 != subject2); @@ -74,8 +74,8 @@ public void MinDateShouldGetTransalatedToNull() [TestMethod] public void TwoInstancesWithDifferentValuesAreNotEqual() { - GlobalFilterCriteria subject1 = CreateSubject_StandardPayMonth(); - GlobalFilterCriteria subject2 = CreateSubject_StandardPayMonthAndVisaFilter(); + var subject1 = CreateSubject_StandardPayMonth(); + var subject2 = CreateSubject_StandardPayMonthAndVisaFilter(); Assert.AreNotEqual(subject1, subject2); Assert.IsTrue(subject1 != subject2); @@ -88,8 +88,8 @@ public void TwoInstancesWithDifferentValuesAreNotEqual() [TestMethod] public void TwoInstancesWithSameValuesShouldHaveSameEqualityHash() { - GlobalFilterCriteria subject1 = CreateSubject_StandardPayMonth(); - GlobalFilterCriteria subject2 = CreateSubject_StandardPayMonth(); + var subject1 = CreateSubject_StandardPayMonth(); + var subject2 = CreateSubject_StandardPayMonth(); Assert.AreEqual(subject1.SignificantDataChangeHash(), subject2.SignificantDataChangeHash()); Assert.IsFalse(subject1.SignificantDataChangeHash() != subject2.SignificantDataChangeHash()); @@ -142,7 +142,7 @@ public void ValidateShouldThrowGivenNullValidationMessages() [TestMethod] public void WhenNotFilteredClearedShouldBeTrue() { - GlobalFilterCriteria subject1 = CreateSubject_NotFiltered(); + var subject1 = CreateSubject_NotFiltered(); Assert.IsTrue(subject1.Cleared); } @@ -173,4 +173,4 @@ private GlobalFilterCriteria CreateSubject_StandardPayMonthAndVisaFilter() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Helper/BudgetModelHelper.cs b/BudgetAnalyser.Engine.UnitTest/Helper/BudgetModelHelper.cs index bc864595..021dacd3 100644 --- a/BudgetAnalyser.Engine.UnitTest/Helper/BudgetModelHelper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Helper/BudgetModelHelper.cs @@ -14,10 +14,12 @@ public static void Output(this IBudgetCurrencyContext instance) if (instance.BudgetActive) { Debug.WriteLine("Budget is ACTIVE."); - } else if (instance.BudgetArchived) + } + else if (instance.BudgetArchived) { Debug.WriteLine("Budget is ARCHIVED."); - } else if (instance.BudgetInFuture) + } + else if (instance.BudgetInFuture) { Debug.WriteLine("Budget is FUTURE."); } @@ -33,9 +35,9 @@ public static void Output(this BudgetModel instance, bool includeTitle = true) } Debug.WriteLine(@" Incomes Expenses"); Debug.WriteLine(@" =================================================================="); - int incomeIndex = 0; + var incomeIndex = 0; var incomeArray = instance.Incomes.ToArray(); - foreach (Expense expense in instance.Expenses) + foreach (var expense in instance.Expenses) { if (incomeIndex <= incomeArray.GetUpperBound(0)) { diff --git a/BudgetAnalyser.Engine.UnitTest/Helper/EmbeddedResourceHelper.cs b/BudgetAnalyser.Engine.UnitTest/Helper/EmbeddedResourceHelper.cs index 2ad12f28..2e7aa1ae 100644 --- a/BudgetAnalyser.Engine.UnitTest/Helper/EmbeddedResourceHelper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Helper/EmbeddedResourceHelper.cs @@ -23,7 +23,7 @@ public static class EmbeddedResourceHelper public static T ExtractEmbeddedResourceAsXamlObject(this Assembly assembly, string resourceName, bool outputXaml = false) { var stringData = assembly.ExtractEmbeddedResourceAsText(resourceName, outputXaml); - return (T) XamlServices.Parse(stringData); + return (T)XamlServices.Parse(stringData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Helper/LedgerBookHelper.cs b/BudgetAnalyser.Engine.UnitTest/Helper/LedgerBookHelper.cs index 790e0d67..72b19ab0 100644 --- a/BudgetAnalyser.Engine.UnitTest/Helper/LedgerBookHelper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Helper/LedgerBookHelper.cs @@ -27,7 +27,7 @@ public static void Output(this LedgerBook book, bool outputTransactions = false) Debug.WriteLine($"Filename: {book.StorageKey}"); Debug.WriteLine($"Modified: {book.Modified}"); Debug.Write("Date "); - Dictionary ledgerOrder = LedgerOrder(book); + var ledgerOrder = LedgerOrder(book); OutputReconciliationHeader(); @@ -70,7 +70,7 @@ public static void Output(this LedgerEntryLine line, IDictionary e.LedgerBucket.BudgetBucket)) { - var tab = new string(' ', 11 + 18 * ledgerOrder[entry.LedgerBucket.BudgetBucket]); + var tab = new string(' ', 11 + (18 * ledgerOrder[entry.LedgerBucket.BudgetBucket])); foreach (var transaction in entry.Transactions) { Debug.WriteLine( @@ -79,7 +79,7 @@ public static void Output(this LedgerEntryLine line, IDictionary= 0 ? (transaction.Amount.ToString("N") + "Cr").PadLeft(8) : (transaction.Amount.ToString("N") + "Dr").PadLeft(16), transaction.Id, - transaction.AutoMatchingReference, + transaction.AutoMatchingReference, transaction.Narrative.Truncate(30)); } } @@ -118,14 +118,17 @@ public static void Output(this LedgerBookDto book, bool outputTransactions = fal if (outputTransactions) { foreach (var entry in line.Entries) - foreach (var transaction in entry.Transactions) { - Debug.WriteLine( - " {0} {1} {2}", - entry.BucketCode.PadRight(6), - transaction.Amount > 0 ? (transaction.Amount.ToString("N") + "Cr").PadLeft(8) : (transaction.Amount.ToString("N") + "Dr").PadLeft(16), - transaction.Narrative); + foreach (var transaction in entry.Transactions) + { + Debug.WriteLine( + " {0} {1} {2}", + entry.BucketCode.PadRight(6), + transaction.Amount > 0 ? (transaction.Amount.ToString("N") + "Cr").PadLeft(8) : (transaction.Amount.ToString("N") + "Dr").PadLeft(16), + transaction.Narrative); + } } + Debug.WriteLine("===================================================================================================================="); } } @@ -149,4 +152,4 @@ private static void OutputReconciliationHeader() Debug.WriteLine("=============================================================================================================================================="); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Helper/StatementModelHelper.cs b/BudgetAnalyser.Engine.UnitTest/Helper/StatementModelHelper.cs index ee977054..c866c2f3 100644 --- a/BudgetAnalyser.Engine.UnitTest/Helper/StatementModelHelper.cs +++ b/BudgetAnalyser.Engine.UnitTest/Helper/StatementModelHelper.cs @@ -12,7 +12,7 @@ public static void Output(this StatementModel instance, DateTime startDate) { Debug.WriteLine("Date Description Bucket Reference1 Reference2 Amount Account Id"); Debug.WriteLine("====================================================================================================================================="); - foreach (Transaction transaction in instance.AllTransactions.Where(t => t.Date >= startDate).OrderBy(t => t.Date)) + foreach (var transaction in instance.AllTransactions.Where(t => t.Date >= startDate).OrderBy(t => t.Date)) { Debug.WriteLine( "{0} {1} {2} {3} {4} {5} {6} {7}", @@ -31,4 +31,4 @@ public static void Output(this StatementModel instance, DateTime startDate) Debug.WriteLine(string.Empty); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/BankBalanceToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/BankBalanceToDtoMapperTest.cs index 3924817a..3e7e36c8 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/BankBalanceToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/BankBalanceToDtoMapperTest.cs @@ -27,8 +27,8 @@ public void ShouldMapBankAccount() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_BankBalanceDto_BankBalance(new InMemoryAccountTypeRepository()); + var subject = new MapperBankBalanceDto2BankBalance(new InMemoryAccountTypeRepository()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/CreditLedgerTransactionTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/CreditLedgerTransactionTest.cs index 6bbde287..0aa7d90b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/CreditLedgerTransactionTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/CreditLedgerTransactionTest.cs @@ -10,7 +10,7 @@ public class CreditLedgerTransactionTest [TestMethod] public void ConstructWithGuidShouldSetId() { - Guid id = Guid.NewGuid(); + var id = Guid.NewGuid(); var subject = new CreditLedgerTransaction(id); Assert.AreEqual(id, subject.Id); @@ -21,7 +21,7 @@ public void WithAmount50ShouldCreateACreditOf50() { var subject = new CreditLedgerTransaction(); - LedgerTransaction result = subject.WithAmount(50); + var result = subject.WithAmount(50); Assert.AreEqual(50M, result.Amount); } @@ -31,7 +31,7 @@ public void WithAmount50ShouldReturnSameObjectForChaining() { var subject = new CreditLedgerTransaction(); - LedgerTransaction result = subject.WithAmount(50); + var result = subject.WithAmount(50); Assert.AreSame(subject, result); } @@ -41,9 +41,9 @@ public void WithAmountMinus50ShouldCreateADebitOf50() { var subject = new CreditLedgerTransaction(); - LedgerTransaction result = subject.WithAmount(-50); + var result = subject.WithAmount(-50); Assert.AreEqual(-50M, result.Amount); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToBankBalanceMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToBankBalanceMapperTest.cs index 69f6d46a..8c41ade4 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToBankBalanceMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToBankBalanceMapperTest.cs @@ -11,17 +11,11 @@ public class DtoToBankBalanceMapperTest { private BankBalance Result { get; set; } - private BankBalanceDto TestData + private BankBalanceDto TestData => new BankBalanceDto { - get - { - return new BankBalanceDto - { - Account = StatementModelTestData.ChequeAccount.Name, - Balance = 44552.44M - }; - } - } + Account = StatementModelTestData.ChequeAccount.Name, + Balance = 44552.44M + }; [TestMethod] public void ShouldMapAmount() @@ -38,8 +32,8 @@ public void ShouldMapBankAccount() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_BankBalanceDto_BankBalance(new InMemoryAccountTypeRepository()); + var subject = new MapperBankBalanceDto2BankBalance(new InMemoryAccountTypeRepository()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest.cs index 19b28989..7d53d871 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest.cs @@ -41,7 +41,7 @@ public void NullTransactionTypeShouldThrow() } catch (ArgumentNullException) { - return; + return; } Assert.Fail(); @@ -51,14 +51,14 @@ public void NullTransactionTypeShouldThrow() [Description("A test designed to break when new propperties are added to the LedgerBook. This is a trigger to update the mappers.")] public void NumberOfLedgerBookPropertiesShouldBe6() { - int domainProperties = typeof(LedgerBook).CountProperties(); + var domainProperties = typeof(LedgerBook).CountProperties(); Assert.AreEqual(6, domainProperties); } [TestMethod] public void ShouldMapCorrectNumberOfLedgers() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(3, result.Ledgers.Count()); } @@ -66,28 +66,28 @@ public void ShouldMapCorrectNumberOfLedgers() [TestMethod] public void ShouldMapCorrectNumberOfLineEntries() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().Entries.Count, result.Reconciliations.First().Entries.Count()); } [TestMethod] public void ShouldMapCorrectNumberOfLineEntryTransactions() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().Entries.First().Transactions.Count, result.Reconciliations.First().Entries.First().Transactions.Count()); } [TestMethod] public void ShouldMapCorrectNumberOfLines() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.Count, result.Reconciliations.Count()); } [TestMethod] public void ShouldMapFileName() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.StorageKey, result.StorageKey); Assert.IsNotNull(result.StorageKey); } @@ -97,7 +97,7 @@ public void ShouldRepopulateLedgerCollectionFromReconciliations_GivenDtoContains { TestData.Ledgers.Clear(); var model = ArrangeAndAct(); - + // There should be three ledgers in the book because it is deemed invalid for there to be NO ledgers at all from the persistence file. If this occurs it is repopulated based on the // reconciliations and this will be persisted next save. Assert.AreEqual(3, model.Ledgers.Count()); @@ -108,7 +108,7 @@ public void ShouldIgnoreAndContinueIfLedgerIsNotDeclared_GivenOneLedgerBucketIsM { TestData.Ledgers.RemoveAt(0); var model = ArrangeAndAct(); - + // There should be three ledgers in the book because it is deemed invalid for there to be NO ledgers at all from the persistence file. If this occurs it is repopulated based on the // reconciliations and this will be persisted next save. Assert.AreEqual(2, model.Ledgers.Count()); @@ -117,15 +117,15 @@ public void ShouldIgnoreAndContinueIfLedgerIsNotDeclared_GivenOneLedgerBucketIsM [TestMethod] public void ShouldMapLedgerBucketsOnLedgerEntriesWithAccountNotNull() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsFalse(result.Reconciliations.SelectMany(e => e.Entries).Any(e => e.LedgerBucket is null)); } [TestMethod] public void ShouldMapLedgerBucketsWithNoDuplicateInstances() { - LedgerBook result = ArrangeAndAct(); - IEnumerable ledgerBuckets = result.Reconciliations + var result = ArrangeAndAct(); + var ledgerBuckets = result.Reconciliations .SelectMany(e => e.Entries) .Select(e => e.LedgerBucket) .Union(result.Ledgers) @@ -138,8 +138,8 @@ public void ShouldMapLedgerBucketsWithNoDuplicateInstances() public void ShouldMapLineBalanceAdjustments() { TestData = LedgerBookDtoTestData.TestData2(); - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(TestData.Reconciliations.First().BankBalanceAdjustments.Sum(a => a.Amount), subject.TotalBalanceAdjustments); Assert.AreNotEqual(0, subject.BankBalanceAdjustments.Count()); @@ -148,8 +148,8 @@ public void ShouldMapLineBalanceAdjustments() [TestMethod] public void ShouldMapLineBankBalance() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(TestData.Reconciliations.First().BankBalance, subject.TotalBankBalance); Assert.AreNotEqual(0, subject.TotalBankBalance); } @@ -157,8 +157,8 @@ public void ShouldMapLineBankBalance() [TestMethod] public void ShouldMapLineDate() { - LedgerBook result = ArrangeAndAct(); - DateTime subject = result.Reconciliations.First().Date; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Date; Assert.AreEqual(TestData.Reconciliations.First().Date, subject); Assert.AreNotEqual(DateTime.MinValue, subject); } @@ -166,8 +166,8 @@ public void ShouldMapLineDate() [TestMethod] public void ShouldMapLineEntryBucketCode() { - LedgerBook result = ArrangeAndAct(); - string subject = result.Reconciliations.First().Entries.First().LedgerBucket.BudgetBucket.Code; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First().LedgerBucket.BudgetBucket.Code; Assert.AreEqual(TestData.Reconciliations.First().Entries.First().BucketCode, subject); Assert.IsNotNull(subject); } @@ -175,8 +175,8 @@ public void ShouldMapLineEntryBucketCode() [TestMethod] public void ShouldMapLineEntryTransactionAmount() { - LedgerBook result = ArrangeAndAct(); - decimal subject = result.Reconciliations.First().Entries.First().Transactions.First().Amount; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First().Transactions.First().Amount; Assert.AreEqual(TestData.Reconciliations.First().Entries.First().Transactions.First().Amount, subject); Assert.AreNotEqual(0, subject); } @@ -184,8 +184,8 @@ public void ShouldMapLineEntryTransactionAmount() [TestMethod] public void ShouldMapLineEntryTransactionId() { - LedgerBook result = ArrangeAndAct(); - Guid subject = result.Reconciliations.First().Entries.First().Transactions.First().Id; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First().Transactions.First().Id; Assert.AreEqual(TestData.Reconciliations.First().Entries.First().Transactions.First().Id, subject); Assert.AreNotEqual(Guid.Empty, subject); } @@ -193,8 +193,8 @@ public void ShouldMapLineEntryTransactionId() [TestMethod] public void ShouldMapLineEntryTransactionNarrative() { - LedgerBook result = ArrangeAndAct(); - string subject = result.Reconciliations.First().Entries.First().Transactions.First().Narrative; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First().Transactions.First().Narrative; Assert.AreEqual(TestData.Reconciliations.First().Entries.First().Transactions.First().Narrative, subject); Assert.IsNotNull(subject); } @@ -202,8 +202,8 @@ public void ShouldMapLineEntryTransactionNarrative() [TestMethod] public void ShouldMapLineEntryTransactionType() { - LedgerBook result = ArrangeAndAct(); - string subject = result.Reconciliations.First().Entries.First().Transactions.First().GetType().FullName; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First().Transactions.First().GetType().FullName; Assert.AreEqual(TestData.Reconciliations.First().Entries.First().Transactions.First().TransactionType, subject); Assert.IsNotNull(subject); } @@ -211,8 +211,8 @@ public void ShouldMapLineEntryTransactionType() [TestMethod] public void ShouldMapLineRemarks() { - LedgerBook result = ArrangeAndAct(); - string subject = result.Reconciliations.First().Remarks; + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Remarks; Assert.AreEqual(TestData.Reconciliations.First().Remarks, subject); Assert.IsNotNull(subject); } @@ -220,7 +220,7 @@ public void ShouldMapLineRemarks() [TestMethod] public void ShouldMapModifiedDate() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Modified, result.Modified); Assert.AreNotEqual(DateTime.MinValue, result.Modified); } @@ -228,7 +228,7 @@ public void ShouldMapModifiedDate() [TestMethod] public void ShouldMapName() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Name, result.Name); Assert.IsNotNull(result.Name); } @@ -243,8 +243,8 @@ private LedgerBook ArrangeAndAct() { var bucketRepo = new BucketBucketRepoAlwaysFind(); var accountRepo = new InMemoryAccountTypeRepository(); - var mapper = new Mapper_LedgerBookDto_LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); + var mapper = new MapperLedgerBookDto2LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); return mapper.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest2.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest2.cs index b0f8965d..54c7cb9b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest2.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBookMapperTest2.cs @@ -46,8 +46,8 @@ public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); var bucketRepo = new BucketBucketRepoAlwaysFind(); - var subject = new Mapper_LedgerBookDto_LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); + var subject = new MapperLedgerBookDto2LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBucketMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBucketMapperTest.cs index 0af9b869..a9f15134 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBucketMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerBucketMapperTest.cs @@ -12,17 +12,11 @@ public class DtoToLedgerBucketMapperTest { private LedgerBucket Result { get; set; } - private LedgerBucketDto TestData + private LedgerBucketDto TestData => new LedgerBucketDto { - get - { - return new LedgerBucketDto - { - BucketCode = TestDataConstants.RegoBucketCode, - StoredInAccount = TestDataConstants.ChequeAccountName - }; - } - } + BucketCode = TestDataConstants.RegoBucketCode, + StoredInAccount = TestDataConstants.ChequeAccountName + }; [TestMethod] public void ShouldMapBankAccount() @@ -41,8 +35,8 @@ public void TestInitialise() { var bucketRepo = new BucketBucketRepoAlwaysFind(); var accountRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerBucketDto_LedgerBucket(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo)); + var subject = new MapperLedgerBucketDto2LedgerBucket(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo)); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryLineMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryLineMapperTest.cs index a2bd5446..703c90bf 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryLineMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryLineMapperTest.cs @@ -18,7 +18,7 @@ private LedgerEntryLineDto TestData { get { - LedgerBookDto book = LedgerBookDtoTestData.TestData3(); + var book = LedgerBookDtoTestData.TestData3(); return book.Reconciliations.First(); } } @@ -87,8 +87,8 @@ public void ShouldSetIsNewToFalse() public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerEntryLineDto_LedgerEntryLine(accountRepo, new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory()); + var subject = new MapperLedgerEntryLineDto2LedgerEntryLine(accountRepo, new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryMapperTest.cs index 179b3c76..321a0afa 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerEntryMapperTest.cs @@ -17,20 +17,17 @@ public class DtoToLedgerEntryMapperTest private LedgerEntry Control { get; set; } private LedgerEntry Result { get; set; } - private LedgerEntryDto TestData - { - get - { + private LedgerEntryDto TestData => /* - - - - - - - - */ - return new LedgerEntryDto + + + + + + + + */ + new LedgerEntryDto { Balance = 52.32M, BucketCode = TestDataConstants.PowerBucketCode, @@ -54,8 +51,6 @@ private LedgerEntryDto TestData } } }; - } - } [TestMethod] public void ShouldMapBalance() @@ -91,11 +86,11 @@ public void ShouldSetIsNewToFalse() public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerEntryDto_LedgerEntry(new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory(), accountRepo); + var subject = new MapperLedgerEntryDto2LedgerEntry(new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory(), accountRepo); Result = subject.ToModel(TestData); - LedgerBook book = LedgerBookTestData.TestData2(); + var book = LedgerBookTestData.TestData2(); Control = book.Reconciliations.First(l => l.Date == new DateTime(2013, 08, 15)).Entries.First(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerTransactionMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerTransactionMapperTest.cs index 741fcaca..3cf88732 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerTransactionMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/DtoToLedgerTransactionMapperTest.cs @@ -37,7 +37,7 @@ public void ShouldMapAccountTypeForBalanceAdjustmentTransaction() Account = StatementModelTestData.ChequeAccount.Name, TransactionType = typeof(BankBalanceAdjustmentTransaction).FullName }; - var subject = new Mapper_LedgerTransactionDto_LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); + var subject = new MapperLedgerTransactionDto2LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); Result = subject.ToModel(TestData); Assert.AreEqual(StatementModelTestData.ChequeAccount.Name, ((BankBalanceAdjustmentTransaction)Result).BankAccount.Name); @@ -70,8 +70,8 @@ public void ShouldMapTransactionType() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_LedgerTransactionDto_LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); + var subject = new MapperLedgerTransactionDto2LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookDtoTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookDtoTest.cs index 2163ffb3..c0a06b0d 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookDtoTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookDtoTest.cs @@ -10,17 +10,17 @@ public class LedgerBookDtoTest [TestMethod] public void OutputLedgerBookTestData1() { - LedgerBookDto testData = LedgerBookDtoTestData.TestData1(); - string serialised = XamlServices.Save(testData); + var testData = LedgerBookDtoTestData.TestData1(); + var serialised = XamlServices.Save(testData); Console.WriteLine(serialised); } [TestMethod] public void OutputLedgerBookTestData2() { - LedgerBookDto testData = LedgerBookDtoTestData.TestData2(); - string serialised = XamlServices.Save(testData); + var testData = LedgerBookDtoTestData.TestData2(); + var serialised = XamlServices.Save(testData); Console.WriteLine(serialised); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookRepositoryTest.cs index 6695fd72..33a9d3f2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookRepositoryTest.cs @@ -43,7 +43,7 @@ public async Task DemoBookFileChecksum_ShouldNotChange_WhenLoadAndSave() LedgerBookDto reserialisedDto = null; subject.SaveDtoToDiskOverride = bookDto => reserialisedDto = bookDto; - + var book = await subject.LoadAsync(TestDataConstants.DemoLedgerBookFileName, false); predeserialiseDto.Output(true); @@ -62,9 +62,9 @@ public async Task SaveAsync_ShouldHaveACheckSumOf8435_GivenLedgerBookTestData2() await subject.SaveAsync(LedgerBookTestData.TestData2(), "Foo.xml", false); var serialisedData = subject.SerialisedData; - int checksumPosition = serialisedData.IndexOf("CheckSum=\"", StringComparison.OrdinalIgnoreCase); - int checksumLength = serialisedData.IndexOf('"', checksumPosition + 11) - checksumPosition; - string serialisedCheckSum = serialisedData.Substring(checksumPosition + 10, checksumLength - 10); + var checksumPosition = serialisedData.IndexOf("CheckSum=\"", StringComparison.OrdinalIgnoreCase); + var checksumLength = serialisedData.IndexOf('"', checksumPosition + 11) - checksumPosition; + var serialisedCheckSum = serialisedData.Substring(checksumPosition + 10, checksumLength - 10); Assert.AreEqual(8435.06, double.Parse(serialisedCheckSum)); } @@ -181,10 +181,10 @@ public async Task Save_ShouldSaveTheXmlFile() var fileName = @"CompleteSmellyFoo.xml"; XamlOnDiskLedgerBookRepository subject = CreateSubject(); - + var testData = LedgerBookTestData.TestData2(); await subject.SaveAsync(testData, fileName, false); - + this.mockReaderWriter.Verify(m => m.WriteToDiskAsync(It.IsAny(), It.IsAny())); } @@ -192,7 +192,7 @@ public async Task Save_ShouldSaveTheXmlFile() public async Task SavingAndLoading_ShouldProduceTheSameCheckSum() { var subject1 = CreateSubject(); - + await subject1.SaveAsync(LedgerBookTestData.TestData2(), "Foo2.xml", false); var serialisedData = subject1.SerialisedData; @@ -207,9 +207,9 @@ public async Task SavingAndLoading_ShouldProduceTheSameCheckSum() await subject2.LoadAsync("foo", false); bookDto = subject2.LedgerBookDto; - int checksumPosition = serialisedData.IndexOf("CheckSum=\"", StringComparison.OrdinalIgnoreCase); - int checksumLength = serialisedData.IndexOf('"', checksumPosition + 11) - checksumPosition; - string serialisedCheckSum = serialisedData.Substring(checksumPosition + 10, checksumLength - 10); + var checksumPosition = serialisedData.IndexOf("CheckSum=\"", StringComparison.OrdinalIgnoreCase); + var checksumLength = serialisedData.IndexOf('"', checksumPosition + 11) - checksumPosition; + var serialisedCheckSum = serialisedData.Substring(checksumPosition + 10, checksumLength - 10); Assert.AreEqual(double.Parse(serialisedCheckSum), bookDto.Checksum); } @@ -232,7 +232,7 @@ public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); var bucketRepo = new BucketBucketRepoAlwaysFind(); - this.mapper = new Mapper_LedgerBookDto_LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); + this.mapper = new MapperLedgerBookDto2LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); this.mockReaderWriterSelector = new Mock(); this.mockReaderWriter = new Mock(); this.mockReaderWriterSelector.Setup(m => m.SelectReaderWriter(It.IsAny())).Returns(this.mockReaderWriter.Object); @@ -254,4 +254,4 @@ private XamlOnDiskLedgerBookRepositoryTestHarness CreateSubject(bool real = fals this.mockReaderWriterSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest.cs index fb59ccf6..ea482ed5 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest.cs @@ -18,35 +18,35 @@ public class LedgerBookToDtoMapperTest [TestMethod] public void FilenameShouldBeMapped() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.StorageKey, result.StorageKey); } [TestMethod] public void FirstDatedEntryShouldHaveSameBankBalance() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().TotalBankBalance, result.Reconciliations.First().BankBalance); } [TestMethod] public void FirstDatedEntryShouldHaveSameDate() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().Date, result.Reconciliations.First().Date); } [TestMethod] public void FirstDatedEntryShouldHaveSameNumberOfBalanceAdjustments() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().BankBalanceAdjustments.Count(), result.Reconciliations.First().BankBalanceAdjustments.Count()); } [TestMethod] public void FirstDatedEntryShouldHaveSameNumberOfEntries() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.Count(), result.Reconciliations.First().Entries.Count()); @@ -55,14 +55,14 @@ public void FirstDatedEntryShouldHaveSameNumberOfEntries() [TestMethod] public void FirstDatedEntryShouldHaveSameRemarks() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.First().Remarks, result.Reconciliations.First().Remarks); } [TestMethod] public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameCredit() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().BankBalanceAdjustments.First().Amount, result.Reconciliations.First().BankBalanceAdjustments.First().Amount); @@ -71,7 +71,7 @@ public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameCredit() [TestMethod] public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameDebit() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().BankBalanceAdjustments.First().Amount, result.Reconciliations.First().BankBalanceAdjustments.First().Amount); @@ -80,7 +80,7 @@ public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameDebit() [TestMethod] public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameId() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().BankBalanceAdjustments.First().Id, result.Reconciliations.First().BankBalanceAdjustments.First().Id); @@ -89,7 +89,7 @@ public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameId() [TestMethod] public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameNarrative() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().BankBalanceAdjustments.First().Narrative, result.Reconciliations.First().BankBalanceAdjustments.First().Narrative); @@ -98,7 +98,7 @@ public void FirstDatedEntryWithFirstBalanceAdjustmentShouldHaveSameNarrative() [TestMethod] public void FirstDatedEntryWithFirstEntryShouldHaveSameBalance() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.First().Balance, result.Reconciliations.First().Entries.First().Balance); @@ -107,7 +107,7 @@ public void FirstDatedEntryWithFirstEntryShouldHaveSameBalance() [TestMethod] public void FirstDatedEntryWithFirstEntryShouldHaveSameBucketCode() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.First().LedgerBucket.BudgetBucket.Code, result.Reconciliations.First().Entries.First().BucketCode); @@ -116,7 +116,7 @@ public void FirstDatedEntryWithFirstEntryShouldHaveSameBucketCode() [TestMethod] public void FirstDatedEntryWithFirstEntryShouldHaveSameNumberOfTransactions() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.First().Transactions.Count(), result.Reconciliations.First().Entries.First().Transactions.Count()); @@ -125,7 +125,7 @@ public void FirstDatedEntryWithFirstEntryShouldHaveSameNumberOfTransactions() [TestMethod] public void FirstDatedEntryWithFirstEntryWithFirstTransactionsShouldHaveSameAmount() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.First().Transactions.First().Amount, result.Reconciliations.First().Entries.First().Transactions.First().Amount); @@ -134,7 +134,7 @@ public void FirstDatedEntryWithFirstEntryWithFirstTransactionsShouldHaveSameAmou [TestMethod] public void FirstDatedEntryWithFirstEntryWithFirstTransactionsShouldHaveSameNarrative() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual( TestData.Reconciliations.First().Entries.First().Transactions.First().Narrative, result.Reconciliations.First().Entries.First().Transactions.First().Narrative); @@ -143,14 +143,14 @@ public void FirstDatedEntryWithFirstEntryWithFirstTransactionsShouldHaveSameNarr [TestMethod] public void ModifiedDateShouldBeMapped() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Modified, result.Modified); } [TestMethod] public void NameShouldBeMapped() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Name, result.Name); } @@ -158,7 +158,7 @@ public void NameShouldBeMapped() [Description("A test designed to break when new propperties are added to the LedgerBookDto. This is a trigger to update the mappers.")] public void NumberOfDataLedgerBookPropertiesShouldBe7() { - int dataProperties = typeof(LedgerBookDto).CountProperties(); + var dataProperties = typeof(LedgerBookDto).CountProperties(); Assert.AreEqual(7, dataProperties); } @@ -166,7 +166,7 @@ public void NumberOfDataLedgerBookPropertiesShouldBe7() [Description("A test designed to break when new propperties are added to the LedgerEntryLineDto. This is a trigger to update the mappers.")] public void NumberOfDataLedgerLinePropertiesShouldBe6() { - int dataProperties = typeof(LedgerEntryLineDto).CountProperties(); + var dataProperties = typeof(LedgerEntryLineDto).CountProperties(); Assert.AreEqual(6, dataProperties); } @@ -174,7 +174,7 @@ public void NumberOfDataLedgerLinePropertiesShouldBe6() [Description("A test designed to break when new propperties are added to the LedgerEntryDto. This is a trigger to update the mappers.")] public void NumberOfDataLedgerPropertiesShouldBe4() { - int dataProperties = typeof(LedgerEntryDto).CountProperties(); + var dataProperties = typeof(LedgerEntryDto).CountProperties(); Assert.AreEqual(4, dataProperties); } @@ -182,14 +182,14 @@ public void NumberOfDataLedgerPropertiesShouldBe4() [Description("A test designed to break when new propperties are added to the LedgerTransactionDto. This is a trigger to update the mappers.")] public void NumberOfDataLedgerTransactionPropertiesShouldBe7() { - int dataProperties = typeof(LedgerTransactionDto).CountProperties(); + var dataProperties = typeof(LedgerTransactionDto).CountProperties(); Assert.AreEqual(7, dataProperties); } [TestMethod] public void ReconciliationsShouldHaveSameCount() { - LedgerBookDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reconciliations.Count(), result.Reconciliations.Count()); } @@ -203,8 +203,8 @@ private LedgerBookDto ArrangeAndAct() { var bucketRepo = new BucketBucketRepoAlwaysFind(); var accountRepo = new InMemoryAccountTypeRepository(); - var mapper = new Mapper_LedgerBookDto_LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); + var mapper = new MapperLedgerBookDto2LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); return mapper.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest2.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest2.cs index ba8df4ab..3c1037b4 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest2.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBookToDtoMapperTest2.cs @@ -45,8 +45,8 @@ public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); var bucketRepo = new BucketBucketRepoAlwaysFind(); - var subject = new Mapper_LedgerBookDto_LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); + var subject = new MapperLedgerBookDto2LedgerBook(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo), new LedgerTransactionFactory()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_DataTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_DataTest.cs index 054f5b81..0e554014 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_DataTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_DataTest.cs @@ -15,97 +15,97 @@ public class LedgerBook_DataTest [TestMethod] public void UsingTestData1_FirstLineBankBalanceEqualsLedgerBalance() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(subject.LedgerBalance, subject.TotalBankBalance); } [TestMethod] public void UsingTestData1_FirstLineHairEntryShouldHaveBalance120() { - LedgerBook result = ArrangeAndAct(); - LedgerEntry subject = result.Reconciliations.First().Entries.First(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First().Entries.First(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); Assert.AreEqual(120, subject.Balance); } [TestMethod] public void UsingTestData1_FirstLineHasNoAdjustments() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(0, result.Reconciliations.First().BankBalanceAdjustments.Count()); } [TestMethod] public void UsingTestData1_FirstLineShouldHave3Entries() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(3, subject.Entries.Count()); } [TestMethod] public void UsingTestData1_FirstLineShouldHaveBankBalance2950() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(2950, subject.TotalBankBalance); } [TestMethod] public void UsingTestData1_FirstLineShouldHaveDate20130815() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(new DateTime(2013, 08, 15), subject.Date); } [TestMethod] public void UsingTestData1_FirstLineShouldHaveSurplusOf2712() { - LedgerBook result = ArrangeAndAct(); - LedgerEntryLine subject = result.Reconciliations.First(); + var result = ArrangeAndAct(); + var subject = result.Reconciliations.First(); Assert.AreEqual(2712.97M, subject.CalculatedSurplus); } [TestMethod] public void UsingTestData1_LedgerCountShouldBe3() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(3, result.Ledgers.Count()); } [TestMethod] public void UsingTestData1_OutputDataInTabularForm() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); result.Output(); } [TestMethod] public void UsingTestData1_ShouldBeHairLedger() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsNotNull(result.Ledgers.FirstOrDefault(l => l.BudgetBucket.Code == TestDataConstants.HairBucketCode)); } [TestMethod] public void UsingTestData1_ShouldBePhoneLedger() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsNotNull(result.Ledgers.FirstOrDefault(l => l.BudgetBucket.Code == TestDataConstants.PhoneBucketCode)); } [TestMethod] public void UsingTestData1_ShouldBePowerLedger() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.IsNotNull(result.Ledgers.FirstOrDefault(l => l.BudgetBucket.Code == TestDataConstants.PowerBucketCode)); } [TestMethod] public void UsingTestData1_ShouldHave3Lines() { - LedgerBook result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(3, result.Reconciliations.Count()); } @@ -116,4 +116,4 @@ private LedgerBook ArrangeAndAct() } // ReSharper restore InconsistentNaming -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_GeneralTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_GeneralTest.cs index 2c397f0f..92a7bfad 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_GeneralTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_GeneralTest.cs @@ -85,4 +85,4 @@ public void Validate_ShouldBeValid_GivenTestData2() { Assert.IsTrue(this.subject.Validate(new StringBuilder())); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_ReconcileTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_ReconcileTest.cs index c548d6d7..ad6282b2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_ReconcileTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBook_ReconcileTest.cs @@ -74,4 +74,4 @@ private void Act() this.subject.Reconcile(this.testDataReconResult); } } -// ReSharper restore InconsistentNaming \ No newline at end of file +// ReSharper restore InconsistentNaming diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketTest.cs index 8b4d63be..d8842c39 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketTest.cs @@ -13,7 +13,7 @@ public class LedgerBucketTest [TestMethod] public void DictionaryTest() { - LedgerBucket instance1 = LedgerBookTestData.HairLedger; + var instance1 = LedgerBookTestData.HairLedger; var dictionary = new Dictionary { @@ -128,4 +128,4 @@ public void TwoInstancesWithSameBucketAndNullAccountHaveTheSameHashCode() Assert.AreEqual(instance1.GetHashCode(), instance2.GetHashCode()); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketToDtoMapperTest.cs index 6375e5e6..1ff81304 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerBucketToDtoMapperTest.cs @@ -31,8 +31,8 @@ public void TestInitialise() { var bucketRepo = new BucketBucketRepoAlwaysFind(); var accountRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerBucketDto_LedgerBucket(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo)); + var subject = new MapperLedgerBucketDto2LedgerBucket(bucketRepo, accountRepo, new LedgerBucketFactory(bucketRepo, accountRepo)); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerCalculationTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerCalculationTest.cs index 8b9ef752..5ad44015 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerCalculationTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerCalculationTest.cs @@ -20,11 +20,11 @@ public class LedgerCalculationTest private static LedgerBook CreateLedgerBookTestData() { return new LedgerBookBuilder - { - StorageKey = "BudgetBucketMonitorWidgetTest.xml", - Modified = new DateTime(2015, 11, 23), - Name = "Smith Budget 2015" - } + { + StorageKey = "BudgetBucketMonitorWidgetTest.xml", + Modified = new DateTime(2015, 11, 23), + Name = "Smith Budget 2015" + } .IncludeLedger(LedgerBookTestData.PhoneLedger, 50M) .IncludeLedger(LedgerBookTestData.HouseInsLedgerSavingsAccount, 200M) .AppendReconciliation( @@ -149,13 +149,13 @@ public void CalculateCurrentPeriodSurplusBalance_ShouldNotCountPositivePayCCTran { var ledgerLine = CreateLedgerBookTestData().Reconciliations.First(); var statement = CreateStatementBuilder().AppendTransaction(new Transaction - { - Account = StatementModelTestData.ChequeAccount, - Amount = -100M, - BudgetBucket = StatementModelTestData.PayCreditCard, - Date = new DateTime(2015, 11, 2), - Reference1 = "Pay credit card debit from surplus" - }) + { + Account = StatementModelTestData.ChequeAccount, + Amount = -100M, + BudgetBucket = StatementModelTestData.PayCreditCard, + Date = new DateTime(2015, 11, 2), + Reference1 = "Pay credit card debit from surplus" + }) .AppendTransaction(new Transaction { Account = StatementModelTestData.VisaAccount, @@ -198,7 +198,7 @@ public void CalculateCurrentPeriodSurplusBalance_ShouldNotCountPositivePayCCTran }) .Build(); var result = Subject.CalculateCurrentPeriodSurplusBalance( - ledgerLine, + ledgerLine, new GlobalFilterCriteria { BeginDate = new DateTime(2015, 10, 20), @@ -247,7 +247,7 @@ public void CalculateOverSpentLedgersShouldReturnEmptyGivenNoLedgerLineForGivenD var beginDate = new DateTime(2014, 07, 01); var endDate = beginDate.AddMonths(1).AddDays(-1); var ledgerLine = TestData.Reconciliations.First(); - IEnumerable result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData1(), ledgerLine, beginDate, endDate); + var result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData1(), ledgerLine, beginDate, endDate); Assert.IsFalse(result.Any()); } @@ -258,7 +258,7 @@ public void CalculateOverSpentLedgersShouldReturnEmptyGivenNoLedgersWereOverdraw var beginDate = new DateTime(2013, 08, 15); var endDate = beginDate.AddMonths(1).AddDays(-1); var ledgerLine = TestData.Reconciliations.First(); - IEnumerable result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData3(), ledgerLine, beginDate, endDate); + var result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData3(), ledgerLine, beginDate, endDate); foreach (var txn in result) { Console.WriteLine("{0} {1} {2}", txn.Date, txn.Narrative, txn.Amount); @@ -274,7 +274,7 @@ public void CalculateOverSpentLedgersShouldReturnOverdrawnTransactionsGivenState var beginDate = new DateTime(2013, 08, 15); var endDate = beginDate.AddMonths(1).AddDays(-1); var ledgerLine = TestData.Reconciliations.First(); - IEnumerable result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData2(), ledgerLine, beginDate, endDate); + var result = Subject.CalculateOverSpentLedgers(StatementModelTestData.TestData2(), ledgerLine, beginDate, endDate); foreach (var txn in result) { Console.WriteLine("{0} {1} {2}", txn.Date, txn.Narrative, txn.Amount); @@ -316,7 +316,7 @@ public void TestInitialise() public void UsingTestData1_LocateApplicableLedgerBalance_ShouldReturn64() { var filter = new GlobalFilterCriteria { BeginDate = new DateTime(2013, 04, 15), EndDate = new DateTime(2013, 05, 15) }; - decimal result = Subject.LocateApplicableLedgerBalance(TestData, filter, StatementModelTestData.PhoneBucket.Code); + var result = Subject.LocateApplicableLedgerBalance(TestData, filter, StatementModelTestData.PhoneBucket.Code); Assert.AreEqual(0M, result); } @@ -325,7 +325,7 @@ public void UsingTestData1WithAugust15_LocateApplicableLedgerBalance_ShouldRetur { var filter = new GlobalFilterCriteria { BeginDate = new DateTime(2013, 07, 15), EndDate = new DateTime(2013, 08, 15) }; - decimal result = Subject.LocateApplicableLedgerBalance(TestData, filter, StatementModelTestData.PhoneBucket.Code); + var result = Subject.LocateApplicableLedgerBalance(TestData, filter, StatementModelTestData.PhoneBucket.Code); TestData.Output(); Assert.AreEqual(64.71M, result); } @@ -346,4 +346,4 @@ public void CalculateCurrentPeriodSurplusBalance_UsingFortnightlyData_ShouldRetu Assert.AreEqual(3777.56M, result); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineTest.cs index f4e6b5e8..b4c85909 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineTest.cs @@ -22,7 +22,7 @@ public class LedgerEntryLineTest public void UpdateRemarks_ShouldSetRemarks() { NewSubject.UpdateRemarks("Foo bar"); - + Assert.AreEqual("Foo bar", NewSubject.Remarks); } @@ -32,7 +32,7 @@ public void RemoveTransactionShouldGiveSurplus1555() // Starting Surplus is $1,530.50 var entry = NewSubject.Entries.First(); entry.RemoveTransaction(entry.Transactions.First(t => t is CreditLedgerTransaction).Id); - + // The balance of a ledger cannot simply be calculated inside the ledger line. It must be recalc'ed at the ledger book level. Assert.AreEqual(1530.50M, NewSubject.CalculatedSurplus); // It should be unchanged. } @@ -41,7 +41,7 @@ public void RemoveTransactionShouldGiveSurplus1555() public void AddAdjustment_ShouldAffectLedgerBalance() { NewSubject.BalanceAdjustment(-101M, "foo dar far", new ChequeAccount("Chq")); - + Assert.AreEqual(1749.50M, NewSubject.LedgerBalance); } @@ -49,7 +49,7 @@ public void AddAdjustment_ShouldAffectLedgerBalance() public void AddBalanceAdjustment_ShouldAddToAdjustmentCollection() { NewSubject.BalanceAdjustment(101M, "foo dar far", new ChequeAccount("Chq")); - + Assert.AreEqual(1, Subject.BankBalanceAdjustments.Count()); } @@ -59,14 +59,14 @@ public void Output() Console.WriteLine("Date: " + Subject.Date); Console.WriteLine("Remarks: " + Subject.Remarks); Console.Write("Entries: x{0} (", Subject.Entries.Count()); - foreach (LedgerEntry entry in Subject.Entries) + foreach (var entry in Subject.Entries) { Console.Write("{0}, ", entry.LedgerBucket.BudgetBucket.Code); } Console.WriteLine(")"); Console.WriteLine("Bank Balances:"); - foreach (BankBalance bankBalance in Subject.BankBalances) + foreach (var bankBalance in Subject.BankBalances) { Console.WriteLine(" {0} {1:N}", bankBalance.Account.Name, bankBalance.Balance); } @@ -74,7 +74,7 @@ public void Output() Console.WriteLine("TotalBankBalance: " + Subject.TotalBankBalance); Console.WriteLine("Balance Adjustments:"); - foreach (BankBalanceAdjustmentTransaction adjustment in Subject.BankBalanceAdjustments) + foreach (var adjustment in Subject.BankBalanceAdjustments) { Console.WriteLine(" {0} {1} {2:N}", adjustment.BankAccount.Name, adjustment.Narrative, adjustment.Amount); } @@ -86,7 +86,7 @@ public void Output() Console.WriteLine(); Console.WriteLine("Surplus Balances:"); - foreach (BankBalance surplusBalance in Subject.SurplusBalances) + foreach (var surplusBalance in Subject.SurplusBalances) { Console.WriteLine(" {0} {1:N}", surplusBalance.Account.Name, surplusBalance.Balance); } @@ -97,14 +97,14 @@ public void Output() [TestMethod] public void SurplusBalancesShouldHave2Items() { - IEnumerable surplusBalances = Subject.SurplusBalances; + var surplusBalances = Subject.SurplusBalances; Assert.AreEqual(2, surplusBalances.Count()); } [TestMethod] public void SurplusBalancesShouldHaveSavingsBalanceOf100() { - IEnumerable surplusBalances = Subject.SurplusBalances; + var surplusBalances = Subject.SurplusBalances; Assert.AreEqual(100M, surplusBalances.Single(b => b.Account.Name == TestDataConstants.SavingsAccountName).Balance); } @@ -130,4 +130,4 @@ private LedgerEntryLine CreateSubject() return LedgerBookTestData.TestData5().Reconciliations.First(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineToDtoMapperTest.cs index 079d4b32..085233f7 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryLineToDtoMapperTest.cs @@ -18,7 +18,7 @@ private LedgerEntryLine TestData { get { - LedgerBook book = LedgerBookTestData.TestData4(); + var book = LedgerBookTestData.TestData4(); return book.Reconciliations.First(); } } @@ -63,8 +63,8 @@ public void ShouldMapRemarks() public void TestInitialise() { var accountRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerEntryLineDto_LedgerEntryLine(accountRepo, new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory()); + var subject = new MapperLedgerEntryLineDto2LedgerEntryLine(accountRepo, new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountRepo), new LedgerTransactionFactory()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryTest.cs index 317f8733..07b59034 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using BudgetAnalyser.Engine.Ledger; @@ -10,7 +10,7 @@ namespace BudgetAnalyser.Engine.UnitTest.Ledger; public class LedgerEntryTest { private LedgerEntry subject; - + [TestInitialize] public void TestInitialise() { @@ -22,13 +22,13 @@ public void TestInitialise() new CreditLedgerTransaction { Amount = -30 } }); } - + [TestMethod] public void AddTransactionShouldEffectEntryBalance() { var newTransaction = new CreditLedgerTransaction { Amount = -100 }; this.subject.AddTransactionForPersistenceOnly(newTransaction); - + Assert.AreEqual(20M, this.subject.Balance); } @@ -37,7 +37,7 @@ public void AddTransactionShouldEffectEntryNetAmount() { var newTransaction = new CreditLedgerTransaction { Amount = -100 }; this.subject.AddTransactionForPersistenceOnly(newTransaction); - + Assert.AreEqual(20M, this.subject.NetAmount); } @@ -45,17 +45,17 @@ public void AddTransactionShouldEffectEntryNetAmount() public void RemoveTransactionShouldNotEffectEntryBalance() { this.subject.RemoveTransaction(this.subject.Transactions.First(t => t is CreditLedgerTransaction).Id); - + // The balance cannot be simply set inside the Ledger Line, it must be recalc'ed at the ledger book level. Assert.AreEqual(120M, this.subject.Balance); } - + [TestMethod] public void RemoveTransactionShouldEffectEntryNetAmount() { var txn = this.subject.Transactions.First(t => t is CreditLedgerTransaction); this.subject.RemoveTransaction(txn.Id); - + Assert.AreEqual(170M, this.subject.NetAmount); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryToDtoMapperTest.cs index 90fbf9cd..ee41ad44 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerEntryToDtoMapperTest.cs @@ -36,9 +36,9 @@ public void ShouldMapCorrectNumberOfTransactions() public void TestInitialise() { var accountTypeRepo = new InMemoryAccountTypeRepository(); - var subject = new Mapper_LedgerEntryDto_LedgerEntry(new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountTypeRepo), new LedgerTransactionFactory(), accountTypeRepo); + var subject = new MapperLedgerEntryDto2LedgerEntry(new LedgerBucketFactory(new BucketBucketRepoAlwaysFind(), accountTypeRepo), new LedgerTransactionFactory(), accountTypeRepo); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerTransactionToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerTransactionToDtoMapperTest.cs index 61970fa0..1b5bf1dc 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerTransactionToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/LedgerTransactionToDtoMapperTest.cs @@ -77,8 +77,8 @@ public void ShouldNotMapBankAccountForDebitLedgerTransaction() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_LedgerTransactionDto_LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); + var subject = new MapperLedgerTransactionDto2LedgerTransaction(new LedgerTransactionFactory(), new InMemoryAccountTypeRepository()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilderTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilderTest.cs index 74ce4733..6ee4e36f 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilderTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilderTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -56,7 +56,7 @@ public void Reconcile_ShouldAutoMatchTransactionsAndLinkIdToStatementTransaction { // The auto-matched credit ledger transaction from last month should be linked to the statement transaction. this.testDataStatement = StatementModelTestData.TestData5(); - List statementTransactions = this.testDataStatement.AllTransactions.Where(t => t.Reference1 == "agkT9kC").ToList(); + var statementTransactions = this.testDataStatement.AllTransactions.Where(t => t.Reference1 == "agkT9kC").ToList(); Debug.Assert(statementTransactions.Count() == 2); ActPeriodEndReconciliationOnTestData5(this.testDataStatement); @@ -187,7 +187,7 @@ public void Reconcile_WithPaymentFromWrongAccountShouldUpdateLedgerBalance_Given public void Reconcile_WithStatementSavedUpForHairLedgerShouldHaveBalance55_GivenTestData1() { TestIntialise(1); - List additionalTransactions = this.testDataStatement.AllTransactions.ToList(); + var additionalTransactions = this.testDataStatement.AllTransactions.ToList(); additionalTransactions.Add(new Transaction { @@ -332,4 +332,4 @@ private void TestIntialise(int testDataId, LedgerBook ledgerBook = null) break; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilder_NarrativeTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilder_NarrativeTest.cs index 92bd80a7..69a707c0 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilder_NarrativeTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationBuilder_NarrativeTest.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.Ledger.Reconciliation; +using BudgetAnalyser.Engine.Ledger.Reconciliation; using BudgetAnalyser.Engine.Statement; using BudgetAnalyser.Engine.UnitTest.TestData; using Rees.UnitTestUtilities; @@ -6,7 +6,7 @@ namespace BudgetAnalyser.Engine.UnitTest.Ledger; [TestClass] -public class ReconciliationBuilder_NarrativeTest +public class ReconciliationBuilderNarrativeTest { private const string? NoDescriptionText = "[No Description]"; private const string? BillPaymentTransactionText = "Bill Payment"; @@ -205,4 +205,4 @@ public void TestInitialise() { return PrivateAccessor.InvokeStaticFunction(typeof(ReconciliationBuilder), "ExtractNarrative", this.testTransaction); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationCreationManagerTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationCreationManagerTest.cs index 32c5203b..bd7668f9 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationCreationManagerTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationCreationManagerTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using BudgetAnalyser.Engine.Budget; @@ -85,15 +85,15 @@ public void Reconcile_ShouldAddLedgerEntryLineToLedgerBook() this.mockReconciliationBuilder.Setup(m => m.CreateNewMonthlyReconciliation(TestDataReconcileDate, this.testDataBudgetModel, this.testDataStatement, It.IsAny())) .Returns(this.testDataReconResult); var count = this.testDataLedgerBook.Reconciliations.Count(); - bool reconcileCalled = false; + var reconcileCalled = false; ((LedgerBookTestHarness)this.testDataLedgerBook).ReconcileOverride = _ => { // record the fact Reconcile was called. reconcileCalled = true; }; - + var result = ActPeriodEndReconciliation(); - + Assert.IsTrue(reconcileCalled); } @@ -113,11 +113,11 @@ public void Reconcile_ShouldNotThrow_GivenTestData1AndUnclassifiedTransactionsOu public void Reconcile_ShouldThrow_GivenInvalidLedgerBook() { var myTestDate = new DateTime(2012, 2, 20); - + // Make sure there is a valid budget to isolate the invalid ledger book test var budget = this.testDataBudgetCollection.OrderBy(b => b.EffectiveFrom).First(); budget.EffectiveFrom = myTestDate.AddDays(-1); - + ActPeriodEndReconciliation(myTestDate); } @@ -346,4 +346,4 @@ private ReconciliationResult ActPeriodEndReconciliationOnTestData5(StatementMode result.Reconciliation.Output(LedgerBookHelper.LedgerOrder(this.testDataLedgerBook), true, true); return result; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationManagerTest_TransferFunds.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationManagerTest_TransferFunds.cs index 49aac381..b7a3e9b4 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationManagerTest_TransferFunds.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/ReconciliationManagerTest_TransferFunds.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Ledger; @@ -26,7 +26,7 @@ public class ReconciliationManagerTest_TransferFunds private LedgerBucket surplusChqLedger; private LedgerEntryLine testDataEntryLine; private LedgerBook testDataLedgerBook; - + [TestInitialize] public void TestInitialise() { @@ -79,12 +79,12 @@ public void TransferFunds_ShouldDecreaseChqBalance_GivenTransferFromChqSurplusTo Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + var beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.ChequeAccount) .Sum(a => a.Amount); this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + var afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.ChequeAccount) .Sum(a => a.Amount); @@ -103,9 +103,9 @@ public void TransferFunds_ShouldDecreaseChqSurplus_GivenTransferFromChqSurplusTo Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; + var beforeBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; + var afterBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; Assert.AreEqual(beforeBalance - transferDetails.TransferAmount, afterBalance); } @@ -121,9 +121,9 @@ public void TransferFunds_ShouldDecreaseChqSurplus_GivenTransferFromChqSurplusTo Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; + var beforeBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; + var afterBalance = this.testDataEntryLine.SurplusBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance; Assert.AreEqual(beforeBalance - transferDetails.TransferAmount, afterBalance); } @@ -139,9 +139,9 @@ public void TransferFunds_ShouldIncreaseChqCarMtc_GivenTransferFromChqSurplusToC Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.phNetChqLedger).Balance; + var beforeBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.phNetChqLedger).Balance; this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.phNetChqLedger).Balance; + var afterBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.phNetChqLedger).Balance; Assert.AreEqual(beforeBalance + transferDetails.TransferAmount, afterBalance); } @@ -157,12 +157,12 @@ public void TransferFunds_ShouldIncreaseSavBalance_GivenTransferFromChqSurplusTo Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + var beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.SavingsAccount) .Sum(a => a.Amount); this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + var afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.SavingsAccount) .Sum(a => a.Amount); @@ -181,9 +181,9 @@ public void TransferFunds_ShouldIncreaseSavInsHome_GivenTransferFromChqSurplusTo Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.insHomeSavLedger).Balance; + var beforeBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.insHomeSavLedger).Balance; this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.insHomeSavLedger).Balance; + var afterBalance = this.testDataEntryLine.Entries.First(e => e.LedgerBucket == this.insHomeSavLedger).Balance; Assert.AreEqual(beforeBalance + transferDetails.TransferAmount, afterBalance); } @@ -223,12 +223,12 @@ public void TransferFunds_ShouldNotDecreaseChqBalance_GivenTransferFromChqSurplu Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + var beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.ChequeAccount) .Sum(a => a.Amount); this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + var afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.ChequeAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.ChequeAccount) .Sum(a => a.Amount); @@ -247,12 +247,12 @@ public void TransferFunds_ShouldNotIncreaseSavBalance_GivenTransferFromChqSurplu Narrative = "Testing 123" }; - decimal beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + var beforeBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.SavingsAccount) .Sum(a => a.Amount); this.subject.TransferFunds(this.testDataLedgerBook, transferDetails, this.testDataEntryLine); - decimal afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + var afterBalance = this.testDataEntryLine.BankBalances.First(b => b.Account == StatementModelTestData.SavingsAccount).Balance + this.testDataEntryLine.BankBalanceAdjustments .Where(a => a.BankAccount == StatementModelTestData.SavingsAccount) .Sum(a => a.Amount); @@ -285,4 +285,4 @@ public void TransferFunds_ShouldThrow_GivenNullTransferDetails() Assert.Fail(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/SavedUpForLedgerReconciliationBehaviourTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/SavedUpForLedgerReconciliationBehaviourTest.cs index d9bfc10d..0c3f8597 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/SavedUpForLedgerReconciliationBehaviourTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/SavedUpForLedgerReconciliationBehaviourTest.cs @@ -66,7 +66,7 @@ public void ShouldAddCompensatingTransaction_GivenNoBudgetAmountAndClosingBalanc }; var result = this.subject2.ApplyReconciliationBehaviour(testInput, this.reconciliationDate, OpeningBalance); - + Assert.IsTrue(result); Assert.AreEqual(2, testInput.Count); } @@ -110,4 +110,4 @@ public void TestInitialise() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/SpentMonthlyLedgerReconciliationBehaviourTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/SpentMonthlyLedgerReconciliationBehaviourTest.cs index 3c68a8c6..88af6098 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/SpentMonthlyLedgerReconciliationBehaviourTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/SpentMonthlyLedgerReconciliationBehaviourTest.cs @@ -407,4 +407,4 @@ public void ShouldSupplementUpToBudgetAmount_GivenClosingBalanceIsLessThanBudget #endregion } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Ledger/TransferFundsCommandTest.cs b/BudgetAnalyser.Engine.UnitTest/Ledger/TransferFundsCommandTest.cs index 489e0bd5..89fadbdb 100644 --- a/BudgetAnalyser.Engine.UnitTest/Ledger/TransferFundsCommandTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Ledger/TransferFundsCommandTest.cs @@ -285,4 +285,4 @@ public void TestInitialise() { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/DataMatchingRuleToMatchingRuleMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/DataMatchingRuleToMatchingRuleMapperTest.cs index 1824cb52..17a06c32 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/DataMatchingRuleToMatchingRuleMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/DataMatchingRuleToMatchingRuleMapperTest.cs @@ -14,42 +14,42 @@ public class DataMatchingRuleToMatchingRuleMapperTest [TestMethod] public void AmountShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Amount, result.Amount); } [TestMethod] public void BucketCodeShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.BucketCode, result.BucketCode); } [TestMethod] public void CreatedDatesShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Created, result.Created); } [TestMethod] public void DescriptionShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Description, result.Description); } [TestMethod] public void LastMatchShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.LastMatch, result.LastMatch); } [TestMethod] public void MatchCountShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.MatchCount, result.MatchCount); } @@ -57,35 +57,35 @@ public void MatchCountShouldBeMapped() [Description("A test designed to break when new propperties are added to the MatchingRuleDto. This is a trigger to update the mappers.")] public void NumberOfDataMatchingRulePropertiesShouldBe12() { - int dataProperties = typeof(MatchingRule).CountProperties(); + var dataProperties = typeof(MatchingRule).CountProperties(); Assert.AreEqual(13, dataProperties); } [TestMethod] public void Reference1ShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference1, result.Reference1); } [TestMethod] public void Reference2ShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference2, result.Reference2); } [TestMethod] public void Reference3ShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference3, result.Reference3); } [TestMethod] public void RuleIdShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.RuleId, result.RuleId); } @@ -110,14 +110,14 @@ public void TestInitialise() [TestMethod] public void TransactionTypeShouldBeMapped() { - MatchingRule result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.TransactionType, result.TransactionType); } private MatchingRule ArrangeAndAct() { - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); return subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/DtoToMatchingRuleMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/DtoToMatchingRuleMapperTest.cs index bec397f3..1f476d25 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/DtoToMatchingRuleMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/DtoToMatchingRuleMapperTest.cs @@ -13,26 +13,20 @@ public class DtoToMatchingRuleMapperTest private static readonly Guid Id = new Guid("901EC4BB-B8B5-43CD-A8C9-15121048CBA4"); private MatchingRule Result { get; set; } - private MatchingRuleDto TestData - { - get - { - return new MatchingRuleDto - { - Amount = 123.45M, - BucketCode = TestDataConstants.PhoneBucketCode, - Created = new DateTime(2014, 07, 04), - Description = "The quick brown fox", - LastMatch = new DateTime(2014, 07, 29), - MatchCount = 2, - Reference1 = "jumped", - Reference2 = "over", - Reference3 = "the lazy", - RuleId = Id, - TransactionType = "dog." - }; - } - } + private MatchingRuleDto TestData => new MatchingRuleDto + { + Amount = 123.45M, + BucketCode = TestDataConstants.PhoneBucketCode, + Created = new DateTime(2014, 07, 04), + Description = "The quick brown fox", + LastMatch = new DateTime(2014, 07, 29), + MatchCount = 2, + Reference1 = "jumped", + Reference2 = "over", + Reference3 = "the lazy", + RuleId = Id, + TransactionType = "dog." + }; [TestMethod] public void ShouldMapAmount() @@ -110,25 +104,25 @@ public void ShouldMapTransactionType() public void ShouldSetCreatedDateToNowIfGivenNull() { TestData.Created = null; - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); - Assert.IsFalse(Result.Created == default(DateTime)); + Assert.IsFalse(Result.Created == default); } [TestMethod] public void ShouldSetRuleIdDateToNowIfGivenNull() { TestData.RuleId = null; - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); - Assert.IsFalse(Result.RuleId == default(Guid)); + Assert.IsFalse(Result.RuleId == default); } [TestInitialize] public void TestInitialise() { - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/MatchMakerTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/MatchMakerTest.cs index 1d5cb3e5..47565810 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/MatchMakerTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/MatchMakerTest.cs @@ -37,7 +37,7 @@ public void MatchShouldMatchIfReferenceIsBucketCode() { this.mockBudgetBucketRepo.Setup(m => m.IsValidCode("Foo")).Returns(true); this.mockBudgetBucketRepo.Setup(m => m.GetByCode("Foo")).Returns(new SpentPerPeriodExpenseBucket("FOO", "Foo")); - IList transactions = this.testDataTransactions; + var transactions = this.testDataTransactions; transactions.First().Reference1 = "Foo"; var subject = Arrange(); @@ -50,10 +50,10 @@ public void MatchShouldPreferMatchFromReferenceOverRules() { this.mockBudgetBucketRepo.Setup(m => m.IsValidCode("Foo")).Returns(true); this.mockBudgetBucketRepo.Setup(m => m.GetByCode("Foo")).Returns(new SpentPerPeriodExpenseBucket("FOO", "Foo")); - IList transactions = this.testDataTransactions; + var transactions = this.testDataTransactions; var firstTxn = transactions.First(); firstTxn.Reference1 = "Foo"; - List rules = this.allRules.ToList(); + var rules = this.allRules.ToList(); var firstRule = rules.First(); firstRule.BucketCode = "FOO"; firstRule.MatchCount = 0; @@ -84,7 +84,7 @@ public void MatchShouldReturnTrueIfRuleMatchesDescription() firstRule.And = false; // Using OR var subject = Arrange(); - + var result = subject.Match(this.testDataTransactions, this.allRules); Assert.IsTrue(result); Assert.AreEqual(2, firstRule.MatchCount); @@ -174,4 +174,4 @@ private Matchmaker Arrange() return new Matchmaker(new FakeLogger(), this.mockBudgetBucketRepo.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleTest.cs index 1f3af68a..09feb95b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleTest.cs @@ -16,93 +16,93 @@ public class MatchingRuleTest [TestMethod] public void AndMatchShouldFailWhenBucketIsInactive() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.Bucket.Active = false; - bool success = subject.Match(new Transaction { Description = "Testing Description" }); + var success = subject.Match(new Transaction { Description = "Testing Description" }); Assert.IsFalse(success); } [TestMethod] public void AndMatchShouldMatchOnAmountAndDescription() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.Amount = 11.01M; - bool success = subject.Match(new Transaction { Description = "Testing Description", Amount = 11.01M }); + var success = subject.Match(new Transaction { Description = "Testing Description", Amount = 11.01M }); Assert.IsTrue(success); } [TestMethod] public void AndMatchShouldMatchOnDescription() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; - bool success = subject.Match(new Transaction { Description = "Testing Description" }); + var success = subject.Match(new Transaction { Description = "Testing Description" }); Assert.IsTrue(success); } [TestMethod] public void AndMatchShouldMatchOnReferences() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Reference1 = "Testing 1"; subject.Reference2 = "Testing 2"; subject.Reference3 = "Testing 3"; - bool success = subject.Match(new Transaction { Reference1 = "Testing 1", Reference2 = "Testing 2", Reference3 = "Testing 3" }); + var success = subject.Match(new Transaction { Reference1 = "Testing 1", Reference2 = "Testing 2", Reference3 = "Testing 3" }); Assert.IsTrue(success); } [TestMethod] public void AndMatchShouldMatchOnTransacionType() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.TransactionType = "Foo"; - bool success = subject.Match(new Transaction { Description = "Testing Description", TransactionType = new NamedTransaction("Foo") }); + var success = subject.Match(new Transaction { Description = "Testing Description", TransactionType = new NamedTransaction("Foo") }); Assert.IsTrue(success); } [TestMethod] public void AndMatchShouldNotMatchOnDescription1() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; - bool success = subject.Match(new Transaction { Description = "xxxTesting Description" }); + var success = subject.Match(new Transaction { Description = "xxxTesting Description" }); Assert.IsFalse(success); } [TestMethod] public void AndMatchShouldNotMatchOnDescription2() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; - bool success = subject.Match(new Transaction { Description = "Testing Descriptionxxx" }); + var success = subject.Match(new Transaction { Description = "Testing Descriptionxxx" }); Assert.IsFalse(success); } [TestMethod] public void AndMatchShouldNotMatchOnDescription3() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.Reference1 = "Ref1"; - bool success = subject.Match(new Transaction { Description = "Testing Description" }); + var success = subject.Match(new Transaction { Description = "Testing Description" }); Assert.IsFalse(success); } [TestMethod] public void AnObjectIsNotEqualWithNull() { - MatchingRule subject = Arrange(); + var subject = Arrange(); Assert.IsFalse(subject.Equals(null)); Assert.IsTrue(subject is not null); } @@ -110,14 +110,14 @@ public void AnObjectIsNotEqualWithNull() [TestMethod] public void CtorShouldInitialiseCreated() { - MatchingRule subject = Arrange(); + var subject = Arrange(); Assert.AreNotEqual(DateTime.MinValue, subject.Created); } [TestMethod] public void CtorShouldInitialiseId() { - MatchingRule subject = Arrange(); + var subject = Arrange(); Assert.AreNotEqual(Guid.Empty, subject.RuleId); } @@ -132,7 +132,7 @@ public void CtorShouldThrowIfNullBucketRepo() [TestMethod] public void MatchShouldSetLastMatchWhenMatchIsMade() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.LastMatch = DateTime.MinValue; subject.Match(new Transaction { Description = "Testing Description" }); @@ -142,7 +142,7 @@ public void MatchShouldSetLastMatchWhenMatchIsMade() [TestMethod] public void MatchShouldSetMatchCountWhenMatchIsMade() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Description = "Testing Description"; subject.MatchCount = 1; subject.Match(new Transaction { Description = "Testing Description" }); @@ -153,7 +153,7 @@ public void MatchShouldSetMatchCountWhenMatchIsMade() [ExpectedException(typeof(ArgumentNullException))] public void MatchShouldThrowWhenTransactionIsNull() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.Match(null); Assert.Fail(); } @@ -161,79 +161,79 @@ public void MatchShouldThrowWhenTransactionIsNull() [TestMethod] public void OrMatchShouldMatchOnAmountAndDescription() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Description = "Testing Description"; subject.Amount = 11.01M; - bool success = subject.Match(new Transaction { Description = "Testing xxxx", Amount = 11.01M }); + var success = subject.Match(new Transaction { Description = "Testing xxxx", Amount = 11.01M }); Assert.IsTrue(success); } [TestMethod] public void OrMatchShouldMatchOnDescription3() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Description = "Testing Description"; subject.Reference1 = "Ref1"; - bool success = subject.Match(new Transaction { Description = "Testing Description" }); + var success = subject.Match(new Transaction { Description = "Testing Description" }); Assert.IsTrue(success); } [TestMethod] public void OrMatchShouldMatchOnReferences() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Reference1 = "Testing 1"; subject.Reference2 = "Testing 2"; subject.Reference3 = "Testing 3"; - bool success = subject.Match(new Transaction { Reference1 = "Testing 1", Reference3 = "Testing xxx" }); + var success = subject.Match(new Transaction { Reference1 = "Testing 1", Reference3 = "Testing xxx" }); Assert.IsTrue(success); } [TestMethod] public void OrMatchShouldMatchOnTransacionType() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Description = "Testing Description"; subject.TransactionType = "Foo"; - bool success = subject.Match(new Transaction { Description = "Testing Description", TransactionType = new NamedTransaction("Foo") }); + var success = subject.Match(new Transaction { Description = "Testing Description", TransactionType = new NamedTransaction("Foo") }); Assert.IsTrue(success); } [TestMethod] public void OrMatchShouldNotMatchOnDescription1() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Description = "Testing Description"; - bool success = subject.Match(new Transaction { Description = "xxxTesting Description" }); + var success = subject.Match(new Transaction { Description = "xxxTesting Description" }); Assert.IsFalse(success); } [TestMethod] public void OrMatchShouldNotMatchOnDescription2() { - MatchingRule subject = Arrange(); + var subject = Arrange(); subject.And = false; subject.Description = "Testing Description"; - bool success = subject.Match(new Transaction { Description = "Testing Descriptionxxx" }); + var success = subject.Match(new Transaction { Description = "Testing Descriptionxxx" }); Assert.IsFalse(success); } [TestMethod] public void RulesWithDifferentIdAreConsideredNotEqual() { - MatchingRule subject = Arrange(); - MatchingRule subject2 = Arrange(); + var subject = Arrange(); + var subject2 = Arrange(); Assert.IsFalse(subject.Equals(subject2)); Assert.IsTrue(subject != subject2); @@ -243,8 +243,8 @@ public void RulesWithDifferentIdAreConsideredNotEqual() [TestMethod] public void RulesWithSameIdAreConsideredEqual() { - MatchingRule subject = Arrange(); - MatchingRule subject2 = Arrange(); + var subject = Arrange(); + var subject2 = Arrange(); subject2.RuleId = subject.RuleId; Assert.IsTrue(subject.Equals(subject2)); Assert.IsTrue(subject == subject2); @@ -260,8 +260,8 @@ public void TestInitialise() [TestMethod] public void TwoObjectsReferringToSameAreEqual() { - MatchingRule subject = Arrange(); - MatchingRule subject2 = subject; + var subject = Arrange(); + var subject2 = subject; Assert.IsTrue(subject.Equals(subject2)); Assert.IsTrue(subject == subject2); Assert.IsTrue(subject.GetHashCode() == subject2.GetHashCode()); @@ -270,7 +270,7 @@ public void TwoObjectsReferringToSameAreEqual() [TestMethod] public void TwoObjectsReferringToSameAreEqual2() { - MatchingRule subject = Arrange(); + var subject = Arrange(); object subject2 = subject; Assert.IsTrue(subject.Equals(subject2)); #pragma warning disable 252,253 @@ -287,4 +287,4 @@ private MatchingRule Arrange() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDataMatchingRuleMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDataMatchingRuleMapperTest.cs index 003229af..a7f449f5 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDataMatchingRuleMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDataMatchingRuleMapperTest.cs @@ -14,42 +14,42 @@ public class MatchingRuleToDataMatchingRuleMapperTest [TestMethod] public void AmountShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Amount, result.Amount); } [TestMethod] public void BucketCodeShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.BucketCode, result.BucketCode); } [TestMethod] public void CreatedDatesShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Created, result.Created); } [TestMethod] public void DescriptionShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Description, result.Description); } [TestMethod] public void LastMatchShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.LastMatch, result.LastMatch); } [TestMethod] public void MatchCountShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.MatchCount, result.MatchCount); } @@ -57,35 +57,35 @@ public void MatchCountShouldBeMapped() [Description("A test designed to break when new propperties are added to the MatchingRuleDto. This is a trigger to update the mappers.")] public void NumberOfDataMatchingRulePropertiesShouldBe12() { - int dataProperties = typeof(MatchingRuleDto).CountProperties(); + var dataProperties = typeof(MatchingRuleDto).CountProperties(); Assert.AreEqual(12, dataProperties); } [TestMethod] public void Reference1ShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference1, result.Reference1); } [TestMethod] public void Reference2ShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference2, result.Reference2); } [TestMethod] public void Reference3ShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.Reference3, result.Reference3); } [TestMethod] public void RuleIdShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.RuleId, result.RuleId); } @@ -109,14 +109,14 @@ public void TestInitialise() [TestMethod] public void TransactionTypeShouldBeMapped() { - MatchingRuleDto result = ArrangeAndAct(); + var result = ArrangeAndAct(); Assert.AreEqual(TestData.TransactionType, result.TransactionType); } private MatchingRuleDto ArrangeAndAct() { - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); return subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDtoMappeTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDtoMappeTest.cs index 8b661f41..4865a50d 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDtoMappeTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/MatchingRuleToDtoMappeTest.cs @@ -13,26 +13,20 @@ public class MatchingRuleToDtoMapperTest private static readonly Guid Id = new Guid("901EC4BB-B8B5-43CD-A8C9-15121048CBA4"); private MatchingRuleDto Result { get; set; } - private MatchingRule TestData + private MatchingRule TestData => new MatchingRule(new BucketBucketRepoAlwaysFind()) { - get - { - return new MatchingRule(new BucketBucketRepoAlwaysFind()) - { - Amount = 123.45M, - BucketCode = TestDataConstants.PhoneBucketCode, - Created = new DateTime(2014, 07, 04), - Description = "The quick brown fox", - LastMatch = new DateTime(2014, 07, 29), - MatchCount = 2, - Reference1 = "jumped", - Reference2 = "over", - Reference3 = "the lazy", - RuleId = Id, - TransactionType = "dog." - }; - } - } + Amount = 123.45M, + BucketCode = TestDataConstants.PhoneBucketCode, + Created = new DateTime(2014, 07, 04), + Description = "The quick brown fox", + LastMatch = new DateTime(2014, 07, 29), + MatchCount = 2, + Reference1 = "jumped", + Reference2 = "over", + Reference3 = "the lazy", + RuleId = Id, + TransactionType = "dog." + }; [TestMethod] public void ShouldMapAmount() @@ -109,8 +103,8 @@ public void ShouldMapTransactionType() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()); + var subject = new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()); Result = Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Matching/XamlOnDiskMatchingRuleRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Matching/XamlOnDiskMatchingRuleRepositoryTest.cs index 45b7b728..79097c3b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Matching/XamlOnDiskMatchingRuleRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Matching/XamlOnDiskMatchingRuleRepositoryTest.cs @@ -31,7 +31,7 @@ public void CtorShouldThrowWhenGivenNullMapper() public async Task LoadFromDemoFileShouldReturnMatchingRules() { var subject = ArrangeUsingEmbeddedResources(); - IEnumerable results = await subject.LoadAsync(TestDataConstants.DemoRulesFileName, false); + var results = await subject.LoadAsync(TestDataConstants.DemoRulesFileName, false); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); @@ -42,7 +42,7 @@ public async Task LoadShouldReturnMatchingRules() { var subject = ArrangeUsingEmbeddedResources(); subject.LoadFromDiskOveride = fileName => MatchingRulesTestData.RawTestData1().ToList(); - IEnumerable results = await subject.LoadAsync("foo.bar", false); + var results = await subject.LoadAsync("foo.bar", false); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); @@ -119,9 +119,9 @@ private XamlOnDiskMatchingRuleRepositoryTestHarness ArrangeUsingEmbeddedResource MatchingRulesTestDataGenerated.BucketRepo = bucketRepo; return new XamlOnDiskMatchingRuleRepositoryTestHarness( - new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()), + new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()), new LocalDiskReaderWriterSelector( - new [] { new EmbeddedResourceFileReaderWriter() })); + new[] { new EmbeddedResourceFileReaderWriter() })); } private XamlOnDiskMatchingRuleRepositoryTestHarness ArrangeUsingMocks() @@ -130,8 +130,8 @@ private XamlOnDiskMatchingRuleRepositoryTestHarness ArrangeUsingMocks() MatchingRulesTestDataGenerated.BucketRepo = bucketRepo; return new XamlOnDiskMatchingRuleRepositoryTestHarness( - new Mapper_MatchingRuleDto_MatchingRule(new BucketBucketRepoAlwaysFind()), + new MapperMatchingRuleDto2MatchingRule(new BucketBucketRepoAlwaysFind()), this.mockSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/MetaTest.cs b/BudgetAnalyser.Engine.UnitTest/MetaTest.cs new file mode 100644 index 00000000..64c6f91b --- /dev/null +++ b/BudgetAnalyser.Engine.UnitTest/MetaTest.cs @@ -0,0 +1,42 @@ +using System.Reflection; + +namespace BudgetAnalyser.Engine.UnitTest; + +[TestClass] +public class MetaTest +{ + private const int MinimumTestCount = 942; + + [TestMethod] + public void ListAllTests() + { + var assembly = GetType().Assembly; + var count = 0; + foreach (var type in assembly.ExportedTypes) + { + var testClassAttrib = type.GetCustomAttribute(); + if (testClassAttrib is not null) + { + foreach (var method in type.GetMethods()) + { + if (method.GetCustomAttribute() is not null) + { + Console.WriteLine("{0} {1} - {2}", ++count, type.FullName, method.Name); + } + } + } + } + } + + [TestMethod] + public void NoDecreaseInTests() + { + var assembly = GetType().Assembly; + var count = (from type in assembly.ExportedTypes + let testClassAttrib = type.GetCustomAttribute() + where testClassAttrib is not null + select type.GetMethods().Count(method => method.GetCustomAttribute() is not null)).Sum(); + Console.WriteLine(count); + Assert.IsTrue(count >= MinimumTestCount); + } +} diff --git a/BudgetAnalyser.Engine.UnitTest/NewZealandPublicHolidaysTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/NewZealandPublicHolidaysTestHarness.cs index 0f8ca888..e1c4f8f9 100644 --- a/BudgetAnalyser.Engine.UnitTest/NewZealandPublicHolidaysTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/NewZealandPublicHolidaysTestHarness.cs @@ -21,7 +21,7 @@ public void VerifyHolidays(IEnumerable expectedResults) { Console.WriteLine(); Console.WriteLine("Expected Holidays:"); - foreach (DateTime holiday in expectedResults) + foreach (var holiday in expectedResults) { Console.WriteLine("{0}", holiday.ToString("d-MMM-yy dddd")); Assert.IsTrue(Results.Contains(holiday)); @@ -32,10 +32,10 @@ private void CalculateHolidays() { Results = NewZealandPublicHolidays.CalculateHolidays(new DateTime(Year, 1, 1), new DateTime(Year, 12, 31)); Console.WriteLine("Calculated Holidays:"); - foreach (Tuple holiday in NewZealandPublicHolidays.CalculateHolidaysVerbose(new DateTime(Year, 1, 1), new DateTime(Year, 12, 31))) + foreach (var holiday in NewZealandPublicHolidays.CalculateHolidaysVerbose(new DateTime(Year, 1, 1), new DateTime(Year, 12, 31))) { Console.WriteLine("{0} {1}", holiday.Item1.PadRight(20), holiday.Item2.ToString("d-MMM-yy dddd")); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Persistence/ApplicationDatabaseToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Persistence/ApplicationDatabaseToDtoMapperTest.cs index eecdff50..063557df 100644 --- a/BudgetAnalyser.Engine.UnitTest/Persistence/ApplicationDatabaseToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Persistence/ApplicationDatabaseToDtoMapperTest.cs @@ -44,9 +44,11 @@ public void ShouldMapStatementModelRootDto() [TestInitialize] public void TestInitialise() { - var todoCollection = new ToDoCollection(); - todoCollection.Add(new ToDoTask("Foo1")); - todoCollection.Add(new ToDoTask("Foo2", false, false)); + var todoCollection = new ToDoCollection + { + new ToDoTask("Foo1"), + new ToDoTask("Foo2", false, false) + }; this.testData = new ApplicationDatabase(); PrivateAccessor.SetProperty(this.testData, "BudgetCollectionStorageKey", "Budget.xml"); PrivateAccessor.SetProperty(this.testData, "FileName", "C:\\Foo\\TestData.bax"); @@ -55,8 +57,8 @@ public void TestInitialise() PrivateAccessor.SetProperty(this.testData, "StatementModelStorageKey", "Statement.xml"); PrivateAccessor.SetProperty(this.testData, "LedgerReconciliationToDoCollection", todoCollection); - var subject = new Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase(); + var subject = new MapperBudgetAnalyserStorageRoot2ApplicationDatabase(); this.result = subject.ToDto(this.testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Persistence/DtoToApplicationDatabaseMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Persistence/DtoToApplicationDatabaseMapperTest.cs index c222d201..4b57a396 100644 --- a/BudgetAnalyser.Engine.UnitTest/Persistence/DtoToApplicationDatabaseMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Persistence/DtoToApplicationDatabaseMapperTest.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using BudgetAnalyser.Engine.Ledger.Data; using BudgetAnalyser.Engine.Persistence; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -57,8 +57,8 @@ public void TestInitialise() } }; - var subject = new Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase(); + var subject = new MapperBudgetAnalyserStorageRoot2ApplicationDatabase(); this.result = subject.ToModel(this.testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Persistence/XamlOnDiskApplicationDatabaseRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Persistence/XamlOnDiskApplicationDatabaseRepositoryTest.cs index e3eeab96..77cffa66 100644 --- a/BudgetAnalyser.Engine.UnitTest/Persistence/XamlOnDiskApplicationDatabaseRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Persistence/XamlOnDiskApplicationDatabaseRepositoryTest.cs @@ -45,14 +45,14 @@ public void LoadShouldSetStatementModelStorageKeyGivenDemoFile() [TestInitialize] public void TestInitialise() { - this.subject = new XamlOnDiskApplicationDatabaseRepositoryTestHarness(new Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase()) + this.subject = new XamlOnDiskApplicationDatabaseRepositoryTestHarness(new MapperBudgetAnalyserStorageRoot2ApplicationDatabase()) { FileExistsOverride = fileName => true }; - Task task = this.subject.LoadAsync(TestDataConstants.DemoBudgetAnalyserFileName); + var task = this.subject.LoadAsync(TestDataConstants.DemoBudgetAnalyserFileName); task.Wait(); this.result = task.Result; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestData.cs b/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestData.cs index 6f733b0e..c4853a08 100644 --- a/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestData.cs @@ -84,4 +84,4 @@ public static class PublicHolidaysTestData } }; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestGenerator.cs b/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestGenerator.cs index 108bcef8..93e2ef94 100644 --- a/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestGenerator.cs +++ b/BudgetAnalyser.Engine.UnitTest/PublicHolidaysTestGenerator.cs @@ -39,7 +39,7 @@ namespace BudgetAnalyser.Engine.UnitTest private static void WriteMainBody(StringBuilder builder) { - foreach (KeyValuePair> annualHoliday in PublicHolidaysTestData.ExpectedHolidays) + foreach (var annualHoliday in PublicHolidaysTestData.ExpectedHolidays) { WriteTestClassHeader(builder, annualHoliday); WriteTestClassBody(builder, annualHoliday.Key); @@ -88,7 +88,7 @@ public class PublicHolidays{0}Test {{ ", annualHoliday.Key); - foreach (DateTime holiday in annualHoliday.Value) + foreach (var holiday in annualHoliday.Value) { builder.AppendFormat(@" new DateTime({0}, {1}, {2}), @@ -97,4 +97,4 @@ public class PublicHolidays{0}Test builder.AppendLine(@" };"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Reports/BurnDownGraphAnalyserTest.cs b/BudgetAnalyser.Engine.UnitTest/Reports/BurnDownGraphAnalyserTest.cs index 3b8ba44b..037d6028 100644 --- a/BudgetAnalyser.Engine.UnitTest/Reports/BurnDownGraphAnalyserTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Reports/BurnDownGraphAnalyserTest.cs @@ -64,14 +64,14 @@ public void AnalyseShouldReturnAFirstBudgetElementEqualToTheMonthlyBudgetAmountG [TestMethod] public void AnalyseShouldReturnALastBudgetElementOfOneThirtythOfTheFirst() { - decimal expected = decimal.Round(BudgetLine.Plots.First().Amount / 31, 2); + var expected = decimal.Round(BudgetLine.Plots.First().Amount / 31, 2); Assert.AreEqual(expected, decimal.Round(BudgetLine.Plots.Last().Amount, 2)); } [TestMethod] public void AnalyseShouldReturnALastReportTransactionsElementWithBalanceEqualTo3376() { - foreach (ReportTransactionWithRunningBalance transaction in Result.ReportTransactions) + foreach (var transaction in Result.ReportTransactions) { Console.WriteLine( "{0} {1} {2:N} {3:N}", @@ -132,4 +132,4 @@ private void Act() endDate); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Reports/GraphDataTest.cs b/BudgetAnalyser.Engine.UnitTest/Reports/GraphDataTest.cs index 38382891..daffe1b9 100644 --- a/BudgetAnalyser.Engine.UnitTest/Reports/GraphDataTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Reports/GraphDataTest.cs @@ -58,7 +58,7 @@ public void TestInitialise() Subject.SeriesList.Add(Series3); var seriesNumber = 0; - foreach (SeriesData series in Subject.SeriesList) + foreach (var series in Subject.SeriesList) { for (var index = 0; index < 31; index++) { @@ -84,4 +84,4 @@ public void VisibleShouldRaiseChangeEventWhenVisibleChanges() Assert.IsTrue(eventRaised); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Reports/LongTermSpendingTrendAnalyserTest.cs b/BudgetAnalyser.Engine.UnitTest/Reports/LongTermSpendingTrendAnalyserTest.cs index 51de786e..78dac6fb 100644 --- a/BudgetAnalyser.Engine.UnitTest/Reports/LongTermSpendingTrendAnalyserTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Reports/LongTermSpendingTrendAnalyserTest.cs @@ -49,7 +49,7 @@ public class LongTermSpendingTrendAnalyserTest [TestMethod] public void OutputTest() { - LongTermSpendingTrendAnalyser subject = Arrange(); + var subject = Arrange(); subject.Analyse(StatementModelTestData.TestData2(), new GlobalFilterCriteria()); @@ -59,10 +59,10 @@ public void OutputTest() private static void Output(LongTermSpendingTrendAnalyser subject) { Console.WriteLine("{0} - {1} lines in the graph.", subject.Graph.GraphName, subject.Graph.Series.Count()); - foreach (SeriesData series in subject.Graph.Series) + foreach (var series in subject.Graph.Series) { Console.WriteLine("[{0}] {1}", series.SeriesName, series.Description); - foreach (DatedGraphPlot data in series.Plots) + foreach (var data in series.Plots) { Console.WriteLine(" {0} {1:C}", data.Month, data.Amount); } @@ -90,4 +90,4 @@ private LongTermSpendingTrendAnalyser Arrange(IBudgetBucketRepository bucketRepo return new LongTermSpendingTrendAnalyser(bucketRepo); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Reports/SpendingGraphAnalyserTest.cs b/BudgetAnalyser.Engine.UnitTest/Reports/SpendingGraphAnalyserTest.cs index 8cae2e50..c7b826a8 100644 --- a/BudgetAnalyser.Engine.UnitTest/Reports/SpendingGraphAnalyserTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Reports/SpendingGraphAnalyserTest.cs @@ -13,4 +13,4 @@ public SpendingGraphAnalyserTest() private BudgetBucket SurplusTestBucket { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Services/ApplicationDatabaseServiceTest.cs b/BudgetAnalyser.Engine.UnitTest/Services/ApplicationDatabaseServiceTest.cs index 8387aa03..b7df6147 100644 --- a/BudgetAnalyser.Engine.UnitTest/Services/ApplicationDatabaseServiceTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Services/ApplicationDatabaseServiceTest.cs @@ -109,7 +109,7 @@ public async Task CreateNewDatabaseAsync_ShouldThrow_GivenNullStorageKey() [TestMethod] public void Ctor_ShouldOrderServices() { - var services = (IEnumerable) PrivateAccessor.GetField(this.subject, "databaseDependents"); + var services = (IEnumerable)PrivateAccessor.GetField(this.subject, "databaseDependents"); var sequence = 0; foreach (var service in services) { @@ -225,7 +225,7 @@ public void NotifyOfChange_ShouldIndicateUnsavedChanges() { foreach (var dataType in Enum.GetValues(typeof(ApplicationDataType))) { - this.subject.NotifyOfChange((ApplicationDataType) dataType); + this.subject.NotifyOfChange((ApplicationDataType)dataType); Assert.IsTrue(this.subject.HasUnsavedChanges); TestInitialise(); } @@ -303,4 +303,4 @@ private void SaveSetup() this.subject.NotifyOfChange(ApplicationDataType.Budget); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Services/BudgetMaintenanceServiceTest.cs b/BudgetAnalyser.Engine.UnitTest/Services/BudgetMaintenanceServiceTest.cs index bff0dad8..7ed071d0 100644 --- a/BudgetAnalyser.Engine.UnitTest/Services/BudgetMaintenanceServiceTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Services/BudgetMaintenanceServiceTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Services; using BudgetAnalyser.Engine.UnitTest.TestData; @@ -152,4 +152,4 @@ public void SetUp() PrivateAccessor.SetProperty(this.service, "Budgets", this.budgetCollection); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Services/StatementModelTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/Services/StatementModelTestHarness.cs index 0b9f36ca..374dac14 100644 --- a/BudgetAnalyser.Engine.UnitTest/Services/StatementModelTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/Services/StatementModelTestHarness.cs @@ -37,4 +37,4 @@ internal override void SplitTransaction(Transaction originalTransaction, decimal SplitTransactionWasCalled++; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Services/TransactionManagerServiceTest.cs b/BudgetAnalyser.Engine.UnitTest/Services/TransactionManagerServiceTest.cs index 7e6d3fc9..d89fa6e8 100644 --- a/BudgetAnalyser.Engine.UnitTest/Services/TransactionManagerServiceTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Services/TransactionManagerServiceTest.cs @@ -75,7 +75,7 @@ public void DetectDuplicateTransactions_ShouldSummaryText_GivenTestData4() this.testData = StatementModelTestData.TestData4(); Arrange(); - string result = this.subject.DetectDuplicateTransactions(); + var result = this.subject.DetectDuplicateTransactions(); Console.WriteLine(result); Assert.IsFalse(string.IsNullOrWhiteSpace(result)); } @@ -303,7 +303,7 @@ public void RemoveTransaction_ShouldCallStatementModelRemove_GivenATransaction() this.testData = new StatementModelTestHarness(); this.testData.LoadTransactions(StatementModelTestData.TestData2().Transactions); Arrange(); - Transaction transaction = this.testData.Transactions.Skip(1).First(); + var transaction = this.testData.Transactions.Skip(1).First(); this.subject.RemoveTransaction(transaction); @@ -416,4 +416,4 @@ private TransactionManagerService CreateSubject() return new TransactionManagerService(this.budgetBucketRepo, this.mockStatementRepo.Object, new FakeLogger(), new FakeMonitorableDependencies()); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Services/TransactionRuleServiceTest.cs b/BudgetAnalyser.Engine.UnitTest/Services/TransactionRuleServiceTest.cs index e83840e2..d0da845b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Services/TransactionRuleServiceTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Services/TransactionRuleServiceTest.cs @@ -56,7 +56,7 @@ public void CreateNewSingleUseRule_ShouldCallFactoryToCreateTheRule() [TestMethod] public void Match_ShouldRemoveSingleUseRulesThatWereUsed() { - IEnumerable testTransactions = StatementModelTestData.TestData1().Transactions; + var testTransactions = StatementModelTestData.TestData1().Transactions; var testMatchingRules = new List { new SingleUseMatchingRule(this.mockBucketRepo) @@ -116,4 +116,4 @@ private void ArrangeForCreateNewRule() PrivateAccessor.SetField(this.subject, "rulesStorageKey", "Anything"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/AnzAccountStatementImporterV1Test.cs b/BudgetAnalyser.Engine.UnitTest/Statement/AnzAccountStatementImporterV1Test.cs index 64ea15c8..a9651f8e 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/AnzAccountStatementImporterV1Test.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/AnzAccountStatementImporterV1Test.cs @@ -92,7 +92,7 @@ public async Task TasteTestShouldReturnFalseGivenAnEmptyTasteTestResponse() var result = await subject.TasteTestAsync(@"transumm.CSV"); Assert.IsFalse(result); } - + [TestMethod] public async Task TasteTestShouldReturnFalseGivenNullTasteTestResponse() { @@ -115,7 +115,7 @@ public async Task TasteTestShouldReturnFalseGivenTheVisaFormat() public async Task TasteTestShouldReturnFalseGivenTheWestpacFormat() { var subject = Arrange(); - subject.ReadTextChunkOverride = file => WestpacChequeCsvTestData.FirstTwoLines1(); + subject.ReadTextChunkOverride = file => WestpacChequeCsvTestData.FirstTwoLines1(); var result = await subject.TasteTestAsync(@"transumm.CSV"); Assert.IsFalse(result); } @@ -140,4 +140,4 @@ private AnzAccountStatementImporterV1TestHarness Arrange() return new AnzAccountStatementImporterV1TestHarness(BankImportUtilities, this.mockReaderWriterSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/AnzVisaStatementImporterV1Test.cs b/BudgetAnalyser.Engine.UnitTest/Statement/AnzVisaStatementImporterV1Test.cs index 798c763e..042506fc 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/AnzVisaStatementImporterV1Test.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/AnzVisaStatementImporterV1Test.cs @@ -140,4 +140,4 @@ private AnzVisaStatementImporterV1TestHarness Arrange() return new AnzVisaStatementImporterV1TestHarness(BankImportUtilities, this.mockReaderWriterSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/BankImportUtilitiesTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/BankImportUtilitiesTest.cs index 27a5b553..951e62c1 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/BankImportUtilitiesTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/BankImportUtilitiesTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.IO; using System.Linq; @@ -20,8 +20,8 @@ public class BankImportUtilitiesTest [ExpectedException(typeof(UnexpectedIndexException))] public void FetchBudgetBucketWithNegativeOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchBudgetBucket(testArray, -12, BucketRepositoryMock.Object); @@ -32,7 +32,7 @@ public void FetchBudgetBucketWithNegativeOutOfRangeIndexShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchBudgetBucketWithNullArrayShouldThrow() { - BankImportUtilities subject = CreateSubject(); + var subject = CreateSubject(); subject.FetchBudgetBucket(null, 2, BucketRepositoryMock.Object); @@ -43,8 +43,8 @@ public void FetchBudgetBucketWithNullArrayShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchBudgetBucketWithNullBucketRepositoryShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchBudgetBucket(testArray, 2, null); @@ -55,8 +55,8 @@ public void FetchBudgetBucketWithNullBucketRepositoryShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchBudgetBucketWithOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchBudgetBucket(testArray, 12, BucketRepositoryMock.Object); @@ -66,12 +66,12 @@ public void FetchBudgetBucketWithOutOfRangeIndexShouldThrow() [TestMethod] public void FetchBudgetBucketWithValidParamsShouldReturnBucketObject() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); var expectedResult = new SpentPerPeriodExpenseBucket("FUEL", "Fuel"); BucketRepositoryMock.Setup(m => m.GetByCode("FUEL")).Returns(expectedResult); - BudgetBucket result = subject.FetchBudgetBucket(testArray, 2, BucketRepositoryMock.Object); + var result = subject.FetchBudgetBucket(testArray, 2, BucketRepositoryMock.Object); BucketRepositoryMock.Verify(); Assert.AreSame(expectedResult, result); @@ -81,8 +81,8 @@ public void FetchBudgetBucketWithValidParamsShouldReturnBucketObject() [ExpectedException(typeof(InvalidDataException))] public void FetchDateWithInvalidDateShouldReturnMinDateTime() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDate(testArray, 3); @@ -93,8 +93,8 @@ public void FetchDateWithInvalidDateShouldReturnMinDateTime() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchDateWithNegativeOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDate(testArray, -12); @@ -105,7 +105,7 @@ public void FetchDateWithNegativeOutOfRangeIndexShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchDateWithNullArrayShouldThrow() { - BankImportUtilities subject = CreateSubject(); + var subject = CreateSubject(); subject.FetchDate(null, 2); @@ -116,8 +116,8 @@ public void FetchDateWithNullArrayShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchDateWithOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDate(testArray, 12); @@ -127,10 +127,10 @@ public void FetchDateWithOutOfRangeIndexShouldThrow() [TestMethod] public void FetchDateWithValidDateStringShouldReturnDate() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); - DateTime result = subject.FetchDate(testArray, 1); + var result = subject.FetchDate(testArray, 1); Assert.IsInstanceOfType(result, typeof(DateTime)); Assert.AreNotEqual(DateTime.MinValue, result); @@ -140,8 +140,8 @@ public void FetchDateWithValidDateStringShouldReturnDate() [ExpectedException(typeof(InvalidDataException))] public void FetchDecimalWithInvalidDecimalShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDecimal(testArray, 2); @@ -152,8 +152,8 @@ public void FetchDecimalWithInvalidDecimalShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchDecimalWithNegativeOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDecimal(testArray, -12); @@ -164,7 +164,7 @@ public void FetchDecimalWithNegativeOutOfRangeIndexShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchDecimalWithNullArrayShouldThrow() { - BankImportUtilities subject = CreateSubject(); + var subject = CreateSubject(); subject.FetchDecimal(null, 2); @@ -175,8 +175,8 @@ public void FetchDecimalWithNullArrayShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchDecimalWithOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchDecimal(testArray, 12); @@ -186,10 +186,10 @@ public void FetchDecimalWithOutOfRangeIndexShouldThrow() [TestMethod] public void FetchDecimalWithValidDecimalStringShouldReturnDecimal() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); - decimal result = subject.FetchDecimal(testArray, 0); + var result = subject.FetchDecimal(testArray, 0); Assert.IsInstanceOfType(result, typeof(decimal)); Assert.AreNotEqual(decimal.MinValue, result); @@ -199,8 +199,8 @@ public void FetchDecimalWithValidDecimalStringShouldReturnDecimal() [ExpectedException(typeof(InvalidDataException))] public void FetchGuidWithInvalidGuidShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchGuid(testArray, 2); @@ -211,8 +211,8 @@ public void FetchGuidWithInvalidGuidShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchGuidWithNegativeOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchGuid(testArray, -12); @@ -223,7 +223,7 @@ public void FetchGuidWithNegativeOutOfRangeIndexShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchGuidWithNullArrayShouldThrow() { - BankImportUtilities subject = CreateSubject(); + var subject = CreateSubject(); subject.FetchGuid(null, 2); @@ -234,8 +234,8 @@ public void FetchGuidWithNullArrayShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchGuidWithOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchGuid(testArray, 12); @@ -245,10 +245,10 @@ public void FetchGuidWithOutOfRangeIndexShouldThrow() [TestMethod] public void FetchGuidWithValidGuidStringShouldReturnGuid() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); - Guid result = subject.FetchGuid(testArray, 4); + var result = subject.FetchGuid(testArray, 4); Assert.IsInstanceOfType(result, typeof(Guid)); Assert.AreNotEqual(Guid.Empty, result); @@ -258,8 +258,8 @@ public void FetchGuidWithValidGuidStringShouldReturnGuid() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchStringWithNegativeOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchString(testArray, -12); @@ -270,7 +270,7 @@ public void FetchStringWithNegativeOutOfRangeIndexShouldThrow() [ExpectedException(typeof(ArgumentNullException))] public void FetchStringWithNullArrayShouldThrow() { - BankImportUtilities subject = CreateSubject(); + var subject = CreateSubject(); subject.FetchString(null, 2); @@ -281,8 +281,8 @@ public void FetchStringWithNullArrayShouldThrow() [ExpectedException(typeof(UnexpectedIndexException))] public void FetchStringWithOutOfRangeIndexShouldThrow() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); subject.FetchString(testArray, 12); @@ -292,10 +292,10 @@ public void FetchStringWithOutOfRangeIndexShouldThrow() [TestMethod] public void FetchStringWithValidStringShouldReturnString() { - BankImportUtilities subject = CreateSubject(); - string[] testArray = CreateTestArray(); + var subject = CreateSubject(); + var testArray = CreateTestArray(); - string result = subject.FetchString(testArray, 2); + var result = subject.FetchString(testArray, 2); Assert.IsInstanceOfType(result, typeof(string)); Assert.AreNotEqual(string.Empty, result); @@ -306,7 +306,7 @@ public void FetchStringWithValidStringShouldReturnString() public void FetchStringShouldRemoveQuotes() { var subject = CreateSubject(); - var myData = new[] { "\"Test String\"","no quotes","-21.45" }; + var myData = new[] { "\"Test String\"", "no quotes", "-21.45" }; Console.WriteLine($"Input:"); Array.ForEach(myData, x => Console.Write($"{x}, ")); var result1 = subject.FetchString(myData, 0); @@ -329,4 +329,4 @@ private string[] CreateTestArray() return new[] { "123.34", "14/04/2014", "FUEL", "42/12/2088", "A94B4FE5-4F43-43A6-8CD2-8430F45FB58D" }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/BankStatementImporterRepositoryTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/BankStatementImporterRepositoryTest.cs index 1b23a5c0..648af9fa 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/BankStatementImporterRepositoryTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/BankStatementImporterRepositoryTest.cs @@ -31,7 +31,7 @@ public async Task CanImportShouldReturnTrueGivenOneImporterCanImport() [TestMethod] public void CtorShouldConstructGivenValidListOfImporters() { - BankStatementImporterRepository subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsNotNull(subject); } @@ -55,7 +55,7 @@ public void CtorShouldThrowGivenNullListOfImporters() [ExpectedException(typeof(NotSupportedException))] public async Task ImportShouldThrowGivenNoImportersCanImport() { - StatementModel model = await Subject.ImportAsync("Foo.bar", new ChequeAccount("Cheque")); + var model = await Subject.ImportAsync("Foo.bar", new ChequeAccount("Cheque")); } [TestInitialize] @@ -74,4 +74,4 @@ private BankStatementImporterRepository CreateSubject() return new BankStatementImporterRepository(Importers.Select(i => i.Object)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/CsvOnDiskStatementModelRepositoryV1Test.cs b/BudgetAnalyser.Engine.UnitTest/Statement/CsvOnDiskStatementModelRepositoryV1Test.cs index 96cf6c0a..6851d253 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/CsvOnDiskStatementModelRepositoryV1Test.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/CsvOnDiskStatementModelRepositoryV1Test.cs @@ -228,19 +228,23 @@ public async Task WrittenDataShouldAutomaticallyStripCommas() var subject = Arrange(); var dto = BudgetAnalyserRawCsvTestDataV1.TransactionSetDtoTestData1(); dto.Transactions.Last().Reference3 = "corrupted,comma,data,for,csv"; - using (var stream = new MemoryStream()) - using (var writer = new StreamWriter(stream, Encoding.UTF8)) + await using var stream = new MemoryStream(); + await using (var writer = new StreamWriter(stream, Encoding.UTF8)) { await subject.WriteToStreamTest(dto, writer); stream.Position = 0; using (var reader = new StreamReader(stream)) { - int lineNumber = 0; + var lineNumber = 0; while (!reader.EndOfStream) { lineNumber++; var line = reader.ReadLine(); - if (lineNumber == 1) continue; + if (lineNumber == 1) + { + continue; + } + Assert.AreEqual(10, line.ToCharArray().Count(c => c == ','), $"Too many commas on line {lineNumber}: {line}"); } } @@ -263,4 +267,4 @@ private CsvOnDiskStatementModelRepositoryV1TestHarness ArrangeWithMockMappers(ID return new CsvOnDiskStatementModelRepositoryV1TestHarness(new BankImportUtilitiesTestHarness(), mapper, this.mockReaderWriterSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/DtoToStatementModelMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/DtoToStatementModelMapperTest.cs index 556f26b7..99aa67c3 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/DtoToStatementModelMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/DtoToStatementModelMapperTest.cs @@ -46,52 +46,52 @@ public void ShouldMapDurationInMonths() Assert.AreEqual(2, Result.DurationInMonths); } -// [TestMethod] -// public void CodifyTestData2() -// { -// var testData = StatementModelTestData.TestData2(); -// var mapper = new StatementModelToTransactionSetDtoMapper(new TransactionToTransactionDtoMapper()); -// var result = mapper.Map(testData, "skjgiuwguih2798yrg972hguoisi7fgiusgfs", @"C:\Foo\Bar.csv"); - -// Console.WriteLine(@" -//public TransactionSetDto TestData2() {{ -// return new TransactionSetDto() {{ -// Checksum = 252523523525, -// StorageKey = ""{0}"", -// LastImport = new DateTime({1}, {2}, {3}), -// VersionHash = ""uiwhgr8972y59872gh5972798gh"", -// Transactions = new List -// {{ {4} }}, -// }}; -//}} -//", result.StorageKey, result.LastImport.Year, result.LastImport.Month, result.LastImport.Day, GenerateTransactionsCode(result)); - -// } - -// private string GenerateTransactionsCode(TransactionSetDto result) -// { -// var builder = new StringBuilder(); -// foreach (var txn in result.Transactions) -// { -// builder.AppendFormat(@" -// new TransactionDto -// {{ -// Account = ""{0}"", -// Amount = {1}M, -// BudgetBucketCode = ""{2}"", -// Date = new DateTime({3}, {4}, {5}), -// Description = ""{6}"", -// Id = new Guid(""{7}""), -// Reference1 = ""{8}"", -// Reference2 = ""{9}"", -// Reference3 = ""{10}"", -// TransactionType = ""{11}"", -// }}, -//", txn.Account, txn.Amount, txn.BudgetBucketCode, txn.Date.Year, txn.Date.Month, txn.Date.Day, txn.Description, txn.Id, txn.Reference1, txn.Reference2, txn.Reference3, txn.TransactionType); -// } - -// return builder.ToString(); -// } + // [TestMethod] + // public void CodifyTestData2() + // { + // var testData = StatementModelTestData.TestData2(); + // var mapper = new StatementModelToTransactionSetDtoMapper(new TransactionToTransactionDtoMapper()); + // var result = mapper.Map(testData, "skjgiuwguih2798yrg972hguoisi7fgiusgfs", @"C:\Foo\Bar.csv"); + + // Console.WriteLine(@" + //public TransactionSetDto TestData2() {{ + // return new TransactionSetDto() {{ + // Checksum = 252523523525, + // StorageKey = ""{0}"", + // LastImport = new DateTime({1}, {2}, {3}), + // VersionHash = ""uiwhgr8972y59872gh5972798gh"", + // Transactions = new List + // {{ {4} }}, + // }}; + //}} + //", result.StorageKey, result.LastImport.Year, result.LastImport.Month, result.LastImport.Day, GenerateTransactionsCode(result)); + + // } + + // private string GenerateTransactionsCode(TransactionSetDto result) + // { + // var builder = new StringBuilder(); + // foreach (var txn in result.Transactions) + // { + // builder.AppendFormat(@" + // new TransactionDto + // {{ + // Account = ""{0}"", + // Amount = {1}M, + // BudgetBucketCode = ""{2}"", + // Date = new DateTime({3}, {4}, {5}), + // Description = ""{6}"", + // Id = new Guid(""{7}""), + // Reference1 = ""{8}"", + // Reference2 = ""{9}"", + // Reference3 = ""{10}"", + // TransactionType = ""{11}"", + // }}, + //", txn.Account, txn.Amount, txn.BudgetBucketCode, txn.Date.Year, txn.Date.Month, txn.Date.Day, txn.Description, txn.Id, txn.Reference1, txn.Reference2, txn.Reference3, txn.TransactionType); + // } + + // return builder.ToString(); + // } [TestMethod] public void ShouldMapFileName() @@ -108,11 +108,11 @@ public void ShouldMapLastImport() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_TransactionSetDto_StatementModel( - new FakeLogger(), - new Mapper_TransactionDto_Transaction( - new InMemoryAccountTypeRepository(), - new BucketBucketRepoAlwaysFind(), + var subject = new MapperTransactionSetDto2StatementModel( + new FakeLogger(), + new MapperTransactionDto2Transaction( + new InMemoryAccountTypeRepository(), + new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository())); Result = subject.ToModel(TestData); } @@ -120,8 +120,8 @@ public void TestInitialise() [TestMethod] public void TransactionsShouldBeInAscendingOrder() { - DateTime previous = DateTime.MinValue; - foreach (Transaction txn in Result.AllTransactions) + var previous = DateTime.MinValue; + foreach (var txn in Result.AllTransactions) { if (txn.Date < previous) { @@ -132,4 +132,4 @@ public void TransactionsShouldBeInAscendingOrder() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/DtoToTransactionMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/DtoToTransactionMapperTest.cs index 39f6e058..86717399 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/DtoToTransactionMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/DtoToTransactionMapperTest.cs @@ -14,25 +14,19 @@ public class DtoToTransactionMapperTest private static readonly Guid TransactionId = new Guid("7F921750-4467-4EA4-81E6-3EFD466341C6"); private Transaction Result { get; set; } - private TransactionDto TestData + private TransactionDto TestData => new TransactionDto { - get - { - return new TransactionDto - { - Id = TransactionId, - Account = StatementModelTestData.ChequeAccount.Name, - Amount = 123.99M, - BudgetBucketCode = TestDataConstants.PowerBucketCode, - Date = new DateTime(2014, 07, 31), - Description = "The quick brown poo", - Reference1 = "Reference 1", - Reference2 = "REference 23", - Reference3 = "REference 33", - TransactionType = "Credit Card Debit" - }; - } - } + Id = TransactionId, + Account = StatementModelTestData.ChequeAccount.Name, + Amount = 123.99M, + BudgetBucketCode = TestDataConstants.PowerBucketCode, + Date = new DateTime(2014, 07, 31), + Description = "The quick brown poo", + Reference1 = "Reference 1", + Reference2 = "REference 23", + Reference3 = "REference 33", + TransactionType = "Credit Card Debit" + }; [TestMethod] public void ShouldMapAccountType() @@ -97,8 +91,8 @@ public void ShouldMapTransactionType() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_TransactionDto_Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository()); + var subject = new MapperTransactionDto2Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository()); Result = subject.ToModel(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelGeneratorTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelGeneratorTest.cs index 78ff048b..d00e58d4 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelGeneratorTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelGeneratorTest.cs @@ -6,4 +6,4 @@ namespace BudgetAnalyser.Engine.UnitTest.Statement public class StatementModelGeneratorTest { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelTest.cs index ec4f9339..5546fdb3 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -144,40 +144,40 @@ private Transaction Transaction3 [TestMethod] public void PerformanceOfValidateTest() { - StatementModel subject = StatementModelTestData.TestData1(); - Stopwatch stopwatch = Stopwatch.StartNew(); + var subject = StatementModelTestData.TestData1(); + var stopwatch = Stopwatch.StartNew(); subject.ValidateAgainstDuplicates(); stopwatch.Stop(); Console.WriteLine("{0:N0} ms", stopwatch.ElapsedMilliseconds); - Assert.IsTrue(stopwatch.ElapsedMilliseconds < 250); + Assert.IsTrue(stopwatch.ElapsedMilliseconds < 500); // Should be less than 500ms on Github actions. Runs much faster locally <250ms } [TestMethod] public void ValidateShouldFailWhenDuplicates1() { - StatementModel statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Transaction3, Duplicate1 }); + var statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Transaction3, Duplicate1 }); Assert.IsTrue(statement.ValidateAgainstDuplicates().Any()); } [TestMethod] public void ValidateShouldFailWhenDuplicates2() { - StatementModel statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Duplicate2, Transaction3 }); + var statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Duplicate2, Transaction3 }); Assert.IsTrue(statement.ValidateAgainstDuplicates().Any()); } [TestMethod] public void ValidateShouldFailWhenDuplicates3() { - StatementModel statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Duplicate3, Transaction1, Transaction2, Transaction3 }); + var statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Duplicate3, Transaction1, Transaction2, Transaction3 }); Assert.IsTrue(statement.ValidateAgainstDuplicates().Any()); } [TestMethod] public void ValidateShouldPassWhenNoDuplicates() { - StatementModel statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Transaction3 }); + var statement = new StatementModel(new FakeLogger()).LoadTransactions(new List { Transaction1, Transaction2, Transaction3 }); Assert.IsFalse(statement.ValidateAgainstDuplicates().Any()); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelToDtoMapperTest.cs index 433091cd..6dd34282 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/StatementModelToDtoMapperTest.cs @@ -31,7 +31,7 @@ public void ShouldMapAllTransactionsAndHaveSameSum() [TestMethod] public void ShouldMapAllTransactionsEvenWhenFiltered() { - StatementModel testData = TestData; + var testData = TestData; testData.Filter(new GlobalFilterCriteria { BeginDate = new DateTime(2013, 07, 20), EndDate = new DateTime(2013, 08, 19) }); Act(testData); @@ -58,13 +58,13 @@ public void TestInitialise() private void Act(StatementModel testData) { - var subject = new Mapper_TransactionSetDto_StatementModel( - new FakeLogger(), - new Mapper_TransactionDto_Transaction( - new InMemoryAccountTypeRepository(), - new BucketBucketRepoAlwaysFind(), + var subject = new MapperTransactionSetDto2StatementModel( + new FakeLogger(), + new MapperTransactionDto2Transaction( + new InMemoryAccountTypeRepository(), + new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository())); Result = subject.ToDto(testData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionDtoTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionDtoTest.cs index b0ab3fd5..784d414b 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionDtoTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionDtoTest.cs @@ -10,8 +10,8 @@ public class TransactionDtoTest [Description("A test designed to break when new propperties are added to the TransactionDto. This is a trigger to update the mappers.")] public void NumberOfPropertiesShouldBe10() { - int dataProperties = typeof(TransactionDto).CountProperties(); + var dataProperties = typeof(TransactionDto).CountProperties(); Assert.AreEqual(10, dataProperties); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionTest.cs index 14906828..0d2e4f6e 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionTest.cs @@ -10,8 +10,8 @@ public class TransactionTest [Description("A test designed to break when new propperties are added to the Transaction. This is a trigger to update the mappers.")] public void NumberOfPropertiesShouldBe11() { - int dataProperties = typeof(Transaction).CountProperties(); + var dataProperties = typeof(Transaction).CountProperties(); Assert.AreEqual(11, dataProperties); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionToDtoMapperTest.cs b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionToDtoMapperTest.cs index bcb801ac..0eeaa005 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/TransactionToDtoMapperTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/TransactionToDtoMapperTest.cs @@ -14,25 +14,19 @@ public class TransactionToDtoMapperTest private static readonly Guid TransactionId = new Guid("7F921750-4467-4EA4-81E6-3EFD466341C6"); private TransactionDto Result { get; set; } - private Transaction TestData + private Transaction TestData => new Transaction { - get - { - return new Transaction - { - Id = TransactionId, - Account = StatementModelTestData.ChequeAccount, - Amount = 123.99M, - BudgetBucket = StatementModelTestData.PowerBucket, - Date = new DateTime(2014, 07, 31), - Description = "The quick brown poo", - Reference1 = "Reference 1", - Reference2 = "REference 23", - Reference3 = "REference 33", - TransactionType = StatementModelTestData.TransactionType - }; - } - } + Id = TransactionId, + Account = StatementModelTestData.ChequeAccount, + Amount = 123.99M, + BudgetBucket = StatementModelTestData.PowerBucket, + Date = new DateTime(2014, 07, 31), + Description = "The quick brown poo", + Reference1 = "Reference 1", + Reference2 = "REference 23", + Reference3 = "REference 33", + TransactionType = StatementModelTestData.TransactionType + }; [TestMethod] public void ShouldMapAccountType() @@ -97,8 +91,8 @@ public void ShouldMapTransactionType() [TestInitialize] public void TestInitialise() { - var subject = new Mapper_TransactionDto_Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository()); + var subject = new MapperTransactionDto2Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository()); Result = subject.ToDto(TestData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Statement/WestpacAccountStatementImporterV1Test.cs b/BudgetAnalyser.Engine.UnitTest/Statement/WestpacAccountStatementImporterV1Test.cs index eead591d..b614ac89 100644 --- a/BudgetAnalyser.Engine.UnitTest/Statement/WestpacAccountStatementImporterV1Test.cs +++ b/BudgetAnalyser.Engine.UnitTest/Statement/WestpacAccountStatementImporterV1Test.cs @@ -63,7 +63,7 @@ public async Task LoadShouldParseAGoodFileAndOutputIt() var result = await subject.LoadAsync("foo.bar", StatementModelTestData.ChequeAccount); Console.WriteLine("Date Type Description Amount "); - foreach(var txn in result.AllTransactions) + foreach (var txn in result.AllTransactions) { Console.WriteLine($"{txn.Date:dd-MMM-yy} {txn.TransactionType,10} {txn.Description,12} {txn.Amount,10}"); } @@ -155,4 +155,4 @@ private WestpacAccountStatementImporterV1TestHarness Arrange() return new WestpacAccountStatementImporterV1TestHarness(BankImportUtilities, this.mockReaderWriterSelector.Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/StringExtensionTest.cs b/BudgetAnalyser.Engine.UnitTest/StringExtensionTest.cs index 8153021b..34b8cc17 100644 --- a/BudgetAnalyser.Engine.UnitTest/StringExtensionTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/StringExtensionTest.cs @@ -234,4 +234,4 @@ public void SplitLines_ShouldReturnNull_GivenNullString() var lines = data.SplitLines(3); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/AnzChequeCsvTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/AnzChequeCsvTestData.cs index 8cb07bfa..58d36967 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/AnzChequeCsvTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/AnzChequeCsvTestData.cs @@ -55,4 +55,4 @@ internal static string FirstTwoLines1() return "Type,Details,Particulars,Code,Reference,Amount,Date,ForeignCurrencyAmount,ConversionCharge\r\nAtm Debit, Anz 1234567 Queen St, Anz S3A1234,Queen St, Anch 123456,-80.00,16 / 06 / 2014,,"; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/AnzVisaCsvTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/AnzVisaCsvTestData.cs index 19cd99c4..e0397858 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/AnzVisaCsvTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/AnzVisaCsvTestData.cs @@ -73,4 +73,4 @@ internal static string FirstTwoLines1() return "Card,Type,Amount,Details,TransactionDate,ProcessedDate,ForeignCurrencyAmount,ConversionCharge\r\n4323-****-****-1234,D,32.36,Z Queen Street Auckland Nz ,24/06/2014,25/06/2014,,\r\n"; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetAnalyserRawCsvTestDataV1.cs b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetAnalyserRawCsvTestDataV1.cs index cdc192ce..5dee864a 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetAnalyserRawCsvTestDataV1.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetAnalyserRawCsvTestDataV1.cs @@ -1,7 +1,7 @@ -using BudgetAnalyser.Engine.Budget; -using BudgetAnalyser.Engine.Statement.Data; -using System; +using System; using System.Collections.Generic; +using BudgetAnalyser.Engine.Budget; +using BudgetAnalyser.Engine.Statement.Data; namespace BudgetAnalyser.Engine.UnitTest.TestData { @@ -25,8 +25,9 @@ public static TransactionSetDto TransactionSetDtoTestData1() // "Payment,The Very Big Telco,202610963,095501328,B Smith,-91.98,2012-08-20T00:00:00.0000000,PHNET,CHEQUE,56b22788-d1e6-4a5d-a715-08b563dae678, ", // "Payment,The very cool Power Co,A B Smith,659792,Energyonline,-212.07,2012-08-20T00:00:00.0000000,POWER,CHEQUE,17b8c91c-5174-41a7-b382-b6a9ff52a11a, ", // "Credit Card Debit,Z Queen Street Auckland Nz,4367-****-****-3239,,,-28.49,2012-08-20T00:00:00.0000000,FUEL,VISA,bd12376a-6aac-4171-a23c-f85af168582f, " - var set = new TransactionSetDto(); - set.Transactions = new List + var set = new TransactionSetDto + { + Transactions = new List { new TransactionDto { @@ -103,6 +104,7 @@ public static TransactionSetDto TransactionSetDtoTestData1() Account = TestDataConstants.VisaAccountName, Id = new Guid("136e9010-9d07-4ddb-b7a3-abd209a23f44"), }, + } }; return set; @@ -208,4 +210,4 @@ public static IEnumerable TestData1() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetBucketTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetBucketTestData.cs index 23c4a0d0..abca490a 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetBucketTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetBucketTestData.cs @@ -10,10 +10,10 @@ public static IEnumerable BudgetModelTestData1Buckets { get { - BudgetModel budgetModel = BudgetModelTestData.CreateTestData1(); + var budgetModel = BudgetModelTestData.CreateTestData1(); return budgetModel.Expenses.Select(e => e.Bucket) .Union(budgetModel.Incomes.Select(i => i.Bucket)); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetModelTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetModelTestData.cs index 8ca95c97..b2fd4c77 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/BudgetModelTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/BudgetModelTestData.cs @@ -20,7 +20,7 @@ public static IEnumerable CreateBudgetBucketDtoTestData1() new BudgetBucketDto { Code = TestDataConstants.IncomeBucketCode, Type = BucketDtoType.Income, Description = "Salary from Lawn Mowing business" } }; } - + public static BudgetCollection CreateCollectionWith1And2() { var collection = new BudgetCollection( @@ -28,8 +28,10 @@ public static BudgetCollection CreateCollectionWith1And2() { CreateTestData1(), CreateTestData2() - }); - collection.StorageKey = @"C:\Temp\Foo.xaml"; + }) + { + StorageKey = @"C:\Temp\Foo.xaml" + }; return collection; } @@ -190,4 +192,4 @@ public static BudgetModel CreateTestData5() return budget; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookBuilder.cs b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookBuilder.cs index 86da1529..7fe14d76 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookBuilder.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookBuilder.cs @@ -183,10 +183,10 @@ public LedgerBookBuilder WithUnlockFlagSet() private void SetReconciliation(IReadOnlyDictionary ledgers, string remarks) { var recon = new LedgerEntryLine(this.tempReconDate, this.tempBankBalances) { Remarks = remarks }; - LedgerEntryLine previousRecon = Reconciliations.OrderByDescending(r => r.Date).FirstOrDefault(); + var previousRecon = Reconciliations.OrderByDescending(r => r.Date).FirstOrDefault(); var entries = new List(); - foreach (LedgerBucket ledgerBucket in this.ledgerBuckets) + foreach (var ledgerBucket in this.ledgerBuckets) { decimal openingBalance; if (previousRecon is null) @@ -195,7 +195,7 @@ private void SetReconciliation(IReadOnlyDictionary e.LedgerBucket == ledgerBucket); + var previousEntry = previousRecon.Entries.Single(e => e.LedgerBucket == ledgerBucket); openingBalance = previousEntry.Balance; } var entry = new LedgerEntry @@ -217,7 +217,7 @@ public class LedgerEntryTestDataBuilder public LedgerEntryTestDataBuilder(IEnumerable ledgers) { - foreach (LedgerBucket ledgerBucket in ledgers) + foreach (var ledgerBucket in ledgers) { this.ledgers.Add(ledgerBucket, new SpecificLedgerEntryTestDataBuilder(this)); } @@ -297,7 +297,7 @@ public class TransactionTestDataBuilder public TransactionTestDataBuilder WithBudgetCredit(decimal amount, DateTime? date = null, string automatchingRef = null) { - BudgetCreditLedgerTransaction budgetTxn = this.transactions.OfType().FirstOrDefault(); + var budgetTxn = this.transactions.OfType().FirstOrDefault(); if (budgetTxn is null) { budgetTxn = new BudgetCreditLedgerTransaction { AutoMatchingReference = automatchingRef, Date = date, Narrative = "Budgeted Amount" }; @@ -315,4 +315,4 @@ public TransactionTestDataBuilder WithCredit(decimal amount, string narrative, D } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookDtoTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookDtoTestData.cs index 500b5170..5d435b1f 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookDtoTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookDtoTestData.cs @@ -8,17 +8,17 @@ namespace BudgetAnalyser.Engine.UnitTest.TestData { internal static class LedgerBookDtoTestData { - private static readonly Guid id1 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A0"); - private static readonly Guid id10 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A9"); - private static readonly Guid id11 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6AA"); - private static readonly Guid id2 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A1"); - private static readonly Guid id3 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A2"); - private static readonly Guid id4 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A3"); - private static readonly Guid id5 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A4"); - private static readonly Guid id6 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A5"); - private static readonly Guid id7 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A6"); - private static readonly Guid id8 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A7"); - private static readonly Guid id9 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A8"); + private static readonly Guid Id1 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A0"); + private static readonly Guid Id10 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A9"); + private static readonly Guid Id11 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6AA"); + private static readonly Guid Id2 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A1"); + private static readonly Guid Id3 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A2"); + private static readonly Guid Id4 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A3"); + private static readonly Guid Id5 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A4"); + private static readonly Guid Id6 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A5"); + private static readonly Guid Id7 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A6"); + private static readonly Guid Id8 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A7"); + private static readonly Guid Id9 = new Guid("2647B4AF-4371-4DA6-B827-E93CCB98B6A8"); public static LedgerBookDto TestData1() { @@ -31,7 +31,7 @@ public static LedgerBookDto TestData1() var lines = new List(); - LedgerEntryLineDto line1 = AddEntryLineForTestData1(lines, new DateTime(2013, 12, 20)); + var line1 = AddEntryLineForTestData1(lines, new DateTime(2013, 12, 20)); line1.Entries.AddRange( new[] { @@ -43,14 +43,14 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id1, + Id = Id1, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id2, + Id = Id2, Amount = -195, Narrative = "Rates payment", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -65,7 +65,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id3, + Id = Id3, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -80,14 +80,14 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id4, + Id = Id4, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id5, + Id = Id5, Amount = -295.45M, Narrative = "Fix car", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -96,7 +96,7 @@ public static LedgerBookDto TestData1() } }); - LedgerEntryLineDto line2 = AddEntryLineForTestData1(lines, new DateTime(2014, 1, 20)); + var line2 = AddEntryLineForTestData1(lines, new DateTime(2014, 1, 20)); line2.Entries.AddRange( new[] { @@ -107,7 +107,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id6, + Id = Id6, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -121,7 +121,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id7, + Id = Id7, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -135,7 +135,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id8, + Id = Id8, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -144,7 +144,7 @@ public static LedgerBookDto TestData1() } }); - LedgerEntryLineDto line3 = AddEntryLineForTestData1(lines, new DateTime(2014, 02, 20)); + var line3 = AddEntryLineForTestData1(lines, new DateTime(2014, 02, 20)); line3.Entries.AddRange( new[] { @@ -155,7 +155,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id9, + Id = Id9, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -169,7 +169,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id10, + Id = Id10, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -183,7 +183,7 @@ public static LedgerBookDto TestData1() { new LedgerTransactionDto { - Id = id11, + Id = Id11, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -213,7 +213,7 @@ public static LedgerBookDto TestData2() var lines = new List(); - LedgerEntryLineDto line1 = AddEntryLineForTestData2(lines, new DateTime(2013, 12, 20)); + var line1 = AddEntryLineForTestData2(lines, new DateTime(2013, 12, 20)); line1.Entries.AddRange( new[] { @@ -225,7 +225,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id1, + Id = Id1, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -240,7 +240,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id2, + Id = Id2, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -255,7 +255,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id3, + Id = Id3, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -264,7 +264,7 @@ public static LedgerBookDto TestData2() } }); - LedgerEntryLineDto line2 = AddEntryLineForTestData2(lines, new DateTime(2014, 1, 20)); + var line2 = AddEntryLineForTestData2(lines, new DateTime(2014, 1, 20)); line2.Entries.AddRange( new[] { @@ -275,7 +275,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id4, + Id = Id4, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -289,7 +289,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id5, + Id = Id5, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -303,7 +303,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id6, + Id = Id6, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -312,7 +312,7 @@ public static LedgerBookDto TestData2() } }); - LedgerEntryLineDto line3 = AddEntryLineForTestData2(lines, new DateTime(2014, 02, 20)); + var line3 = AddEntryLineForTestData2(lines, new DateTime(2014, 02, 20)); line3.Entries.AddRange( new[] { @@ -323,14 +323,14 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id7, + Id = Id7, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id8, + Id = Id8, Amount = -195, Narrative = "Rates payment", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -344,7 +344,7 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id9, + Id = Id9, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -358,14 +358,14 @@ public static LedgerBookDto TestData2() { new LedgerTransactionDto { - Id = id10, + Id = Id10, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id11, + Id = Id11, Amount = -295.45M, Narrative = "Fix car", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -399,7 +399,7 @@ public static LedgerBookDto TestData3() var lines = new List(); - LedgerEntryLineDto line1 = AddEntryLineForTestData1(lines, new DateTime(2013, 12, 20)); + var line1 = AddEntryLineForTestData1(lines, new DateTime(2013, 12, 20)); line1.Entries.AddRange( new[] { @@ -411,14 +411,14 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id1, + Id = Id1, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id2, + Id = Id2, Amount = -195, Narrative = "Rates payment", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -433,7 +433,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id3, + Id = Id3, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -448,14 +448,14 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id4, + Id = Id4, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName }, new LedgerTransactionDto { - Id = id5, + Id = Id5, Amount = -295.45M, Narrative = "Fix car", TransactionType = typeof(CreditLedgerTransaction).FullName @@ -464,7 +464,7 @@ public static LedgerBookDto TestData3() } }); - LedgerEntryLineDto line2 = AddEntryLineForTestData1(lines, new DateTime(2014, 1, 20)); + var line2 = AddEntryLineForTestData1(lines, new DateTime(2014, 1, 20)); line2.Entries.AddRange( new[] { @@ -475,7 +475,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id6, + Id = Id6, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -489,7 +489,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id7, + Id = Id7, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -503,7 +503,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id8, + Id = Id8, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -512,7 +512,7 @@ public static LedgerBookDto TestData3() } }); - LedgerEntryLineDto line3 = AddEntryLineForTestData1(lines, new DateTime(2014, 02, 20)); + var line3 = AddEntryLineForTestData1(lines, new DateTime(2014, 02, 20)); line3.Entries.AddRange( new[] { @@ -523,7 +523,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id9, + Id = Id9, Amount = 75, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -537,7 +537,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id10, + Id = Id10, Amount = 21.15M, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -551,7 +551,7 @@ public static LedgerBookDto TestData3() { new LedgerTransactionDto { - Id = id11, + Id = Id11, Amount = 95, Narrative = "Budgeted Amount", TransactionType = typeof(BudgetCreditLedgerTransaction).FullName @@ -626,9 +626,9 @@ private static void UpdateLineBalances(LedgerEntryLineDto currentLine, LedgerEnt return; } - foreach (LedgerEntryDto entry in currentLine.Entries) + foreach (var entry in currentLine.Entries) { - LedgerEntryDto previousEntry = previousLine.Entries.Single(e => e.BucketCode == entry.BucketCode); + var previousEntry = previousLine.Entries.Single(e => e.BucketCode == entry.BucketCode); entry.Balance = previousEntry.Balance + entry.Transactions.Sum(t => t.Amount); if (entry.Balance < 0) { @@ -637,4 +637,4 @@ private static void UpdateLineBalances(LedgerEntryLineDto currentLine, LedgerEnt } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookTestData.cs index ce096d93..eed11341 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/LedgerBookTestData.cs @@ -66,7 +66,7 @@ public static LedgerBook TestData1() StorageKey = "C:\\Folder\\book1.xml" }; - LedgerEntryLine line = CreateLine(new DateTime(2013, 06, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 2500) }, "Lorem ipsum"); + var line = CreateLine(new DateTime(2013, 06, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 2500) }, "Lorem ipsum"); SetEntriesForTesting( line, new List @@ -94,9 +94,9 @@ public static LedgerBook TestData1() var list = new List { line }; - LedgerEntry previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); - LedgerEntry previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); - LedgerEntry previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); + var previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); + var previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); list.Add( CreateLine(new DateTime(2013, 07, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 3700) }, "dolor amet set").SetEntriesForTesting( @@ -199,9 +199,9 @@ public static LedgerBook TestData2() }) }; - LedgerEntry previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); - LedgerEntry previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); - LedgerEntry previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); + var previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); + var previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); list.Add( CreateLine(new DateTime(2013, 07, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 3700) }, "dolor amet set").SetEntriesForTesting( @@ -231,7 +231,7 @@ public static LedgerBook TestData2() previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); - LedgerEntryLine line = CreateLine( + var line = CreateLine( new DateTime(2013, 08, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 2950) }, "The quick brown fox jumped over the lazy dog").SetEntriesForTesting( @@ -393,9 +393,9 @@ public static LedgerBook TestData4() }) }; - LedgerEntry previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); - LedgerEntry previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); - LedgerEntry previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); + var previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); + var previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); list.Add( CreateLine(new DateTime(2013, 07, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 3700) }, "dolor amet set").SetEntriesForTesting( @@ -425,7 +425,7 @@ public static LedgerBook TestData4() previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); - LedgerEntryLine line = CreateLine( + var line = CreateLine( new DateTime(2013, 08, 15), new[] { new BankBalance(StatementModelTestData.ChequeAccount, 2750), new BankBalance(StatementModelTestData.SavingsAccount, 200) }, "The quick brown fox jumped over the lazy dog").SetEntriesForTesting( @@ -464,15 +464,7 @@ public static LedgerBook TestData4() /// public static LedgerBook TestData5(Func ctor = null) { - LedgerBook book; - if (ctor is not null) - { - book = ctor(); - } - else - { - book = new LedgerBook(); - } + var book = ctor is not null ? ctor() : new LedgerBook(); book.Name = "Test Data 5 Book"; book.Modified = new DateTime(2013, 12, 16); book.StorageKey = "C:\\Folder\\book5.xml"; @@ -512,10 +504,10 @@ public static LedgerBook TestData5(Func ctor = null) }) }; - LedgerEntry previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); - LedgerEntry previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); - LedgerEntry previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); - LedgerEntry previousInsEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.InsuranceHomeBucketCode); + var previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); + var previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); + var previousInsEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.InsuranceHomeBucketCode); list.Add( CreateLine( @@ -553,7 +545,7 @@ public static LedgerBook TestData5(Func ctor = null) previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); previousInsEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.InsuranceHomeBucketCode); - LedgerEntryLine line = CreateLine( + var line = CreateLine( new DateTime(2013, 08, 15), new[] { new BankBalance(ChequeAccount, 3050), new BankBalance(SavingsAccount, 1000) }, "The quick brown fox jumped over the lazy dog").SetEntriesForTesting( @@ -598,15 +590,7 @@ public static LedgerBook TestData5(Func ctor = null) /// public static LedgerBook TestData6(Func ctor = null) { - LedgerBook book; - if (ctor is not null) - { - book = ctor(); - } - else - { - book = new LedgerBook(); - } + var book = ctor is not null ? ctor() : new LedgerBook(); book.Name = "Test Data 6 Book"; book.Modified = new DateTime(2013, 08, 15); book.StorageKey = "C:\\FakeFolder\\book6.xml"; @@ -646,10 +630,10 @@ public static LedgerBook TestData6(Func ctor = null) }) }; - LedgerEntry previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); - LedgerEntry previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); - LedgerEntry previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); - LedgerEntry previousInsEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.InsuranceHomeBucketCode); + var previousHairEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.HairBucketCode); + var previousPowerEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PowerBucketCode); + var previousPhoneEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.PhoneBucketCode); + var previousInsEntry = list.Last().Entries.Single(e => e.LedgerBucket.BudgetBucket.Code == TestDataConstants.InsuranceHomeBucketCode); list.Add( CreateLine( @@ -695,15 +679,19 @@ public static LedgerBook TestData6(Func ctor = null) /// internal static void Finalise(LedgerBook book, bool unlock = false) { - if (book.Reconciliations.None()) return; + if (book.Reconciliations.None()) + { + return; + } + var ledgers = new Dictionary(); - foreach (LedgerEntryLine line in book.Reconciliations) + foreach (var line in book.Reconciliations) { if (!unlock) { PrivateAccessor.SetProperty(line, "IsNew", false); } - foreach (LedgerEntry entry in line.Entries) + foreach (var entry in line.Entries) { if (!unlock) { @@ -732,7 +720,7 @@ internal static LedgerEntryLine SetEntriesForTesting(this LedgerEntryLine line, internal static LedgerEntry SetTransactionsForTesting(this LedgerEntry entry, List transactions) { PrivateAccessor.SetField(entry, "transactions", transactions); - decimal newBalance = entry.Balance + entry.NetAmount; + var newBalance = entry.Balance + entry.NetAmount; entry.Balance = newBalance < 0 ? 0 : newBalance; return entry; } @@ -748,4 +736,4 @@ private static LedgerEntryLine CreateLine(DateTime date, IEnumerable RawTestData1() .ExtractEmbeddedResourceAsXamlObject>("BudgetAnalyser.Engine.UnitTest.TestData.MatchingRulesTestData.xml"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerated.cs b/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerated.cs index f89e78f8..1c643fc5 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerated.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerated.cs @@ -2526,4 +2526,4 @@ public static IEnumerable TestData1() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerator.cs b/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerator.cs index 6d445409..e4fa921f 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerator.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/MatchingRulesTestDataGenerator.cs @@ -1,4 +1,4 @@ -//using System; +//using System; //using System.Collections.Generic; //using System.Diagnostics; //using System.Linq; @@ -98,4 +98,4 @@ // return string.Format("\"{0}\"", description); // } // } -//} \ No newline at end of file +//} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelBuilder.cs b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelBuilder.cs index a33cc07d..d29be8ec 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelBuilder.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelBuilder.cs @@ -61,4 +61,4 @@ public StatementModelBuilder TestData5() return this; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestData.cs index fc413da7..1538988a 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestData.cs @@ -37,7 +37,7 @@ public static StatementModel TestData1() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions1(); + var transactions = CreateTransactions1(); statement.LoadTransactions(transactions); return statement; } @@ -54,7 +54,7 @@ public static StatementModel TestData2() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions2(); + var transactions = CreateTransactions2(); statement.LoadTransactions(transactions); return statement; } @@ -92,7 +92,7 @@ public static StatementModel TestData3() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions3(); + var transactions = CreateTransactions3(); statement.LoadTransactions(transactions); return statement; } @@ -111,7 +111,7 @@ public static StatementModel TestData4() LastImport = new DateTime(2013, 08, 15) }; - List transactions = CreateTransactions3().ToList(); + var transactions = CreateTransactions3().ToList(); transactions.AddRange(CreateTransactions1()); statement.LoadTransactions(transactions); return statement; @@ -132,7 +132,7 @@ public static StatementModel TestData5() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions5(); + var transactions = CreateTransactions5(); statement.LoadTransactions(transactions); return statement; } @@ -581,4 +581,4 @@ private static IEnumerable CreateTransactions5() }; return transactions; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerated.cs b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerated.cs index 04a77d16..945b3f59 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerated.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerated.cs @@ -20,4 +20,4 @@ public static StatementModel TestDataGenerated() return null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerator.cs b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerator.cs index 0d964e69..0d3e6cf5 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerator.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/StatementModelTestDataGenerator.cs @@ -82,4 +82,4 @@ //}"); // End Method // } // } -//} \ No newline at end of file +//} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/TestDataConstants.cs b/BudgetAnalyser.Engine.UnitTest/TestData/TestDataConstants.cs index 6c6d4f1a..69466295 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/TestDataConstants.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/TestDataConstants.cs @@ -30,4 +30,4 @@ public static class TestDataConstants public const string VisaAccountName = "VISA"; public const string WaterBucketCode = "WATER"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/TransactionSetDtoTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/TransactionSetDtoTestData.cs index ab7174ab..e785086e 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/TransactionSetDtoTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/TransactionSetDtoTestData.cs @@ -150,4 +150,4 @@ public static TransactionSetDto TestData2() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestData/WestpacChequeCsvTestData.cs b/BudgetAnalyser.Engine.UnitTest/TestData/WestpacChequeCsvTestData.cs index 27590154..724c7482 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestData/WestpacChequeCsvTestData.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestData/WestpacChequeCsvTestData.cs @@ -54,4 +54,4 @@ public static IEnumerable TestData2() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzAccountStatementImporterV1TestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzAccountStatementImporterV1TestHarness.cs index ee253af6..54c9b036 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzAccountStatementImporterV1TestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzAccountStatementImporterV1TestHarness.cs @@ -18,22 +18,16 @@ public AnzAccountStatementImporterV1TestHarness([NotNull] BankImportUtilities im protected override Task> ReadLinesAsync(string fileName) { - if (ReadLinesOverride is null) - { - return Task.FromResult((IEnumerable)new string[] { }); - } - - return Task.FromResult(ReadLinesOverride(fileName)); + return ReadLinesOverride is null + ? Task.FromResult((IEnumerable)new string[] { }) + : Task.FromResult(ReadLinesOverride(fileName)); } protected override Task ReadTextChunkAsync(string filePath) { - if (ReadTextChunkOverride is null) - { - return Task.FromResult("Type,Details,Particulars,Code,Reference,Amount,Date,ForeignCurrencyAmount,ConversionCharge\r\nAtm Debit,Anz 1234567 Queen St,Anz S3A1234,Queen St,Anch 123456,-80.00,16/06/2014,,"); - } - - return Task.FromResult(ReadTextChunkOverride(filePath)); + return ReadTextChunkOverride is null + ? Task.FromResult("Type,Details,Particulars,Code,Reference,Amount,Date,ForeignCurrencyAmount,ConversionCharge\r\nAtm Debit,Anz 1234567 Queen St,Anz S3A1234,Queen St,Anch 123456,-80.00,16/06/2014,,") + : Task.FromResult(ReadTextChunkOverride(filePath)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzVisaStatementImporterV1TestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzVisaStatementImporterV1TestHarness.cs index 3c9bf745..e968339c 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzVisaStatementImporterV1TestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/AnzVisaStatementImporterV1TestHarness.cs @@ -18,22 +18,16 @@ public AnzVisaStatementImporterV1TestHarness([NotNull] BankImportUtilities impor protected override Task> ReadLinesAsync(string fileName) { - if (ReadLinesOverride is null) - { - return Task.FromResult((IEnumerable)new List()); - } - - return Task.FromResult(ReadLinesOverride(fileName)); + return ReadLinesOverride is null + ? Task.FromResult((IEnumerable)new List()) + : Task.FromResult(ReadLinesOverride(fileName)); } protected override Task ReadTextChunkAsync(string filePath) { - if (ReadTextChunkOverride is null) - { - return Task.FromResult("Card,Type,Amount,Details,TransactionDate,ProcessedDate,ForeignCurrencyAmount,ConversionCharge\r\n4323-****-****-1234,D,32.36,Z Queen Street Auckland Nz ,24/06/2014,25/06/2014,,\r\n"); - } - - return Task.FromResult(ReadTextChunkOverride(filePath)); + return ReadTextChunkOverride is null + ? Task.FromResult("Card,Type,Amount,Details,TransactionDate,ProcessedDate,ForeignCurrencyAmount,ConversionCharge\r\n4323-****-****-1234,D,32.36,Z Queen Street Auckland Nz ,24/06/2014,25/06/2014,,\r\n") + : Task.FromResult(ReadTextChunkOverride(filePath)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/BankImportUtilitiesTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/BankImportUtilitiesTestHarness.cs index 35f9bb43..3f33a717 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/BankImportUtilitiesTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/BankImportUtilitiesTestHarness.cs @@ -21,4 +21,4 @@ internal override void AbortIfFileDoesntExist(string fileName) AbortIfFileDoesntExistOverride(fileName); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/BucketBucketRepoAlwaysFind.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/BucketBucketRepoAlwaysFind.cs index 31b95fed..de8287be 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/BucketBucketRepoAlwaysFind.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/BucketBucketRepoAlwaysFind.cs @@ -8,7 +8,7 @@ public class BucketBucketRepoAlwaysFind : InMemoryBudgetBucketRepository { private readonly string projectPrefix; - public BucketBucketRepoAlwaysFind() : base(new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory())) + public BucketBucketRepoAlwaysFind() : base(new MapperBudgetBucketDtoBudgetBucket(new BudgetBucketFactory())) { InitialiseMandatorySpecialBuckets(); this.projectPrefix = string.Format(FixedBudgetProjectBucket.ProjectCodeTemplateWithPrefix, string.Empty); @@ -31,12 +31,9 @@ public override BudgetBucket GetByCode(string code) return SurplusBucket; } - if (code.StartsWith(this.projectPrefix)) - { - return GetOrCreateNew(code, () => new FixedBudgetProjectBucket(code, code, 100000M)); - } - - return GetOrCreateNew(code, () => new SavedUpForExpenseBucket(code, code)); + return code.StartsWith(this.projectPrefix) + ? GetOrCreateNew(code, () => new FixedBudgetProjectBucket(code, code, 100000M)) + : GetOrCreateNew(code, () => new SavedUpForExpenseBucket(code, code)); } public override void Initialise(IEnumerable buckets) @@ -49,4 +46,4 @@ public override bool IsValidCode(string code) return true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetBucketTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetBucketTestHarness.cs index 0fe5cb24..1e2850ab 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetBucketTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetBucketTestHarness.cs @@ -12,4 +12,4 @@ public BudgetBucketTestHarness(string code, string name) : base(code, name) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetModelFake.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetModelFake.cs index 7e8bcca3..f6b4cd08 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetModelFake.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/BudgetModelFake.cs @@ -11,12 +11,7 @@ public class BudgetModelFake : BudgetModel internal override bool Validate(StringBuilder validationMessages) { - if (ValidateOverride is not null) - { - return ValidateOverride(validationMessages); - } - - return base.Validate(validationMessages); + return ValidateOverride is not null ? ValidateOverride(validationMessages) : base.Validate(validationMessages); } protected override void Initialise() @@ -30,4 +25,4 @@ protected override void Initialise() base.Initialise(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/CsvOnDiskStatementModelRepositoryV1TestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/CsvOnDiskStatementModelRepositoryV1TestHarness.cs index 7e409dfc..67aa3cc9 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/CsvOnDiskStatementModelRepositoryV1TestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/CsvOnDiskStatementModelRepositoryV1TestHarness.cs @@ -15,9 +15,9 @@ internal class CsvOnDiskStatementModelRepositoryV1TestHarness : CsvOnDiskStateme public CsvOnDiskStatementModelRepositoryV1TestHarness(BankImportUtilities importUtilities, IReaderWriterSelector readerWriterSelector) : base(importUtilities, new FakeLogger(), - new Mapper_TransactionSetDto_StatementModel( - new FakeLogger(), - new Mapper_TransactionDto_Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository())), + new MapperTransactionSetDto2StatementModel( + new FakeLogger(), + new MapperTransactionDto2Transaction(new InMemoryAccountTypeRepository(), new BucketBucketRepoAlwaysFind(), new InMemoryTransactionTypeRepository())), readerWriterSelector) { } @@ -37,27 +37,21 @@ public CsvOnDiskStatementModelRepositoryV1TestHarness( protected override Task> ReadLinesAsync(string fileName, bool isEncrypted) { - if (ReadLinesOverride is null) - { - return Task.FromResult>(new List()); - } - - return Task.FromResult(ReadLinesOverride(fileName)); + return ReadLinesOverride is null + ? Task.FromResult>(new List()) + : Task.FromResult(ReadLinesOverride(fileName)); } protected override Task> ReadLinesAsync(string fileName, int lines, bool isEncrypted) { - if (ReadLinesOverride is null) - { - return Task.FromResult>(new List()); - } - - return Task.FromResult(ReadLinesOverride(fileName).Take(lines)); + return ReadLinesOverride is null + ? Task.FromResult>(new List()) + : Task.FromResult(ReadLinesOverride(fileName).Take(lines)); } internal async Task WriteToStreamTest(TransactionSetDto dto, StreamWriter writer) { - await this.WriteToStream(dto, writer); + await WriteToStream(dto, writer); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/DtoMapperStub.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/DtoMapperStub.cs index b6ec6145..48d760de 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/DtoMapperStub.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/DtoMapperStub.cs @@ -23,4 +23,4 @@ public TDestination ToModel(TSource dto) throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeLogger.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeLogger.cs index 31165b83..03128b1a 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeLogger.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeLogger.cs @@ -3,7 +3,7 @@ namespace BudgetAnalyser.Engine.UnitTest.TestHarness { - [AutoRegisterWithIoC(Named = "Named Logger", SingleInstance = true)] + [AutoRegisterWithIoC(Named = "Named Logger", SingleInstance = true)] public class FakeLogger : ILogger { public LogLevel LogLevelFilter { get; set; } @@ -44,4 +44,4 @@ public void LogWarning(Func logEntryBuilder) Debug.WriteLine(logEntryBuilder(this)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeMonitorableDependencies.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeMonitorableDependencies.cs index 439b50c4..f59598eb 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeMonitorableDependencies.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/FakeMonitorableDependencies.cs @@ -43,12 +43,6 @@ internal override object RetrieveDependency(Type key) /// /// Gets a list of supported types /// - internal override IEnumerable SupportedWidgetDependencyTypes - { - get - { - return new List(); - } - } + internal override IEnumerable SupportedWidgetDependencyTypes => new List(); } } diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/LedgerBookTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/LedgerBookTestHarness.cs index 8756af4d..20897219 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/LedgerBookTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/LedgerBookTestHarness.cs @@ -24,4 +24,4 @@ internal override void Reconcile(ReconciliationResult newRecon) ReconcileOverride?.Invoke(newRecon); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/WestpacAccountStatementImporterV1TestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/WestpacAccountStatementImporterV1TestHarness.cs index afefa9c5..8d9ca6a7 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/WestpacAccountStatementImporterV1TestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/WestpacAccountStatementImporterV1TestHarness.cs @@ -18,22 +18,16 @@ public WestpacAccountStatementImporterV1TestHarness([NotNull] BankImportUtilitie protected override Task> ReadLinesAsync(string fileName) { - if (ReadLinesOverride is null) - { - return Task.FromResult((IEnumerable)new string[] { }); - } - - return Task.FromResult(ReadLinesOverride(fileName)); + return ReadLinesOverride is null + ? Task.FromResult((IEnumerable)new string[] { }) + : Task.FromResult(ReadLinesOverride(fileName)); } protected override Task ReadTextChunkAsync(string filePath) { - if (ReadTextChunkOverride is null) - { - return Task.FromResult("Date,Amount,Other Party,Description,Reference,Particulars,Analysis Code\r\n20/07/2020,-12.50,\"Brew On Quay\",\"EFTPOS TRANSACTION\",\"20-16:10-941\",\"************\",\"7786 30941\""); - } - - return Task.FromResult(ReadTextChunkOverride(filePath)); + return ReadTextChunkOverride is null + ? Task.FromResult("Date,Amount,Other Party,Description,Reference,Particulars,Analysis Code\r\n20/07/2020,-12.50,\"Brew On Quay\",\"EFTPOS TRANSACTION\",\"20-16:10-941\",\"************\",\"7786 30941\"") + : Task.FromResult(ReadTextChunkOverride(filePath)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskApplicationDatabaseRepositoryTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskApplicationDatabaseRepositoryTestHarness.cs index cf5f0977..5f2fa1ef 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskApplicationDatabaseRepositoryTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskApplicationDatabaseRepositoryTestHarness.cs @@ -1,8 +1,8 @@ -using JetBrains.Annotations; -using BudgetAnalyser.Engine.Persistence; +using BudgetAnalyser.Engine.Persistence; +using JetBrains.Annotations; +using Portable.Xaml; using Rees.TangyFruitMapper; using Rees.UnitTestUtilities; -using Portable.Xaml; namespace BudgetAnalyser.Engine.UnitTest.TestHarness { @@ -19,12 +19,7 @@ public XamlOnDiskApplicationDatabaseRepositoryTestHarness( protected override bool FileExists(string budgetAnalyserDataStorage) { - if (FileExistsOverride is null) - { - return base.FileExists(budgetAnalyserDataStorage); - } - - return FileExistsOverride(budgetAnalyserDataStorage); + return FileExistsOverride is null ? base.FileExists(budgetAnalyserDataStorage) : FileExistsOverride(budgetAnalyserDataStorage); } protected override string LoadXamlAsString(string fileName) @@ -34,4 +29,4 @@ protected override string LoadXamlAsString(string fileName) return StorageRootDtoSerialised; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskLedgerBookRepositoryTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskLedgerBookRepositoryTestHarness.cs index 9c30f390..ce9a9b1c 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskLedgerBookRepositoryTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskLedgerBookRepositoryTestHarness.cs @@ -31,7 +31,7 @@ protected override string LoadXamlAsString(string fileName) { if (LoadXamlAsStringOverride is null) { - string result = base.LoadXamlAsString(fileName); + var result = base.LoadXamlAsString(fileName); Debug.WriteLine(result); return result; } @@ -44,7 +44,7 @@ protected override async Task LoadXamlFromDiskAsync(string fileNa if (LoadXamlFromDiskFromEmbeddedResources) { LedgerBookDto = GetType().Assembly.ExtractEmbeddedResourceAsXamlObject(fileName, true); - EventHandler handler = DtoDeserialised; + var handler = DtoDeserialised; handler?.Invoke(this, EventArgs.Empty); return LedgerBookDto; @@ -71,4 +71,4 @@ protected override string Serialise(LedgerBookDto dataEntity) return SerialisedData; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskMatchingRuleRepositoryTestHarness.cs b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskMatchingRuleRepositoryTestHarness.cs index f97235d0..e75c4421 100644 --- a/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskMatchingRuleRepositoryTestHarness.cs +++ b/BudgetAnalyser.Engine.UnitTest/TestHarness/XamlOnDiskMatchingRuleRepositoryTestHarness.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using JetBrains.Annotations; using BudgetAnalyser.Engine.Matching; using BudgetAnalyser.Engine.Matching.Data; +using JetBrains.Annotations; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.UnitTest.TestHarness @@ -21,12 +21,7 @@ internal class XamlOnDiskMatchingRuleRepositoryTestHarness : XamlOnDiskMatchingR protected override async Task> LoadFromDiskAsync(string fileName, bool isEncrypted) { - if (LoadFromDiskOveride is null) - { - return await base.LoadFromDiskAsync(fileName, isEncrypted); - } - - return LoadFromDiskOveride(fileName); + return LoadFromDiskOveride is null ? await base.LoadFromDiskAsync(fileName, isEncrypted) : LoadFromDiskOveride(fileName); } protected override async Task SaveToDiskAsync(string fileName, IEnumerable dataEntities, bool isEncrypted) @@ -46,4 +41,4 @@ protected override string Serialise(IEnumerable dataEntity) return SerialisedData; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/TypeExtensions.cs b/BudgetAnalyser.Engine.UnitTest/TypeExtensions.cs index 5b42d074..9dda3eba 100644 --- a/BudgetAnalyser.Engine.UnitTest/TypeExtensions.cs +++ b/BudgetAnalyser.Engine.UnitTest/TypeExtensions.cs @@ -8,9 +8,9 @@ public static class TypeExtensions { public static int CountProperties(this Type instance) { - PropertyInfo[] properties = instance.GetProperties(); + var properties = instance.GetProperties(); properties.ToList().ForEach(p => Console.WriteLine(p.Name)); return properties.Length; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Widgets/BudgetBucketMonitorWidgetTest.cs b/BudgetAnalyser.Engine.UnitTest/Widgets/BudgetBucketMonitorWidgetTest.cs index 19cbacf8..bf82ec46 100644 --- a/BudgetAnalyser.Engine.UnitTest/Widgets/BudgetBucketMonitorWidgetTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Widgets/BudgetBucketMonitorWidgetTest.cs @@ -2,10 +2,10 @@ using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Ledger; using BudgetAnalyser.Engine.Statement; -using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.Engine.UnitTest.Helper; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; +using BudgetAnalyser.Engine.Widgets; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.Engine.UnitTest.Widgets @@ -32,8 +32,10 @@ public void OutputTestData() [TestInitialize] public void TestInitialise() { - this.subject = new BudgetBucketMonitorWidget(); - this.subject.BucketCode = StatementModelTestData.PhoneBucket.Code; + this.subject = new BudgetBucketMonitorWidget + { + BucketCode = StatementModelTestData.PhoneBucket.Code + }; this.bucketRepo = new BucketBucketRepoAlwaysFind(); this.criteriaTestData = new GlobalFilterCriteria @@ -44,7 +46,7 @@ public void TestInitialise() CreateStatementTestData(); - BudgetModel budgetModel = BudgetModelTestData.CreateTestData5(); + var budgetModel = BudgetModelTestData.CreateTestData5(); this.budgetTestData = new BudgetCurrencyContext(new BudgetCollection(budgetModel), budgetModel); CreateLedgerBookTestData(); @@ -131,4 +133,4 @@ public void Update_ShouldExcludeAutoMatchedTransactionsInCalculation() Assert.AreEqual(130.00, this.subject.Value); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Widgets/OverspentWarningTest.cs b/BudgetAnalyser.Engine.UnitTest/Widgets/OverspentWarningTest.cs index da90683f..6936edf2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Widgets/OverspentWarningTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Widgets/OverspentWarningTest.cs @@ -1,9 +1,9 @@ using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Ledger; using BudgetAnalyser.Engine.Statement; -using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; +using BudgetAnalyser.Engine.Widgets; using Moq; using Range = Moq.Range; @@ -160,4 +160,4 @@ private void SetLedgerBalancesFakeDataSomeOverspentBuckets() }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingActualSurplusWidgetTest.cs b/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingActualSurplusWidgetTest.cs index cf5b414d..0c9b5708 100644 --- a/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingActualSurplusWidgetTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingActualSurplusWidgetTest.cs @@ -5,12 +5,12 @@ using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Ledger; using BudgetAnalyser.Engine.Statement; -using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.Engine.UnitTest.Helper; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using BudgetAnalyser.Engine.Widgets; using Castle.Core.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.Engine.UnitTest.Widgets { @@ -1058,4 +1058,4 @@ public static StatementModel TestDataGenerated() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingSurplusWidgetTest.cs b/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingSurplusWidgetTest.cs index 6dcd8cc3..ec47cad2 100644 --- a/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingSurplusWidgetTest.cs +++ b/BudgetAnalyser.Engine.UnitTest/Widgets/RemainingSurplusWidgetTest.cs @@ -6,10 +6,10 @@ using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Ledger; using BudgetAnalyser.Engine.Statement; -using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.Engine.UnitTest.Helper; using BudgetAnalyser.Engine.UnitTest.TestData; using BudgetAnalyser.Engine.UnitTest.TestHarness; +using BudgetAnalyser.Engine.Widgets; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.Engine.UnitTest.Widgets @@ -48,7 +48,7 @@ public void TestInitialise() StatementModelTestDataForThisTest.BudgetBucketRepo = this.bucketRepo; this.statementTestData = StatementModelTestDataForThisTest.TestDataGenerated(); - BudgetModel budgetModel = BudgetModelTestData.CreateTestData1(); + var budgetModel = BudgetModelTestData.CreateTestData1(); this.budgetTestData = new BudgetCurrencyContext(new BudgetCollection(budgetModel), budgetModel); this.ledgerBookTestData = new LedgerBookBuilder @@ -630,4 +630,4 @@ public static StatementModel TestDataGenerated() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ApplicationDataType.cs b/BudgetAnalyser.Engine/ApplicationDataType.cs index f97a3f00..68c17057 100644 --- a/BudgetAnalyser.Engine/ApplicationDataType.cs +++ b/BudgetAnalyser.Engine/ApplicationDataType.cs @@ -30,4 +30,4 @@ public enum ApplicationDataType /// Tasks, } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/AutoRegisterWithIoCAttribute.cs b/BudgetAnalyser.Engine/AutoRegisterWithIoCAttribute.cs index 2cc1d7e3..a8711abb 100644 --- a/BudgetAnalyser.Engine/AutoRegisterWithIoCAttribute.cs +++ b/BudgetAnalyser.Engine/AutoRegisterWithIoCAttribute.cs @@ -33,4 +33,4 @@ public sealed class AutoRegisterWithIoCAttribute : Attribute /// public bool SingleInstance { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/Account.cs b/BudgetAnalyser.Engine/BankAccount/Account.cs index 0594accb..66f6f531 100644 --- a/BudgetAnalyser.Engine/BankAccount/Account.cs +++ b/BudgetAnalyser.Engine/BankAccount/Account.cs @@ -40,16 +40,16 @@ protected Account() public string Name { get; protected set; } /// - /// Determines whether the specified , is equal to this instance. Or if the + /// Determines whether the specified , is equal to this instance. Or if the /// Equals the other /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object? obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -57,11 +57,7 @@ public override bool Equals(object? obj) { return true; } - if (obj.GetType() != GetType()) - { - return false; - } - return Equals((Account) obj); + return obj.GetType() != GetType() ? false : Equals((Account)obj); } /// @@ -93,10 +89,10 @@ public override int GetHashCode() } /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// public override string ToString() { @@ -108,11 +104,7 @@ public override string ToString() /// protected bool Equals(Account? other) { - if (other is null) - { - return false; - } - return string.Equals(Name, other.Name); + return other is not null && string.Equals(Name, other.Name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/AccountType.cs b/BudgetAnalyser.Engine/BankAccount/AccountType.cs index eb506f7e..bc0c440b 100644 --- a/BudgetAnalyser.Engine/BankAccount/AccountType.cs +++ b/BudgetAnalyser.Engine/BankAccount/AccountType.cs @@ -26,4 +26,4 @@ public enum AccountType /// Savings } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/AccountTypeRepositoryConstants.cs b/BudgetAnalyser.Engine/BankAccount/AccountTypeRepositoryConstants.cs index e86b5fd3..18a91f5c 100644 --- a/BudgetAnalyser.Engine/BankAccount/AccountTypeRepositoryConstants.cs +++ b/BudgetAnalyser.Engine/BankAccount/AccountTypeRepositoryConstants.cs @@ -30,4 +30,4 @@ public static class AccountTypeRepositoryConstants /// public const string Visa = "VISA"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/AmexAccount.cs b/BudgetAnalyser.Engine/BankAccount/AmexAccount.cs index 4ab37ef1..d56afc38 100644 --- a/BudgetAnalyser.Engine/BankAccount/AmexAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/AmexAccount.cs @@ -35,4 +35,4 @@ public virtual Account Clone(string name) return new AmexAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/ChequeAccount.cs b/BudgetAnalyser.Engine/BankAccount/ChequeAccount.cs index 083d023b..cb53842a 100644 --- a/BudgetAnalyser.Engine/BankAccount/ChequeAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/ChequeAccount.cs @@ -44,4 +44,4 @@ public virtual Account Clone(string name) return new ChequeAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/IAccountTypeRepository.cs b/BudgetAnalyser.Engine/BankAccount/IAccountTypeRepository.cs index 6792e14e..c265efdd 100644 --- a/BudgetAnalyser.Engine/BankAccount/IAccountTypeRepository.cs +++ b/BudgetAnalyser.Engine/BankAccount/IAccountTypeRepository.cs @@ -41,4 +41,4 @@ public interface IAccountTypeRepository /// IEnumerable ListCurrentlyUsedAccountTypes(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/InMemoryAccountTypeRepository.cs b/BudgetAnalyser.Engine/BankAccount/InMemoryAccountTypeRepository.cs index 856f9152..19fd6dde 100644 --- a/BudgetAnalyser.Engine/BankAccount/InMemoryAccountTypeRepository.cs +++ b/BudgetAnalyser.Engine/BankAccount/InMemoryAccountTypeRepository.cs @@ -55,12 +55,9 @@ public Account Add([NotNull] string key, [NotNull] Account instance) throw new ArgumentNullException(nameof(instance)); } - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key)); - } - - return this.repository.GetOrAdd(key.ToUpperInvariant(), instance); + return string.IsNullOrWhiteSpace(key) + ? throw new ArgumentNullException(nameof(key)) + : this.repository.GetOrAdd(key.ToUpperInvariant(), instance); } /// @@ -70,7 +67,7 @@ public Account Add([NotNull] string key, [NotNull] Account instance) /// The found account or null. public Account Find(Predicate criteria) { - KeyValuePair[] copy = this.repository.ToArray(); + var copy = this.repository.ToArray(); return copy.FirstOrDefault(x => criteria(x.Value)).Value; } @@ -86,13 +83,7 @@ public Account GetByKey(string key) return null; } - Account account; - if (this.repository.TryGetValue(key.ToUpperInvariant(), out account)) - { - return account; - } - - return null; + return this.repository.TryGetValue(key.ToUpperInvariant(), out var account) ? account : null; } /// @@ -104,4 +95,4 @@ public IEnumerable ListCurrentlyUsedAccountTypes() return this.repository.Values.ToList(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/MastercardAccount.cs b/BudgetAnalyser.Engine/BankAccount/MastercardAccount.cs index f107debf..3519c6c5 100644 --- a/BudgetAnalyser.Engine/BankAccount/MastercardAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/MastercardAccount.cs @@ -35,4 +35,4 @@ public virtual Account Clone(string name) return new MastercardAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/MiscellaneousAccount.cs b/BudgetAnalyser.Engine/BankAccount/MiscellaneousAccount.cs index 7bcd314a..ec3c2b84 100644 --- a/BudgetAnalyser.Engine/BankAccount/MiscellaneousAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/MiscellaneousAccount.cs @@ -35,4 +35,4 @@ public virtual Account Clone(string name) return new MiscellaneousAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/SavingsAccount.cs b/BudgetAnalyser.Engine/BankAccount/SavingsAccount.cs index 808df080..047169ff 100644 --- a/BudgetAnalyser.Engine/BankAccount/SavingsAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/SavingsAccount.cs @@ -37,4 +37,4 @@ public virtual Account Clone(string name) return new SavingsAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BankAccount/VisaAccount.cs b/BudgetAnalyser.Engine/BankAccount/VisaAccount.cs index 219dbee8..91cb5202 100644 --- a/BudgetAnalyser.Engine/BankAccount/VisaAccount.cs +++ b/BudgetAnalyser.Engine/BankAccount/VisaAccount.cs @@ -34,4 +34,4 @@ public virtual Account Clone(string name) return new VisaAccount(name); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BillToPayExpenseBucket.cs b/BudgetAnalyser.Engine/Budget/BillToPayExpenseBucket.cs index f569ba17..f8d0b6ed 100644 --- a/BudgetAnalyser.Engine/Budget/BillToPayExpenseBucket.cs +++ b/BudgetAnalyser.Engine/Budget/BillToPayExpenseBucket.cs @@ -24,4 +24,4 @@ protected BillToPayExpenseBucket(string code, string name) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BucketComparer.cs b/BudgetAnalyser.Engine/Budget/BucketComparer.cs index 9e8c5ffd..eaf88cff 100644 --- a/BudgetAnalyser.Engine/Budget/BucketComparer.cs +++ b/BudgetAnalyser.Engine/Budget/BucketComparer.cs @@ -18,12 +18,7 @@ public bool Equals(BudgetBucket x, BudgetBucket y) { return false; } - if (x is SurplusBucket && y is SurplusBucket) - { - return true; - } - - return ReferenceEquals(x, y); + return x is SurplusBucket && y is SurplusBucket ? true : ReferenceEquals(x, y); } /// @@ -43,4 +38,4 @@ public int GetHashCode(BudgetBucket obj) return obj.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetBucket.cs b/BudgetAnalyser.Engine/Budget/BudgetBucket.cs index 5bf5a5b6..8e35f655 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetBucket.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetBucket.cs @@ -66,7 +66,7 @@ protected BudgetBucket(string code, string name) : this() /// public bool Active { - get { return this.doNotUseActive; } + get => this.doNotUseActive; set { this.doNotUseActive = value; @@ -79,7 +79,7 @@ public bool Active /// public string Code { - get { return this.doNotUseCode; } + get => this.doNotUseCode; set { @@ -98,7 +98,7 @@ public string Code /// public string Description { - get { return this.doNotUseDescription; } + get => this.doNotUseDescription; set { this.doNotUseDescription = value; @@ -121,13 +121,7 @@ public string Description /// public int CompareTo(object obj) { - var otherBucket = obj as BudgetBucket; - if (otherBucket is null) - { - return -1; - } - - return string.Compare(Code, otherBucket.Code, StringComparison.Ordinal); + return obj is not BudgetBucket otherBucket ? -1 : string.Compare(Code, otherBucket.Code, StringComparison.Ordinal); } /// @@ -175,22 +169,16 @@ public bool Validate([NotNull] StringBuilder validationMessages) } /// - /// Determines whether the specified , is equal to this instance. + /// Determines whether the specified , is equal to this instance. /// Comparisons are performed using the Property. /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object obj) { - var otherBucket = obj as BudgetBucket; - if (otherBucket is null) - { - return false; - } - - return Code == otherBucket.Code; + return obj is not BudgetBucket otherBucket ? false : Code == otherBucket.Code; } /// @@ -220,12 +208,7 @@ public override int GetHashCode() return false; } - if (ReferenceEquals(obj1, obj2)) - { - return true; - } - - return obj1.Equals(obj2); + return ReferenceEquals(obj1, obj2) ? true : obj1.Equals(obj2); } /// @@ -240,12 +223,7 @@ public override int GetHashCode() throw new ArgumentNullException(nameof(obj1)); } - if (obj2 is null) - { - throw new ArgumentNullException(nameof(obj2)); - } - - return obj1.CompareTo(obj2) > 0; + return obj2 is null ? throw new ArgumentNullException(nameof(obj2)) : obj1.CompareTo(obj2) > 0; } /// @@ -268,19 +246,14 @@ public override int GetHashCode() throw new ArgumentNullException(nameof(obj1)); } - if (obj2 is null) - { - throw new ArgumentNullException(nameof(obj2)); - } - - return obj1.CompareTo(obj2) < 0; + return obj2 is null ? throw new ArgumentNullException(nameof(obj2)) : obj1.CompareTo(obj2) < 0; } /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// public override string ToString() { @@ -298,4 +271,4 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetBucketPaternity.cs b/BudgetAnalyser.Engine/Budget/BudgetBucketPaternity.cs index a8de8e55..f45edccb 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetBucketPaternity.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetBucketPaternity.cs @@ -28,4 +28,4 @@ public bool OfSameBucketFamily(BudgetBucket bucket1, BudgetBucket bucket2) return bucket1 == bucket2; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetCollection.cs b/BudgetAnalyser.Engine/Budget/BudgetCollection.cs index e9ba96f3..76f3d14c 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetCollection.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetCollection.cs @@ -50,14 +50,8 @@ public BudgetCollection(params BudgetModel[] initialBudgets) : this(initialBudge /// /// Gets the current active budget. /// - public BudgetModel CurrentActiveBudget - { - get - { - return this.OrderByDescending(b => b.EffectiveFrom) + public BudgetModel CurrentActiveBudget => this.OrderByDescending(b => b.EffectiveFrom) .FirstOrDefault(b => b.EffectiveFrom <= DateTime.Now); - } - } internal BudgetModel this[int index] => this.budgetStorage.ElementAt(index).Value; @@ -136,13 +130,8 @@ public BudgetModel ForDate(DateTime date) public IEnumerable ForDates(DateTime beginInclusive, DateTime endInclusive) { var budgets = new List(); - var firstEffectiveBudget = ForDate(beginInclusive); - if (firstEffectiveBudget is null) - { - throw new BudgetException( + var firstEffectiveBudget = ForDate(beginInclusive) ?? throw new BudgetException( "The period covered by the dates given overlaps a period where no budgets are available."); - } - budgets.Add(firstEffectiveBudget); budgets.AddRange(this.Where(b => b.EffectiveFrom >= beginInclusive && b.EffectiveFrom < endInclusive)); return budgets; @@ -158,12 +147,7 @@ public bool IsArchivedBudget(BudgetModel budget) return false; } - if (IsCurrentBudget(budget)) - { - return false; - } - - return this.Any(b => b.EffectiveFrom <= budget.EffectiveFrom); + return IsCurrentBudget(budget) ? false : this.Any(b => b.EffectiveFrom <= budget.EffectiveFrom); } /// @@ -182,12 +166,7 @@ public bool IsCurrentBudget(BudgetModel budget) Justification = "Better for consistency with other methods here")] public bool IsFutureBudget([NotNull] BudgetModel budget) { - if (budget is null) - { - throw new ArgumentNullException(nameof(budget)); - } - - return budget.EffectiveFrom > DateTime.Now; + return budget is null ? throw new ArgumentNullException(nameof(budget)) : budget.EffectiveFrom > DateTime.Now; } internal virtual int IndexOf(BudgetModel budget) @@ -195,4 +174,4 @@ internal virtual int IndexOf(BudgetModel budget) return this.budgetStorage.IndexOfValue(budget); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetCurrencyContext.cs b/BudgetAnalyser.Engine/Budget/BudgetCurrencyContext.cs index 2480fbfe..ada73f47 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetCurrencyContext.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetCurrencyContext.cs @@ -87,4 +87,4 @@ public DateTime? EffectiveUntil /// public virtual BudgetModel Model { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetCycle.cs b/BudgetAnalyser.Engine/Budget/BudgetCycle.cs index 017dd2cd..7f21543c 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetCycle.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetCycle.cs @@ -1,4 +1,4 @@ -namespace BudgetAnalyser.Engine.Budget; +namespace BudgetAnalyser.Engine.Budget; /// /// The period for which a budget covers. @@ -7,4 +7,4 @@ public enum BudgetCycle { Monthly = 0, Fortnightly = 1 -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetException.cs b/BudgetAnalyser.Engine/Budget/BudgetException.cs index 2b4e147a..950f9516 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetException.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetException.cs @@ -35,4 +35,4 @@ public BudgetException(string message, Exception innerException) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetItem.cs b/BudgetAnalyser.Engine/Budget/BudgetItem.cs index 3390edb6..518a2de0 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetItem.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetItem.cs @@ -25,7 +25,7 @@ public abstract class BudgetItem : INotifyPropertyChanged /// public decimal Amount { - get { return this.doNotUseAmount; } + get => this.doNotUseAmount; set { @@ -44,7 +44,7 @@ public decimal Amount /// public BudgetBucket Bucket { - get { return this.doNotUseBucket; } + get => this.doNotUseBucket; set { if (this.doNotUseBucket is not null) @@ -73,16 +73,16 @@ public BudgetBucket Bucket Bucket.Description); /// - /// Determines whether the specified , is equal to this instance. + /// Determines whether the specified , is equal to this instance. /// Delegates to /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -132,12 +132,7 @@ public override int GetHashCode() /// protected bool Equals([NotNull] BudgetItem other) { - if (other is null) - { - throw new ArgumentNullException(nameof(other)); - } - - return Equals(Bucket, other.Bucket) && GetType() == other.GetType(); + return other is null ? throw new ArgumentNullException(nameof(other)) : Equals(Bucket, other.Bucket) && GetType() == other.GetType(); } /// @@ -163,14 +158,7 @@ private static string EnsureNoRepeatedLastWord(string sentence1, string sentence string lastWord; var wordIndex = sentence1.LastIndexOf(' '); - if (wordIndex <= 0) - { - lastWord = sentence1; - } - else - { - lastWord = sentence1.Substring(wordIndex + 1); - } + lastWord = wordIndex <= 0 ? sentence1 : sentence1.Substring(wordIndex + 1); string firstWord; wordIndex = sentence2.IndexOf(' '); @@ -184,12 +172,9 @@ private static string EnsureNoRepeatedLastWord(string sentence1, string sentence firstWord = sentence2.Substring(0, wordIndex); } - if (lastWord == firstWord) - { - return string.Format(CultureInfo.CurrentCulture, "{0}{1}", sentence1, sentence2.Substring(wordIndex)); - } - - return string.Format(CultureInfo.CurrentCulture, "{0} {1}", sentence1, sentence2); + return lastWord == firstWord + ? string.Format(CultureInfo.CurrentCulture, "{0}{1}", sentence1, sentence2.Substring(wordIndex)) + : string.Format(CultureInfo.CurrentCulture, "{0} {1}", sentence1, sentence2); } private void OnBucketPropertyChanged(object sender, PropertyChangedEventArgs e) @@ -202,4 +187,4 @@ private void OnBucketPropertyChanged(object sender, PropertyChangedEventArgs e) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/BudgetModel.cs b/BudgetAnalyser.Engine/Budget/BudgetModel.cs index 395fcdf4..8c8bde82 100644 --- a/BudgetAnalyser.Engine/Budget/BudgetModel.cs +++ b/BudgetAnalyser.Engine/Budget/BudgetModel.cs @@ -192,7 +192,7 @@ internal virtual bool Validate(StringBuilder validationMessages) retval = false; } - IEnumerable duplicates = Expenses + var duplicates = Expenses .GroupBy(i => i.Bucket.Code) .Where(g => g.Count() > 1) .Select(g => g.Key); @@ -206,4 +206,4 @@ internal virtual bool Validate(StringBuilder validationMessages) return retval; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BucketDtoType.cs b/BudgetAnalyser.Engine/Budget/Data/BucketDtoType.cs index 161f4f97..1de132e0 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BucketDtoType.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BucketDtoType.cs @@ -47,4 +47,4 @@ public enum BucketDtoType /// A spent periodically (either fortnightly or monthly) expense bucket. /// SpentPeriodicallyExpense -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketDto.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketDto.cs index a18fd6e4..80dac5db 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketDto.cs @@ -34,4 +34,4 @@ public class BudgetBucketDto Justification = "Permissable in this case as it is linked to the type.")] public virtual BucketDtoType Type { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketFactory.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketFactory.cs index 9b644016..3616e8cc 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketFactory.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketFactory.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Budget.Data; @@ -46,18 +46,13 @@ public BudgetBucketDto BuildDto(BudgetBucket bucket) { BudgetBucketDto dto; var fixedProjectBucket = bucket as FixedBudgetProjectBucket; - if (fixedProjectBucket is not null) - { - dto = new FixedBudgetBucketDto + dto = fixedProjectBucket is not null + ? new FixedBudgetBucketDto { Created = fixedProjectBucket.Created, FixedBudgetAmount = fixedProjectBucket.FixedBudgetAmount - }; - } - else - { - dto = new BudgetBucketDto(); - } + } + : new BudgetBucketDto(); dto.Type = SerialiseType(bucket); return dto; @@ -103,4 +98,4 @@ public BucketDtoType SerialiseType([NotNull] BudgetBucket bucket) throw new NotSupportedException("Unsupported bucket type detected: " + bucket.GetType().FullName); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.cs index ed54042c..5771d2c1 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.cs @@ -1,16 +1,20 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Budget.Data { [AutoRegisterWithIoC] - internal partial class Mapper_BudgetBucketDto_BudgetBucket + internal partial class MapperBudgetBucketDtoBudgetBucket { private readonly IBudgetBucketFactory bucketFactory; - public Mapper_BudgetBucketDto_BudgetBucket([NotNull] IBudgetBucketFactory bucketFactory) + public MapperBudgetBucketDtoBudgetBucket([NotNull] IBudgetBucketFactory bucketFactory) { - if (bucketFactory is null) throw new ArgumentNullException(nameof(bucketFactory)); + if (bucketFactory is null) + { + throw new ArgumentNullException(nameof(bucketFactory)); + } + this.bucketFactory = bucketFactory; } @@ -26,4 +30,4 @@ partial void ModelFactory(BudgetBucketDto dto, ref BudgetBucket model) model = this.bucketFactory.BuildModel(dto); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.generated.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.generated.cs index a80cca21..19aa7cbd 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.generated.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetBucketToDtoMapper.generated.cs @@ -10,7 +10,7 @@ namespace BudgetAnalyser.Engine.Budget.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 6:22:12 AM UTC")] - internal partial class Mapper_BudgetBucketDto_BudgetBucket : IDtoMapper + internal partial class MapperBudgetBucketDtoBudgetBucket : IDtoMapper { public virtual BudgetBucket ToModel(BudgetBucketDto dto) diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionDto.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionDto.cs index 1fe7fbd2..9c3560cc 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionDto.cs @@ -34,4 +34,4 @@ public class BudgetCollectionDto /// public string StorageKey { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.cs index 9345afcc..fb400014 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.cs @@ -6,20 +6,32 @@ namespace BudgetAnalyser.Engine.Budget.Data { [AutoRegisterWithIoC] - internal partial class Mapper_BudgetCollectionDto_BudgetCollection + internal partial class MapperBudgetCollectionDtoBudgetCollection { private readonly IDtoMapper bucketMapper; private readonly IBudgetBucketRepository bucketRepo; private readonly IDtoMapper budgetMapper; - public Mapper_BudgetCollectionDto_BudgetCollection( + public MapperBudgetCollectionDtoBudgetCollection( [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] IDtoMapper bucketMapper, [NotNull] IDtoMapper budgetMapper) { - if (bucketRepo is null) throw new ArgumentNullException(nameof(bucketRepo)); - if (bucketMapper is null) throw new ArgumentNullException(nameof(bucketMapper)); - if (budgetMapper is null) throw new ArgumentNullException(nameof(budgetMapper)); + if (bucketRepo is null) + { + throw new ArgumentNullException(nameof(bucketRepo)); + } + + if (bucketMapper is null) + { + throw new ArgumentNullException(nameof(bucketMapper)); + } + + if (budgetMapper is null) + { + throw new ArgumentNullException(nameof(budgetMapper)); + } + this.bucketRepo = bucketRepo; this.bucketMapper = bucketMapper; this.budgetMapper = budgetMapper; @@ -38,4 +50,4 @@ partial void ToModelPostprocessing(BudgetCollectionDto dto, ref BudgetCollection dto.Buckets.ForEach(x => this.bucketRepo.GetOrCreateNew(x.Code, () => this.bucketMapper.ToModel(x))); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.generated.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.generated.cs index 9c472913..d035cbf3 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.generated.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetCollectionToDtoMapper.generated.cs @@ -11,7 +11,7 @@ namespace BudgetAnalyser.Engine.Budget.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 12:33:20 AM UTC")] - internal partial class Mapper_BudgetCollectionDto_BudgetCollection : IDtoMapper + internal partial class MapperBudgetCollectionDtoBudgetCollection : IDtoMapper { public virtual BudgetCollection ToModel(BudgetCollectionDto dto) diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetModelDto.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetModelDto.cs index b3a2e07c..365f40b7 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetModelDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetModelDto.cs @@ -13,7 +13,7 @@ public class BudgetModelDto /// Gets the pay cycle for this budget. Can only be set during budget creation. /// public BudgetCycle BudgetCycle { get; set; } - + /// /// Gets or sets the effective from date. /// @@ -49,4 +49,4 @@ public class BudgetModelDto /// Gets or sets the name of the Budget Model. /// public string Name { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.cs index 26ec95da..48bc8b3f 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.cs @@ -6,35 +6,35 @@ namespace BudgetAnalyser.Engine.Budget.Data { [AutoRegisterWithIoC] - internal partial class Mapper_BudgetModelDto_BudgetModel + internal partial class MapperBudgetModelDtoBudgetModel { private readonly IBudgetBucketRepository bucketRepo; - public Mapper_BudgetModelDto_BudgetModel(IBudgetBucketRepository bucketRepo) + public MapperBudgetModelDtoBudgetModel(IBudgetBucketRepository bucketRepo) { this.bucketRepo = bucketRepo; } partial void ToDtoPostprocessing(ref BudgetModelDto dto, BudgetModel model) { - var mapper3 = new Mapper_ExpenseDto_Expense(this.bucketRepo); - List expenses8 = model.Expenses.Select(mapper3.ToDto).ToList(); + var mapper3 = new MapperExpenseDto2Expense(this.bucketRepo); + var expenses8 = model.Expenses.Select(mapper3.ToDto).ToList(); dto.Expenses = expenses8; - var mapper4 = new Mapper_IncomeDto_Income(this.bucketRepo); - List incomes9 = model.Incomes.Select(mapper4.ToDto).ToList(); + var mapper4 = new MapperIncomeDto2Income(this.bucketRepo); + var incomes9 = model.Incomes.Select(mapper4.ToDto).ToList(); dto.Incomes = incomes9; } partial void ToModelPostprocessing(BudgetModelDto dto, ref BudgetModel model) { var modelType = model.GetType(); - var mapper1 = new Mapper_ExpenseDto_Expense(this.bucketRepo); - List expenses2 = dto.Expenses.Select(mapper1.ToModel).ToList(); + var mapper1 = new MapperExpenseDto2Expense(this.bucketRepo); + var expenses2 = dto.Expenses.Select(mapper1.ToModel).ToList(); model.LastModified = dto.LastModified ?? DateTime.Now; modelType.GetProperty("Expenses").SetValue(model, expenses2); - var mapper2 = new Mapper_IncomeDto_Income(this.bucketRepo); - List incomes3 = dto.Incomes.Select(mapper2.ToModel).ToList(); + var mapper2 = new MapperIncomeDto2Income(this.bucketRepo); + var incomes3 = dto.Incomes.Select(mapper2.ToModel).ToList(); modelType.GetProperty("Incomes").SetValue(model, incomes3); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.generated.cs b/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.generated.cs index bd1489e5..e55d5e35 100644 --- a/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.generated.cs +++ b/BudgetAnalyser.Engine/Budget/Data/BudgetModelToDtoMapper.generated.cs @@ -11,7 +11,7 @@ namespace BudgetAnalyser.Engine.Budget.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 12:48:10 AM UTC")] - internal partial class Mapper_BudgetModelDto_BudgetModel : IDtoMapper + internal partial class MapperBudgetModelDtoBudgetModel : IDtoMapper { public virtual BudgetModel ToModel(BudgetModelDto dto) @@ -60,7 +60,7 @@ public virtual BudgetModelDto ToDto(BudgetModel model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 12:48:10 AM UTC")] - internal partial class Mapper_ExpenseDto_Expense : IDtoMapper + internal partial class MapperExpenseDto2Expense : IDtoMapper { public virtual Expense ToModel(ExpenseDto dto) @@ -97,7 +97,7 @@ public virtual ExpenseDto ToDto(Expense model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 12:48:10 AM UTC")] - internal partial class Mapper_IncomeDto_Income : IDtoMapper + internal partial class MapperIncomeDto2Income : IDtoMapper { public virtual Income ToModel(IncomeDto dto) diff --git a/BudgetAnalyser.Engine/Budget/Data/ExpenseDto.cs b/BudgetAnalyser.Engine/Budget/Data/ExpenseDto.cs index 45b39b9f..2b759198 100644 --- a/BudgetAnalyser.Engine/Budget/Data/ExpenseDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/ExpenseDto.cs @@ -15,4 +15,4 @@ public class ExpenseDto /// public string BudgetBucketCode { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/ExpenseToDtoMapper.cs b/BudgetAnalyser.Engine/Budget/Data/ExpenseToDtoMapper.cs index 813b61d6..fa2e1251 100644 --- a/BudgetAnalyser.Engine/Budget/Data/ExpenseToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Budget/Data/ExpenseToDtoMapper.cs @@ -4,15 +4,9 @@ namespace BudgetAnalyser.Engine.Budget.Data { [AutoRegisterWithIoC] - internal partial class Mapper_ExpenseDto_Expense + internal partial class MapperExpenseDto2Expense(IBudgetBucketRepository bucketRepo) { - private readonly IBudgetBucketRepository bucketRepo; - - public Mapper_ExpenseDto_Expense([NotNull] IBudgetBucketRepository bucketRepo) - { - if (bucketRepo is null) throw new ArgumentNullException(nameof(bucketRepo)); - this.bucketRepo = bucketRepo; - } + private readonly IBudgetBucketRepository bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); partial void ToDtoPostprocessing(ref ExpenseDto dto, Expense model) { @@ -24,4 +18,4 @@ partial void ToModelPostprocessing(ExpenseDto dto, ref Expense model) model.Bucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/FixedBudgetBucketDto.cs b/BudgetAnalyser.Engine/Budget/Data/FixedBudgetBucketDto.cs index c3644c5d..317fbb63 100644 --- a/BudgetAnalyser.Engine/Budget/Data/FixedBudgetBucketDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/FixedBudgetBucketDto.cs @@ -23,8 +23,8 @@ public class FixedBudgetBucketDto : BudgetBucketDto /// public override BucketDtoType Type { - get { return BucketDtoType.FixedBudgetProject; } + get => BucketDtoType.FixedBudgetProject; set { } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/IBudgetBucketFactory.cs b/BudgetAnalyser.Engine/Budget/Data/IBudgetBucketFactory.cs index e58597e8..9f69b930 100644 --- a/BudgetAnalyser.Engine/Budget/Data/IBudgetBucketFactory.cs +++ b/BudgetAnalyser.Engine/Budget/Data/IBudgetBucketFactory.cs @@ -1,4 +1,4 @@ -namespace BudgetAnalyser.Engine.Budget.Data +namespace BudgetAnalyser.Engine.Budget.Data { /// /// A factory to build to and from persistence types for . @@ -20,4 +20,4 @@ public interface IBudgetBucketFactory /// BucketDtoType SerialiseType(BudgetBucket bucket); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/IncomeDto.cs b/BudgetAnalyser.Engine/Budget/Data/IncomeDto.cs index d5f9df4a..eca3ec4d 100644 --- a/BudgetAnalyser.Engine/Budget/Data/IncomeDto.cs +++ b/BudgetAnalyser.Engine/Budget/Data/IncomeDto.cs @@ -15,4 +15,4 @@ public class IncomeDto /// public string BudgetBucketCode { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Data/IncomeToDtoMapper.cs b/BudgetAnalyser.Engine/Budget/Data/IncomeToDtoMapper.cs index 6327ef34..321e6cdf 100644 --- a/BudgetAnalyser.Engine/Budget/Data/IncomeToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Budget/Data/IncomeToDtoMapper.cs @@ -4,15 +4,9 @@ namespace BudgetAnalyser.Engine.Budget.Data { [AutoRegisterWithIoC] - internal partial class Mapper_IncomeDto_Income + internal partial class MapperIncomeDto2Income(IBudgetBucketRepository bucketRepo) { - private readonly IBudgetBucketRepository bucketRepo; - - public Mapper_IncomeDto_Income([NotNull] IBudgetBucketRepository bucketRepo) - { - if (bucketRepo is null) throw new ArgumentNullException(nameof(bucketRepo)); - this.bucketRepo = bucketRepo; - } + private readonly IBudgetBucketRepository bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); partial void ToDtoPostprocessing(ref IncomeDto dto, Income model) { @@ -24,4 +18,4 @@ partial void ToModelPostprocessing(IncomeDto dto, ref Income model) model.Bucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/DateTimeDescendingOrder.cs b/BudgetAnalyser.Engine/Budget/DateTimeDescendingOrder.cs index 416a24db..874c8f95 100644 --- a/BudgetAnalyser.Engine/Budget/DateTimeDescendingOrder.cs +++ b/BudgetAnalyser.Engine/Budget/DateTimeDescendingOrder.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace BudgetAnalyser.Engine.Budget @@ -11,11 +11,7 @@ public int Compare(DateTime x, DateTime y) { return 1; } - if (x > y) - { - return -1; - } - return 0; + return x > y ? -1 : 0; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Expense.cs b/BudgetAnalyser.Engine/Budget/Expense.cs index 83cba344..9a3b7371 100644 --- a/BudgetAnalyser.Engine/Budget/Expense.cs +++ b/BudgetAnalyser.Engine/Budget/Expense.cs @@ -64,4 +64,4 @@ public bool Validate([NotNull] StringBuilder validationMessages) return retval; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/ExpenseBucket.cs b/BudgetAnalyser.Engine/Budget/ExpenseBucket.cs index 39e8b0b2..b4e932d3 100644 --- a/BudgetAnalyser.Engine/Budget/ExpenseBucket.cs +++ b/BudgetAnalyser.Engine/Budget/ExpenseBucket.cs @@ -22,4 +22,4 @@ protected ExpenseBucket(string code, string name) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/FixedBudgetProjectBucket.cs b/BudgetAnalyser.Engine/Budget/FixedBudgetProjectBucket.cs index 63697db4..e19f570e 100644 --- a/BudgetAnalyser.Engine/Budget/FixedBudgetProjectBucket.cs +++ b/BudgetAnalyser.Engine/Budget/FixedBudgetProjectBucket.cs @@ -70,12 +70,9 @@ internal FixedBudgetProjectBucket(string code, string description, decimal fixed /// public static string CreateCode([NotNull] string subCode) { - if (subCode is null) - { - throw new ArgumentNullException(nameof(subCode)); - } - - return string.Format(CultureInfo.InvariantCulture, ProjectCodeTemplateWithPrefix, subCode.ToUpperInvariant()); + return subCode is null + ? throw new ArgumentNullException(nameof(subCode)) + : string.Format(CultureInfo.InvariantCulture, ProjectCodeTemplateWithPrefix, subCode.ToUpperInvariant()); } /// @@ -89,4 +86,4 @@ public override string ToString() return string.Format(CultureInfo.CurrentCulture, "[{0}] {1} {2}", Code, Description, Created.ToString("d")); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/IBudgetBucketRepository.cs b/BudgetAnalyser.Engine/Budget/IBudgetBucketRepository.cs index b392078c..a89bcb41 100644 --- a/BudgetAnalyser.Engine/Budget/IBudgetBucketRepository.cs +++ b/BudgetAnalyser.Engine/Budget/IBudgetBucketRepository.cs @@ -65,4 +65,4 @@ FixedBudgetProjectBucket CreateNewFixedBudgetProject([NotNull] string bucketCode /// The project bucket to remove. void RemoveFixedBudgetProject([NotNull] FixedBudgetProjectBucket projectBucket); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/IBudgetCurrencyContext.cs b/BudgetAnalyser.Engine/Budget/IBudgetCurrencyContext.cs index f1d6e4c2..fa7c5f6f 100644 --- a/BudgetAnalyser.Engine/Budget/IBudgetCurrencyContext.cs +++ b/BudgetAnalyser.Engine/Budget/IBudgetCurrencyContext.cs @@ -41,4 +41,4 @@ public interface IBudgetCurrencyContext /// BudgetModel Model { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/IBudgetRepository.cs b/BudgetAnalyser.Engine/Budget/IBudgetRepository.cs index 79afbca8..71c5d593 100644 --- a/BudgetAnalyser.Engine/Budget/IBudgetRepository.cs +++ b/BudgetAnalyser.Engine/Budget/IBudgetRepository.cs @@ -51,4 +51,4 @@ public interface IBudgetRepository /// A boolean to indicate if the data file should be encrypted or not. Task SaveAsync(string storageKey, bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/InMemoryBudgetBucketRepository.cs b/BudgetAnalyser.Engine/Budget/InMemoryBudgetBucketRepository.cs index 380f28b5..c7df2e1f 100644 --- a/BudgetAnalyser.Engine/Budget/InMemoryBudgetBucketRepository.cs +++ b/BudgetAnalyser.Engine/Budget/InMemoryBudgetBucketRepository.cs @@ -115,12 +115,7 @@ public virtual BudgetBucket GetByCode(string code) } var upperCode = code.ToUpperInvariant(); - if (IsValidCode(upperCode)) - { - return this.lookupTable[upperCode]; - } - - return null; + return IsValidCode(upperCode) ? this.lookupTable[upperCode] : null; } /// @@ -189,12 +184,7 @@ public virtual void Initialise(IEnumerable buckets) /// public virtual bool IsValidCode(string code) { - if (code is null) - { - throw new ArgumentNullException(nameof(code)); - } - - return ContainsKeyInternal(code); + return code is null ? throw new ArgumentNullException(nameof(code)) : ContainsKeyInternal(code); } /// @@ -268,4 +258,4 @@ protected void InitialiseMandatorySpecialBuckets() AddBucket(new PayCreditCardBucket(PayCreditCardBucket.PayCreditCardCode, "A special bucket to allocate internal transfers.")); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/Income.cs b/BudgetAnalyser.Engine/Budget/Income.cs index 9c5df260..f8f55ff9 100644 --- a/BudgetAnalyser.Engine/Budget/Income.cs +++ b/BudgetAnalyser.Engine/Budget/Income.cs @@ -55,4 +55,4 @@ public bool Validate([NotNull] StringBuilder validationMessages) return retval; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/IncomeBudgetBucket.cs b/BudgetAnalyser.Engine/Budget/IncomeBudgetBucket.cs index 95e61609..8512844b 100644 --- a/BudgetAnalyser.Engine/Budget/IncomeBudgetBucket.cs +++ b/BudgetAnalyser.Engine/Budget/IncomeBudgetBucket.cs @@ -21,4 +21,4 @@ public IncomeBudgetBucket(string code, string name) : base(code, name) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/PayCreditCardBucket.cs b/BudgetAnalyser.Engine/Budget/PayCreditCardBucket.cs index 1d1827ee..189e0d09 100644 --- a/BudgetAnalyser.Engine/Budget/PayCreditCardBucket.cs +++ b/BudgetAnalyser.Engine/Budget/PayCreditCardBucket.cs @@ -27,4 +27,4 @@ public PayCreditCardBucket(string code, string description) : base(code, descrip { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/SavedUpForExpenseBucket.cs b/BudgetAnalyser.Engine/Budget/SavedUpForExpenseBucket.cs index 8cc46d29..c4fedabc 100644 --- a/BudgetAnalyser.Engine/Budget/SavedUpForExpenseBucket.cs +++ b/BudgetAnalyser.Engine/Budget/SavedUpForExpenseBucket.cs @@ -28,4 +28,4 @@ public SavedUpForExpenseBucket(string code, string name) /// public override string TypeDescription => "Accumulated Expense"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/SpentPerPeriodExpenseBucket.cs b/BudgetAnalyser.Engine/Budget/SpentPerPeriodExpenseBucket.cs index aaba623c..418a5b97 100644 --- a/BudgetAnalyser.Engine/Budget/SpentPerPeriodExpenseBucket.cs +++ b/BudgetAnalyser.Engine/Budget/SpentPerPeriodExpenseBucket.cs @@ -28,4 +28,4 @@ public SpentPerPeriodExpenseBucket(string code, string name) /// public override string TypeDescription => "Spent Monthly/Fortnightly Expense"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/SurplusBucket.cs b/BudgetAnalyser.Engine/Budget/SurplusBucket.cs index 1f662e20..19b3f9f2 100644 --- a/BudgetAnalyser.Engine/Budget/SurplusBucket.cs +++ b/BudgetAnalyser.Engine/Budget/SurplusBucket.cs @@ -37,4 +37,4 @@ protected SurplusBucket(string bucketCode, string description) : base(bucketCode /// public override string TypeDescription => "Calculated Surplus"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Budget/XamlOnDiskBudgetRepository.cs b/BudgetAnalyser.Engine/Budget/XamlOnDiskBudgetRepository.cs index aa3b28c3..ce8505b6 100644 --- a/BudgetAnalyser.Engine/Budget/XamlOnDiskBudgetRepository.cs +++ b/BudgetAnalyser.Engine/Budget/XamlOnDiskBudgetRepository.cs @@ -1,8 +1,8 @@ -using System.Globalization; -using Portable.Xaml; +using System.Globalization; using BudgetAnalyser.Engine.Budget.Data; using BudgetAnalyser.Engine.Services; using JetBrains.Annotations; +using Portable.Xaml; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.Budget @@ -102,8 +102,7 @@ public async Task LoadAsync(string storageKey, bool isEncrypte throw new DataFormatException("Deserialisation the Budget file failed, an exception was thrown by the Xaml deserialiser, the file format is invalid.", ex); } - var correctDataFormat = serialised as BudgetCollectionDto; - if (correctDataFormat is null) + if (serialised is not BudgetCollectionDto correctDataFormat) { throw new DataFormatException( string.Format(CultureInfo.InvariantCulture, @@ -159,4 +158,4 @@ protected virtual string Serialise(BudgetCollectionDto budgetData) return XamlServices.Save(budgetData); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/BudgetAnalyserLog4NetLogger.cs b/BudgetAnalyser.Engine/BudgetAnalyserLog4NetLogger.cs index 0f5c4a62..34b22851 100644 --- a/BudgetAnalyser.Engine/BudgetAnalyserLog4NetLogger.cs +++ b/BudgetAnalyser.Engine/BudgetAnalyserLog4NetLogger.cs @@ -11,4 +11,4 @@ namespace BudgetAnalyser.Engine; public class BudgetAnalyserLog4NetLogger : DebugLogger { // TODO This class needs to be redesigned to use something other than Log4Net. -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DataFormatException.cs b/BudgetAnalyser.Engine/DataFormatException.cs index 2b6461d9..16cf12de 100644 --- a/BudgetAnalyser.Engine/DataFormatException.cs +++ b/BudgetAnalyser.Engine/DataFormatException.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.Engine { @@ -34,4 +34,4 @@ public DataFormatException(string message, Exception innerException) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DateTimeExtension.cs b/BudgetAnalyser.Engine/DateTimeExtension.cs index f937057f..3e4c235e 100644 --- a/BudgetAnalyser.Engine/DateTimeExtension.cs +++ b/BudgetAnalyser.Engine/DateTimeExtension.cs @@ -15,7 +15,7 @@ public static class DateTimeExtension /// An integer number of whole calendar months. public static int DurationInMonths(this DateTime minDate, DateTime maxDate) { - var durationInMonths = (int) Math.Round(maxDate.Subtract(minDate).TotalDays / 30, 0); + var durationInMonths = (int)Math.Round(maxDate.Subtract(minDate).TotalDays / 30, 0); if (durationInMonths <= 0) { durationInMonths = 1; @@ -53,4 +53,4 @@ public static DateTime LastDateInMonth(this DateTime instance) return instance.AddMonths(1).FirstDateInMonth().AddDays(-1); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DebugLogger.cs b/BudgetAnalyser.Engine/DebugLogger.cs index 6ab7cbc1..60e91311 100644 --- a/BudgetAnalyser.Engine/DebugLogger.cs +++ b/BudgetAnalyser.Engine/DebugLogger.cs @@ -25,7 +25,11 @@ public LogLevel LogLevelFilter get => this.logLevelFilter; set { - if (value == this.logLevelFilter) return; + if (value == this.logLevelFilter) + { + return; + } + LogAlways(l => l.Format("Logging Filter Level change from {0} to {1}.", this.logLevelFilter, value)); this.logLevelFilter = value; } @@ -37,8 +41,7 @@ public LogLevel LogLevelFilter /// public string Format(string formatTemplate, params object[] parameters) { - if (!this.isDebuggerAttached) return string.Empty; - return string.Format(formatTemplate, parameters); + return !this.isDebuggerAttached ? string.Empty : string.Format(formatTemplate, parameters); } /// @@ -46,7 +49,11 @@ public string Format(string formatTemplate, params object[] parameters) /// public void LogAlways(Func logEntryBuilder) { - if (!ShouldILog(LogLevel.Always)) return; + if (!ShouldILog(LogLevel.Always)) + { + return; + } + var msg = ConstructLogEntry(LogLevel.Always, logEntryBuilder); Debug.WriteLine(msg); } @@ -56,7 +63,11 @@ public void LogAlways(Func logEntryBuilder) /// public void LogError(Func logEntryBuilder) { - if (!ShouldILog(LogLevel.Error)) return; + if (!ShouldILog(LogLevel.Error)) + { + return; + } + Debug.WriteLine(ConstructLogEntry(LogLevel.Error, logEntryBuilder)); } @@ -65,7 +76,11 @@ public void LogError(Func logEntryBuilder) /// public void LogError(Exception ex, Func logEntryBuilder) { - if (!ShouldILog(LogLevel.Error)) return; + if (!ShouldILog(LogLevel.Error)) + { + return; + } + if (ex is null) { throw new ArgumentNullException(nameof(ex)); @@ -85,7 +100,11 @@ public void LogError(Exception ex, Func logEntryBuilder) /// public void LogInfo(Func logEntryBuilder) { - if (!ShouldILog(LogLevel.Info)) return; + if (!ShouldILog(LogLevel.Info)) + { + return; + } + if (logEntryBuilder is null) { throw new ArgumentNullException(nameof(logEntryBuilder)); @@ -99,7 +118,11 @@ public void LogInfo(Func logEntryBuilder) /// public void LogWarning(Func logEntryBuilder) { - if (!ShouldILog(LogLevel.Warn)) return; + if (!ShouldILog(LogLevel.Warn)) + { + return; + } + Debug.WriteLine(ConstructLogEntry(LogLevel.Warn, logEntryBuilder)); } @@ -111,8 +134,15 @@ private string ConstructLogEntry(LogLevel level, Func logEntryB private bool ShouldILog(LogLevel logEntryLevel) { // Only log if debugger is attached. Uses a field so unit testing can still test when debugger is not attached. - if (!this.isDebuggerAttached) return false; - if (LogLevelFilter == LogLevel.Always || logEntryLevel == LogLevel.Always) return true; + if (!this.isDebuggerAttached) + { + return false; + } + + if (LogLevelFilter == LogLevel.Always || logEntryLevel == LogLevel.Always) + { + return true; + } switch (LogLevelFilter) { @@ -126,4 +156,4 @@ private bool ShouldILog(LogLevel logEntryLevel) return false; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DebugPlusLog4NetLogger.cs b/BudgetAnalyser.Engine/DebugPlusLog4NetLogger.cs index b6f40e3b..c615f1b5 100644 --- a/BudgetAnalyser.Engine/DebugPlusLog4NetLogger.cs +++ b/BudgetAnalyser.Engine/DebugPlusLog4NetLogger.cs @@ -1,4 +1,4 @@ -// TODO Reconsider if this is necessary, I'm removing Log4Net from the project. +// TODO Reconsider if this is necessary, I'm removing Log4Net from the project. //using System; //using JetBrains.Annotations; @@ -45,4 +45,4 @@ // } //} -namespace BudgetAnalyser.Engine; \ No newline at end of file +namespace BudgetAnalyser.Engine; diff --git a/BudgetAnalyser.Engine/DefaultIoCRegistrations.cs b/BudgetAnalyser.Engine/DefaultIoCRegistrations.cs index 8a2f924e..68564218 100644 --- a/BudgetAnalyser.Engine/DefaultIoCRegistrations.cs +++ b/BudgetAnalyser.Engine/DefaultIoCRegistrations.cs @@ -19,14 +19,21 @@ public static class DefaultIoCRegistrations /// The found named instance, or null if no instance matches the name. public static T GetNamedInstance([NotNull] IEnumerable instances, string name) where T : class { - if (instances is null) throw new ArgumentNullException(nameof(instances)); + if (instances is null) + { + throw new ArgumentNullException(nameof(instances)); + } + foreach (var instance in instances) { - IEnumerable attributes = instance.GetType().GetTypeInfo().GetCustomAttributes(); + var attributes = instance.GetType().GetTypeInfo().GetCustomAttributes(); var attribute = attributes.FirstOrDefault(); if (attribute is not null) { - if (attribute.Named == name) return instance; + if (attribute.Named == name) + { + return instance; + } } } @@ -47,7 +54,7 @@ public static IEnumerable ProcessPropert throw new ArgumentNullException(nameof(assembly)); } - Type[] allTypes = assembly.GetTypes() + var allTypes = assembly.GetTypes() .Where(t => { var typeInfo = t.GetTypeInfo(); @@ -84,7 +91,7 @@ public static IEnumerable RegisterAutoMapping throw new ArgumentNullException(nameof(assembly)); } - Type[] allTypes = assembly.GetTypes() + var allTypes = assembly.GetTypes() .Where(t => { var typeInfo = t.GetTypeInfo(); @@ -93,14 +100,14 @@ public static IEnumerable RegisterAutoMapping .ToArray(); return from type in allTypes - let autoRegisterAttribute = type.GetTypeInfo().GetCustomAttribute() - select new DependencyRegistrationRequirement - { - DependencyRequired = type, - IsSingleInstance = autoRegisterAttribute.SingleInstance, - NamedInstanceName = autoRegisterAttribute.Named, - AdditionalRegistrationType = autoRegisterAttribute.RegisterAs - }; + let autoRegisterAttribute = type.GetTypeInfo().GetCustomAttribute() + select new DependencyRegistrationRequirement + { + DependencyRequired = type, + IsSingleInstance = autoRegisterAttribute.SingleInstance, + NamedInstanceName = autoRegisterAttribute.Named, + AdditionalRegistrationType = autoRegisterAttribute.RegisterAs + }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DependencyRegistrationRequirement.cs b/BudgetAnalyser.Engine/DependencyRegistrationRequirement.cs index 0e1e4c14..8325158a 100644 --- a/BudgetAnalyser.Engine/DependencyRegistrationRequirement.cs +++ b/BudgetAnalyser.Engine/DependencyRegistrationRequirement.cs @@ -37,4 +37,4 @@ public class DependencyRegistrationRequirement /// public string NamedInstanceName { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/DuplicateNameException.cs b/BudgetAnalyser.Engine/DuplicateNameException.cs index b33de918..e2cd4c60 100644 --- a/BudgetAnalyser.Engine/DuplicateNameException.cs +++ b/BudgetAnalyser.Engine/DuplicateNameException.cs @@ -31,4 +31,4 @@ public DuplicateNameException(string message, Exception innerException) : base(m { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/GlobalFilterCriteria.cs b/BudgetAnalyser.Engine/GlobalFilterCriteria.cs index 9cb365af..99f39fff 100644 --- a/BudgetAnalyser.Engine/GlobalFilterCriteria.cs +++ b/BudgetAnalyser.Engine/GlobalFilterCriteria.cs @@ -32,7 +32,7 @@ public GlobalFilterCriteria() /// public DateTime? BeginDate { - get { return this.doNotUseBeginDate; } + get => this.doNotUseBeginDate; set { this.doNotUseBeginDate = value; @@ -47,7 +47,7 @@ public DateTime? BeginDate /// public bool Cleared { - get { return this.doNotUseCleared; } + get => this.doNotUseCleared; private set { this.doNotUseCleared = value; @@ -60,7 +60,7 @@ private set /// public DateTime? EndDate { - get { return this.doNotUseEndDate; } + get => this.doNotUseEndDate; set { this.doNotUseEndDate = value; @@ -92,7 +92,10 @@ public long SignificantDataChangeHash() /// If the instance is in an invalid state it will return false, otherwise it returns true. public bool Validate(StringBuilder validationMessages) { - if (validationMessages is null) throw new ArgumentNullException(nameof(validationMessages)); + if (validationMessages is null) + { + throw new ArgumentNullException(nameof(validationMessages)); + } if (Cleared) { @@ -144,15 +147,8 @@ private void CheckConsistency() EndDate = null; } - if (BeginDate is null - && EndDate is null) - { - Cleared = true; - } - else - { - Cleared = false; - } + Cleared = BeginDate is null + && EndDate is null; if (BeginDate is not null && EndDate is not null && BeginDate > EndDate) { @@ -160,4 +156,4 @@ private void CheckConsistency() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/GlobalSuppressions.cs b/BudgetAnalyser.Engine/GlobalSuppressions.cs index f630197f..d5d3bce3 100644 Binary files a/BudgetAnalyser.Engine/GlobalSuppressions.cs and b/BudgetAnalyser.Engine/GlobalSuppressions.cs differ diff --git a/BudgetAnalyser.Engine/ICloneable.cs b/BudgetAnalyser.Engine/ICloneable.cs index 82f995cd..3c1fe13d 100644 --- a/BudgetAnalyser.Engine/ICloneable.cs +++ b/BudgetAnalyser.Engine/ICloneable.cs @@ -4,4 +4,4 @@ internal interface ICloneable { T Clone(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/IDataChangeDetection.cs b/BudgetAnalyser.Engine/IDataChangeDetection.cs index eb3545ec..e9704dbf 100644 --- a/BudgetAnalyser.Engine/IDataChangeDetection.cs +++ b/BudgetAnalyser.Engine/IDataChangeDetection.cs @@ -12,4 +12,4 @@ public interface IDataChangeDetection /// long SignificantDataChangeHash(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/IEnumerableExtension.cs b/BudgetAnalyser.Engine/IEnumerableExtension.cs index a247e85c..6bb1eeb7 100644 --- a/BudgetAnalyser.Engine/IEnumerableExtension.cs +++ b/BudgetAnalyser.Engine/IEnumerableExtension.cs @@ -14,8 +14,7 @@ public static class EnumerableExtension /// public static bool None(this IEnumerable instance) { - if (instance is null) return false; - return !instance.Any(); + return instance is null ? false : !instance.Any(); } /// @@ -23,12 +22,8 @@ public static bool None(this IEnumerable instance) /// public static double SafeAverage(this IEnumerable instance, Func selector) { - List copy = instance.ToList(); - if (copy.None()) - { - return 0; - } - return copy.Average(selector); + var copy = instance.ToList(); + return copy.None() ? 0 : copy.Average(selector); } /// @@ -36,12 +31,8 @@ public static double SafeAverage(this IEnumerable instance, Func public static decimal SafeAverage(this IEnumerable instance, Func selector) { - List copy = instance.ToList(); - if (copy.None()) - { - return 0; - } - return copy.Average(selector); + var copy = instance.ToList(); + return copy.None() ? 0 : copy.Average(selector); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/IEnvironmentFolders.cs b/BudgetAnalyser.Engine/IEnvironmentFolders.cs index ae440cf2..3f3cf968 100644 --- a/BudgetAnalyser.Engine/IEnvironmentFolders.cs +++ b/BudgetAnalyser.Engine/IEnvironmentFolders.cs @@ -18,4 +18,4 @@ public interface IEnvironmentFolders /// Task LogFolder(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ILogger.cs b/BudgetAnalyser.Engine/ILogger.cs index 6303dc62..fc1a65d6 100644 --- a/BudgetAnalyser.Engine/ILogger.cs +++ b/BudgetAnalyser.Engine/ILogger.cs @@ -41,4 +41,4 @@ public interface ILogger /// void LogWarning(Func logEntryBuilder); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/IModelValidate.cs b/BudgetAnalyser.Engine/IModelValidate.cs index 85a060f3..80b41a1a 100644 --- a/BudgetAnalyser.Engine/IModelValidate.cs +++ b/BudgetAnalyser.Engine/IModelValidate.cs @@ -15,4 +15,4 @@ public interface IModelValidate /// If the instance is in an invalid state it will return false, otherwise it returns true. bool Validate(StringBuilder validationMessages); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/IReaderWriterSelector.cs b/BudgetAnalyser.Engine/IReaderWriterSelector.cs index fae707b9..b2297ab8 100644 --- a/BudgetAnalyser.Engine/IReaderWriterSelector.cs +++ b/BudgetAnalyser.Engine/IReaderWriterSelector.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.Persistence; +using BudgetAnalyser.Engine.Persistence; namespace BudgetAnalyser.Engine { @@ -14,4 +14,4 @@ public interface IReaderWriterSelector /// An instance of the repository ready to use. IFileReaderWriter SelectReaderWriter(bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/BankBalance.cs b/BudgetAnalyser.Engine/Ledger/BankBalance.cs index fe01dcd6..32b71dde 100644 --- a/BudgetAnalyser.Engine/Ledger/BankBalance.cs +++ b/BudgetAnalyser.Engine/Ledger/BankBalance.cs @@ -26,4 +26,4 @@ public BankBalance(Account account, decimal balance) /// public decimal Balance { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/BankBalanceAdjustmentTransaction.cs b/BudgetAnalyser.Engine/Ledger/BankBalanceAdjustmentTransaction.cs index 44cf37f2..f51583f2 100644 --- a/BudgetAnalyser.Engine/Ledger/BankBalanceAdjustmentTransaction.cs +++ b/BudgetAnalyser.Engine/Ledger/BankBalanceAdjustmentTransaction.cs @@ -29,4 +29,4 @@ internal BankBalanceAdjustmentTransaction() /// public Account BankAccount { get; internal set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/BudgetCreditLedgerTransaction.cs b/BudgetAnalyser.Engine/Ledger/BudgetCreditLedgerTransaction.cs index 285dac41..3fe17575 100644 --- a/BudgetAnalyser.Engine/Ledger/BudgetCreditLedgerTransaction.cs +++ b/BudgetAnalyser.Engine/Ledger/BudgetCreditLedgerTransaction.cs @@ -23,4 +23,4 @@ internal BudgetCreditLedgerTransaction() { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/CorruptedLedgerBookException.cs b/BudgetAnalyser.Engine/Ledger/CorruptedLedgerBookException.cs index 8e04db80..fdd64adb 100644 --- a/BudgetAnalyser.Engine/Ledger/CorruptedLedgerBookException.cs +++ b/BudgetAnalyser.Engine/Ledger/CorruptedLedgerBookException.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Ledger @@ -35,4 +35,4 @@ public CorruptedLedgerBookException(string message, Exception innerException) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/CreditLedgerTransaction.cs b/BudgetAnalyser.Engine/Ledger/CreditLedgerTransaction.cs index e3b55cd1..7b6e50d7 100644 --- a/BudgetAnalyser.Engine/Ledger/CreditLedgerTransaction.cs +++ b/BudgetAnalyser.Engine/Ledger/CreditLedgerTransaction.cs @@ -21,4 +21,4 @@ internal CreditLedgerTransaction() { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/BankBalanceDto.cs b/BudgetAnalyser.Engine/Ledger/Data/BankBalanceDto.cs index d732c772..3b5e64f5 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/BankBalanceDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/BankBalanceDto.cs @@ -17,4 +17,4 @@ public class BankBalanceDto /// Gets or sets the balance. /// public decimal Balance { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/ILedgerBucketFactory.cs b/BudgetAnalyser.Engine/Ledger/Data/ILedgerBucketFactory.cs index 1ba208b2..289af135 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/ILedgerBucketFactory.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/ILedgerBucketFactory.cs @@ -6,4 +6,4 @@ internal interface ILedgerBucketFactory { LedgerBucket Build(string bucketCode, string accountName); LedgerBucket Build(string bucketCode, Account account); -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/ILedgerTransactionFactory.cs b/BudgetAnalyser.Engine/Ledger/Data/ILedgerTransactionFactory.cs index 898b54ce..4af8591f 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/ILedgerTransactionFactory.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/ILedgerTransactionFactory.cs @@ -11,4 +11,4 @@ internal interface ILedgerTransactionFactory /// Builds the specified transaction. /// LedgerTransaction Build(string transactionTypeName, Guid id); -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookDto.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookDto.cs index 70da75cf..2fcb29ea 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookDto.cs @@ -62,4 +62,4 @@ public LedgerBookDto() /// Gets or sets the storage key. /// public string StorageKey { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.cs index bd7ddb14..f147b69a 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.cs @@ -10,25 +10,17 @@ namespace BudgetAnalyser.Engine.Ledger.Data; [AutoRegisterWithIoC] -internal partial class Mapper_LedgerBookDto_LedgerBook +internal partial class MapperLedgerBookDto2LedgerBook( + IBudgetBucketRepository bucketRepo, + IAccountTypeRepository accountTypeRepo, + ILedgerBucketFactory bucketFactory, + ILedgerTransactionFactory transactionFactory) { - private readonly IAccountTypeRepository accountTypeRepo; - private readonly ILedgerBucketFactory bucketFactory; - private readonly IBudgetBucketRepository bucketRepo; + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); + private readonly ILedgerBucketFactory bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); + private readonly IBudgetBucketRepository bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); private readonly Dictionary cachedLedgers = new(); - private readonly ILedgerTransactionFactory transactionFactory; - - public Mapper_LedgerBookDto_LedgerBook( - [NotNull] IBudgetBucketRepository bucketRepo, - [NotNull] IAccountTypeRepository accountTypeRepo, - [NotNull] ILedgerBucketFactory bucketFactory, - [NotNull] ILedgerTransactionFactory transactionFactory) - { - this.bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - this.bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); - this.transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); - } + private readonly ILedgerTransactionFactory transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); // ReSharper disable once UnusedParameter.Local - This argument is used to optionally detect elements not in array. private LedgerBucket GetOrAddFromCache(LedgerBucket ledger, bool throwIfNotFound = false) @@ -111,13 +103,13 @@ partial void ToModelPostprocessing(LedgerBookDto dto, ref LedgerBook model) } [AutoRegisterWithIoC] -internal partial class Mapper_LedgerBucketDto_LedgerBucket +internal partial class MapperLedgerBucketDto2LedgerBucket { private readonly IAccountTypeRepository accountTypeRepo; private readonly ILedgerBucketFactory bucketFactory; private readonly IBudgetBucketRepository bucketRepo; - public Mapper_LedgerBucketDto_LedgerBucket([NotNull] IBudgetBucketRepository bucketRepo, [NotNull] IAccountTypeRepository accountTypeRepo, [NotNull] ILedgerBucketFactory bucketFactory) + public MapperLedgerBucketDto2LedgerBucket(IBudgetBucketRepository bucketRepo, IAccountTypeRepository accountTypeRepo, ILedgerBucketFactory bucketFactory) { this.bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); @@ -144,21 +136,14 @@ partial void ToModelPostprocessing(LedgerBucketDto dto, ref LedgerBucket model) } [AutoRegisterWithIoC] -internal partial class Mapper_LedgerEntryLineDto_LedgerEntryLine +internal partial class MapperLedgerEntryLineDto2LedgerEntryLine( + IAccountTypeRepository accountTypeRepo, + ILedgerBucketFactory bucketFactory, + ILedgerTransactionFactory transactionFactory) { - private readonly IAccountTypeRepository accountTypeRepo; - private readonly ILedgerBucketFactory bucketFactory; - private readonly ILedgerTransactionFactory transactionFactory; - - public Mapper_LedgerEntryLineDto_LedgerEntryLine( - [NotNull] IAccountTypeRepository accountTypeRepo, - [NotNull] ILedgerBucketFactory bucketFactory, - [NotNull] ILedgerTransactionFactory transactionFactory) - { - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - this.bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); - this.transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); - } + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); + private readonly ILedgerBucketFactory bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); + private readonly ILedgerTransactionFactory transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); partial void ToDtoPostprocessing(ref LedgerEntryLineDto dto, LedgerEntryLine model) { @@ -172,14 +157,9 @@ partial void ToModelPostprocessing(LedgerEntryLineDto dto, ref LedgerEntryLine m } [AutoRegisterWithIoC] -internal partial class Mapper_LedgerTransactionDto_BankBalanceAdjustmentTransaction +internal partial class MapperLedgerTransactionDto2BankBalanceAdjustmentTransaction(IAccountTypeRepository accountTypeRepo) { - private readonly IAccountTypeRepository accountTypeRepo; - - public Mapper_LedgerTransactionDto_BankBalanceAdjustmentTransaction([NotNull] IAccountTypeRepository accountTypeRepo) - { - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - } + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); partial void ToDtoPostprocessing(ref LedgerTransactionDto dto, BankBalanceAdjustmentTransaction model) { @@ -194,14 +174,9 @@ partial void ToModelPostprocessing(LedgerTransactionDto dto, ref BankBalanceAdju } [AutoRegisterWithIoC] -internal partial class Mapper_BankBalanceDto_BankBalance +internal partial class MapperBankBalanceDto2BankBalance(IAccountTypeRepository accountTypeRepo) { - private readonly IAccountTypeRepository accountTypeRepo; - - public Mapper_BankBalanceDto_BankBalance([NotNull] IAccountTypeRepository accountTypeRepo) - { - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - } + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); // ReSharper disable once RedundantAssignment partial void ModelFactory(BankBalanceDto dto, ref BankBalance model) @@ -216,21 +191,14 @@ partial void ToDtoPostprocessing(ref BankBalanceDto dto, BankBalance model) } [AutoRegisterWithIoC] -internal partial class Mapper_LedgerEntryDto_LedgerEntry +internal partial class MapperLedgerEntryDto2LedgerEntry( + ILedgerBucketFactory bucketFactory, + ILedgerTransactionFactory transactionFactory, + IAccountTypeRepository accountTypeRepo) { - private readonly IAccountTypeRepository accountTypeRepo; - private readonly ILedgerBucketFactory bucketFactory; - private readonly ILedgerTransactionFactory transactionFactory; - - public Mapper_LedgerEntryDto_LedgerEntry( - [NotNull] ILedgerBucketFactory bucketFactory, - [NotNull] ILedgerTransactionFactory transactionFactory, - [NotNull] IAccountTypeRepository accountTypeRepo) - { - this.bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); - this.transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - } + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); + private readonly ILedgerBucketFactory bucketFactory = bucketFactory ?? throw new ArgumentNullException(nameof(bucketFactory)); + private readonly ILedgerTransactionFactory transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); partial void ToDtoPostprocessing(ref LedgerEntryDto dto, LedgerEntry model) { @@ -246,7 +214,7 @@ partial void ToModelPostprocessing(LedgerEntryDto dto, ref LedgerEntry model) partial void ToModelPreprocessing(LedgerEntryDto dto, LedgerEntry model) { // Transactions must be done first otherwise balance will be changed by adding transactions and the balance should be read from the Dto. - var transactionMapper = new Mapper_LedgerTransactionDto_LedgerTransaction(this.transactionFactory, this.accountTypeRepo); + var transactionMapper = new MapperLedgerTransactionDto2LedgerTransaction(this.transactionFactory, this.accountTypeRepo); foreach (var txn in dto.Transactions) { model.AddTransactionForPersistenceOnly(transactionMapper.ToModel(txn)); @@ -255,16 +223,10 @@ partial void ToModelPreprocessing(LedgerEntryDto dto, LedgerEntry model) } [AutoRegisterWithIoC] -internal partial class Mapper_LedgerTransactionDto_LedgerTransaction +internal partial class MapperLedgerTransactionDto2LedgerTransaction(ILedgerTransactionFactory transactionFactory, IAccountTypeRepository accountTypeRepo) { - private readonly IAccountTypeRepository accountTypeRepo; - private readonly ILedgerTransactionFactory transactionFactory; - - public Mapper_LedgerTransactionDto_LedgerTransaction([NotNull] ILedgerTransactionFactory transactionFactory, [NotNull] IAccountTypeRepository accountTypeRepo) - { - this.transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); - this.accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); - } + private readonly IAccountTypeRepository accountTypeRepo = accountTypeRepo ?? throw new ArgumentNullException(nameof(accountTypeRepo)); + private readonly ILedgerTransactionFactory transactionFactory = transactionFactory ?? throw new ArgumentNullException(nameof(transactionFactory)); // ReSharper disable once RedundantAssignment partial void ModelFactory(LedgerTransactionDto dto, ref LedgerTransaction model) @@ -290,4 +252,4 @@ partial void ToModelPostprocessing(LedgerTransactionDto dto, ref LedgerTransacti balanceTransaction.BankAccount = this.accountTypeRepo.GetByKey(dto.Account); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.generated.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.generated.cs index cac6548a..261869d9 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.generated.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerBookToDtoMapper.generated.cs @@ -12,7 +12,7 @@ namespace BudgetAnalyser.Engine.Ledger.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerBookDto_LedgerBook : IDtoMapper + internal partial class MapperLedgerBookDto2LedgerBook : IDtoMapper { public virtual LedgerBook ToModel(LedgerBookDto dto) @@ -27,14 +27,14 @@ public virtual LedgerBook ToModel(LedgerBookDto dto) model = (LedgerBook)constructor.Invoke(new Type[] { }); } var modelType = model.GetType(); - var mapper1 = new Mapper_LedgerBucketDto_LedgerBucket(this.bucketRepo, this.accountTypeRepo, this.bucketFactory); + var mapper1 = new MapperLedgerBucketDto2LedgerBucket(this.bucketRepo, this.accountTypeRepo, this.bucketFactory); var ledgers1 = dto.Ledgers.Select(mapper1.ToModel).ToList(); modelType.GetProperty("Ledgers").SetValue(model, ledgers1); var modified2 = dto.Modified; modelType.GetProperty("Modified").SetValue(model, modified2); var name3 = dto.Name; modelType.GetProperty("Name").SetValue(model, name3); - var mapper2 = new Mapper_LedgerEntryLineDto_LedgerEntryLine(this.accountTypeRepo, this.bucketFactory, this.transactionFactory); + var mapper2 = new MapperLedgerEntryLineDto2LedgerEntryLine(this.accountTypeRepo, this.bucketFactory, this.transactionFactory); var reconciliations4 = dto.Reconciliations.Select(mapper2.ToModel).ToList(); modelType.GetProperty("Reconciliations").SetValue(model, reconciliations4); var storageKey5 = dto.StorageKey; @@ -55,14 +55,14 @@ public virtual LedgerBookDto ToDto(LedgerBook model) { dto = new LedgerBookDto(); } - var mapper3 = new Mapper_LedgerBucketDto_LedgerBucket(this.bucketRepo, this.accountTypeRepo, this.bucketFactory); + var mapper3 = new MapperLedgerBucketDto2LedgerBucket(this.bucketRepo, this.accountTypeRepo, this.bucketFactory); var ledgers7 = model.Ledgers.Select(mapper3.ToDto).ToList(); dto.Ledgers = ledgers7; var modified8 = model.Modified; dto.Modified = modified8; var name9 = model.Name; dto.Name = name9; - var mapper4 = new Mapper_LedgerEntryLineDto_LedgerEntryLine(this.accountTypeRepo, this.bucketFactory, this.transactionFactory); + var mapper4 = new MapperLedgerEntryLineDto2LedgerEntryLine(this.accountTypeRepo, this.bucketFactory, this.transactionFactory); var reconciliations10 = model.Reconciliations.Select(mapper4.ToDto).ToList(); dto.Reconciliations = reconciliations10; var storageKey11 = model.StorageKey; @@ -82,7 +82,7 @@ public virtual LedgerBookDto ToDto(LedgerBook model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerBucketDto_LedgerBucket : IDtoMapper + internal partial class MapperLedgerBucketDto2LedgerBucket : IDtoMapper { public virtual LedgerBucket ToModel(LedgerBucketDto dto) @@ -124,7 +124,7 @@ public virtual LedgerBucketDto ToDto(LedgerBucket model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerEntryLineDto_LedgerEntryLine : IDtoMapper + internal partial class MapperLedgerEntryLineDto2LedgerEntryLine : IDtoMapper { public virtual LedgerEntryLine ToModel(LedgerEntryLineDto dto) @@ -139,15 +139,15 @@ public virtual LedgerEntryLine ToModel(LedgerEntryLineDto dto) model = (LedgerEntryLine)constructor.Invoke(new Type[] { }); } var modelType = model.GetType(); - var mapper5 = new Mapper_LedgerTransactionDto_BankBalanceAdjustmentTransaction(this.accountTypeRepo); + var mapper5 = new MapperLedgerTransactionDto2BankBalanceAdjustmentTransaction(this.accountTypeRepo); var bankBalanceAdjustments18 = dto.BankBalanceAdjustments.Select(mapper5.ToModel).ToList(); modelType.GetProperty("BankBalanceAdjustments").SetValue(model, bankBalanceAdjustments18); - var mapper6 = new Mapper_BankBalanceDto_BankBalance(this.accountTypeRepo); + var mapper6 = new MapperBankBalanceDto2BankBalance(this.accountTypeRepo); var bankBalances19 = dto.BankBalances.Select(mapper6.ToModel).ToList(); modelType.GetProperty("BankBalances").SetValue(model, bankBalances19); var date20 = dto.Date; modelType.GetProperty("Date").SetValue(model, date20); - var mapper7 = new Mapper_LedgerEntryDto_LedgerEntry(this.bucketFactory, this.transactionFactory, this.accountTypeRepo); + var mapper7 = new MapperLedgerEntryDto2LedgerEntry(this.bucketFactory, this.transactionFactory, this.accountTypeRepo); var entries21 = dto.Entries.Select(mapper7.ToModel).ToList(); modelType.GetProperty("Entries").SetValue(model, entries21); var remarks22 = dto.Remarks; @@ -165,15 +165,15 @@ public virtual LedgerEntryLineDto ToDto(LedgerEntryLine model) { dto = new LedgerEntryLineDto(); } - var mapper8 = new Mapper_LedgerTransactionDto_BankBalanceAdjustmentTransaction(this.accountTypeRepo); + var mapper8 = new MapperLedgerTransactionDto2BankBalanceAdjustmentTransaction(this.accountTypeRepo); var bankBalanceAdjustments24 = model.BankBalanceAdjustments.Select(mapper8.ToDto).ToList(); dto.BankBalanceAdjustments = bankBalanceAdjustments24; - var mapper9 = new Mapper_BankBalanceDto_BankBalance(this.accountTypeRepo); + var mapper9 = new MapperBankBalanceDto2BankBalance(this.accountTypeRepo); var bankBalances25 = model.BankBalances.Select(mapper9.ToDto).ToList(); dto.BankBalances = bankBalances25; var date26 = model.Date; dto.Date = date26; - var mapper10 = new Mapper_LedgerEntryDto_LedgerEntry(this.bucketFactory, this.transactionFactory, this.accountTypeRepo); + var mapper10 = new MapperLedgerEntryDto2LedgerEntry(this.bucketFactory, this.transactionFactory, this.accountTypeRepo); var entries27 = model.Entries.Select(mapper10.ToDto).ToList(); dto.Entries = entries27; var remarks28 = model.Remarks; @@ -190,7 +190,7 @@ public virtual LedgerEntryLineDto ToDto(LedgerEntryLine model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerTransactionDto_BankBalanceAdjustmentTransaction : IDtoMapper + internal partial class MapperLedgerTransactionDto2BankBalanceAdjustmentTransaction : IDtoMapper { public virtual BankBalanceAdjustmentTransaction ToModel(LedgerTransactionDto dto) @@ -250,7 +250,7 @@ public virtual LedgerTransactionDto ToDto(BankBalanceAdjustmentTransaction model } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_BankBalanceDto_BankBalance : IDtoMapper + internal partial class MapperBankBalanceDto2BankBalance : IDtoMapper { public virtual BankBalance ToModel(BankBalanceDto dto) @@ -290,7 +290,7 @@ public virtual BankBalanceDto ToDto(BankBalance model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerEntryDto_LedgerEntry : IDtoMapper + internal partial class MapperLedgerEntryDto2LedgerEntry : IDtoMapper { public virtual LedgerEntry ToModel(LedgerEntryDto dto) @@ -322,7 +322,7 @@ public virtual LedgerEntryDto ToDto(LedgerEntry model) } var balance49 = model.Balance; dto.Balance = balance49; - var mapper11 = new Mapper_LedgerTransactionDto_LedgerTransaction(this.transactionFactory, this.accountTypeRepo); + var mapper11 = new MapperLedgerTransactionDto2LedgerTransaction(this.transactionFactory, this.accountTypeRepo); var transactions52 = model.Transactions.Select(mapper11.ToDto).ToList(); dto.Transactions = transactions52; ToDtoPostprocessing(ref dto, model); @@ -337,7 +337,7 @@ public virtual LedgerEntryDto ToDto(LedgerEntry model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 3/01/2016 2:19:01 AM UTC")] - internal partial class Mapper_LedgerTransactionDto_LedgerTransaction : IDtoMapper + internal partial class MapperLedgerTransactionDto2LedgerTransaction : IDtoMapper { public virtual LedgerTransaction ToModel(LedgerTransactionDto dto) diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketDto.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketDto.cs index 81421cf1..477e7e5a 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketDto.cs @@ -29,4 +29,4 @@ public LedgerBucketDto() /// Gets or sets the bank account that this ledger bucket is stored in. /// public string StoredInAccount { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketFactory.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketFactory.cs index 2382936c..dee6c77e 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketFactory.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerBucketFactory.cs @@ -36,11 +36,8 @@ public LedgerBucket Build(string bucketCode, Account account) return new SavedUpForLedger { BudgetBucket = bucket, StoredInAccount = account }; } - if (bucket is SpentPerPeriodExpenseBucket) - { - return new SpentPerPeriodLedger { BudgetBucket = bucket, StoredInAccount = account }; - } - - throw new NotSupportedException($"Unsupported budget bucket {bucketCode} with type {bucket.GetType().Name}, found in ledger book"); + return bucket is SpentPerPeriodExpenseBucket + ? (LedgerBucket)new SpentPerPeriodLedger { BudgetBucket = bucket, StoredInAccount = account } + : throw new NotSupportedException($"Unsupported budget bucket {bucketCode} with type {bucket.GetType().Name}, found in ledger book"); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryDto.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryDto.cs index 393f9918..d8b3b106 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryDto.cs @@ -40,4 +40,4 @@ public LedgerEntryDto() [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Required for serialisation")] [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Required for serialisation")] public List Transactions { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryLineDto.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryLineDto.cs index 5f7abe8f..965a4a2d 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryLineDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerEntryLineDto.cs @@ -57,4 +57,4 @@ public LedgerEntryLineDto() /// Gets or sets the remarks. /// public string Remarks { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionDto.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionDto.cs index f01315a7..dbbf3ba3 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionDto.cs @@ -44,4 +44,4 @@ public class LedgerTransactionDto /// Gets or sets the type of the transaction. /// public string TransactionType { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionFactory.cs b/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionFactory.cs index c5ea699c..5393236e 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionFactory.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/LedgerTransactionFactory.cs @@ -17,11 +17,8 @@ internal class LedgerTransactionFactory : ILedgerTransactionFactory public LedgerTransaction Build(string transactionTypeName, Guid id) { var type = Type.GetType(transactionTypeName); - if (type is null) - { - throw new DataFormatException("Invalid transaction type encountered: " + transactionTypeName); - } - - return Activator.CreateInstance(type, id) as LedgerTransaction; + return type is null + ? throw new DataFormatException("Invalid transaction type encountered: " + transactionTypeName) + : Activator.CreateInstance(type, id) as LedgerTransaction; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/MobileStorageSettingsDto.cs b/BudgetAnalyser.Engine/Ledger/Data/MobileStorageSettingsDto.cs index 1def90e6..a0dd6ddd 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/MobileStorageSettingsDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/MobileStorageSettingsDto.cs @@ -19,4 +19,4 @@ public class MobileStorageSettingsDto /// The Amazon S3 region the data is stored in /// public string AmazonS3Region { get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/ToDoCollectionToDtoMapper.cs b/BudgetAnalyser.Engine/Ledger/Data/ToDoCollectionToDtoMapper.cs index 827b2998..2d20699f 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/ToDoCollectionToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/ToDoCollectionToDtoMapper.cs @@ -7,7 +7,7 @@ namespace BudgetAnalyser.Engine.Ledger.Data; [AutoRegisterWithIoC] -internal class Mapper_ListToDoTaskDto_ToDoCollection : IDtoMapper, ToDoCollection> +internal class MapperListToDoTaskDto2ToDoCollection : IDtoMapper, ToDoCollection> { public List ToDto(ToDoCollection model) { @@ -29,4 +29,4 @@ public ToDoCollection ToModel([NotNull] List dto) dto.ForEach(d => model.Add(mapper.ToModel(d))); return model; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Data/ToDoTaskDto.cs b/BudgetAnalyser.Engine/Ledger/Data/ToDoTaskDto.cs index 0c1bd51d..a87bc0bf 100644 --- a/BudgetAnalyser.Engine/Ledger/Data/ToDoTaskDto.cs +++ b/BudgetAnalyser.Engine/Ledger/Data/ToDoTaskDto.cs @@ -21,4 +21,4 @@ public class ToDoTaskDto /// Gets or sets a value indicating whether task is system generated. /// public bool SystemGenerated { [UsedImplicitly] get; set; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/ILedgerBookRepository.cs b/BudgetAnalyser.Engine/Ledger/ILedgerBookRepository.cs index 1e070d92..31db0f85 100644 --- a/BudgetAnalyser.Engine/Ledger/ILedgerBookRepository.cs +++ b/BudgetAnalyser.Engine/Ledger/ILedgerBookRepository.cs @@ -42,4 +42,4 @@ public interface ILedgerBookRepository /// Will be thrown if arguments are null. Task SaveAsync([NotNull] LedgerBook book, [NotNull] string storageKey, bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerBook.cs b/BudgetAnalyser.Engine/Ledger/LedgerBook.cs index 3f1733ab..2cbde474 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerBook.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerBook.cs @@ -34,7 +34,7 @@ internal LedgerBook() public IEnumerable Ledgers { get => this.ledgersColumns; - internal set { this.ledgersColumns = value.OrderBy(c => c.BudgetBucket.Code).ToList(); } + internal set => this.ledgersColumns = value.OrderBy(c => c.BudgetBucket.Code).ToList(); } /// @@ -58,7 +58,8 @@ public IEnumerable Ledgers public IEnumerable Reconciliations { get => this.reconciliations; - [UsedImplicitly] private set => this.reconciliations = value.ToList(); + [UsedImplicitly] + private set => this.reconciliations = value.ToList(); } /// @@ -110,8 +111,8 @@ public bool Validate([NotNull] StringBuilder validationMessages) /// public IEnumerable LedgersAvailableForTransfer() { - List ledgers = Ledgers.ToList(); - IEnumerable accounts = Ledgers.Select(l => l.StoredInAccount).Distinct(); + var ledgers = Ledgers.ToList(); + var accounts = Ledgers.Select(l => l.StoredInAccount).Distinct(); foreach (var account in accounts) { ledgers.Insert(0, new SurplusLedger { StoredInAccount = account }); @@ -173,4 +174,4 @@ internal LedgerEntryLine UnlockMostRecentLine() return line; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerBucket.cs b/BudgetAnalyser.Engine/Ledger/LedgerBucket.cs index 923226be..7d4e8823 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerBucket.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerBucket.cs @@ -33,7 +33,7 @@ public abstract class LedgerBucket /// public BudgetBucket BudgetBucket { - get { return this.budgetBucket; } + get => this.budgetBucket; internal set { ValidateBucketSet(value); @@ -58,16 +58,16 @@ internal set public abstract bool ApplyReconciliationBehaviour([NotNull] IList transactions, DateTime reconciliationDate, decimal openingBalance); /// - /// Determines whether the specified , is equal to this instance. + /// Determines whether the specified , is equal to this instance. /// Delegates to /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -75,11 +75,7 @@ public override bool Equals(object obj) { return true; } - if (obj.GetType() != GetType()) - { - return false; - } - return Equals((LedgerBucket) obj); + return obj.GetType() != GetType() ? false : Equals((LedgerBucket)obj); } /// @@ -130,11 +126,7 @@ public override string ToString() /// protected bool Equals([CanBeNull] LedgerBucket other) { - if (other is null) - { - return false; - } - return Equals(BudgetBucket, other.BudgetBucket) && Equals(StoredInAccount, other.StoredInAccount); + return other is null ? false : Equals(BudgetBucket, other.BudgetBucket) && Equals(StoredInAccount, other.StoredInAccount); } /// @@ -143,4 +135,4 @@ protected bool Equals([CanBeNull] LedgerBucket other) /// protected abstract void ValidateBucketSet(BudgetBucket bucket); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerCalculation.cs b/BudgetAnalyser.Engine/Ledger/LedgerCalculation.cs index 568fe6a7..6433f7aa 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerCalculation.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerCalculation.cs @@ -120,7 +120,7 @@ public virtual decimal CalculateCurrentPeriodSurplusBalance([NotNull] LedgerEntr balance += transactionTotal; // Find any ledgers that are overpsent and subtract them from the Surplus total. This is actually what is happening when you overspend a ledger, it spills over and spend Surplus. - Dictionary ledgersSummary = CalculateLedgersCurrentBalances(ledgerLine, filter.BeginDate.Value, filter.EndDate.Value, statement); + var ledgersSummary = CalculateLedgersCurrentBalances(ledgerLine, filter.BeginDate.Value, filter.EndDate.Value, statement); balance += ledgersSummary.Where(kvp => kvp.Value < 0).Sum(kvp => kvp.Value); return balance; @@ -189,8 +189,8 @@ List GetOverSpentTransactions() //private function { var overSpendTransactions = new List(); var currentDate = inclBeginDate; - Dictionary runningBalances = ledgerLine.Entries.ToDictionary(entry => entry.LedgerBucket.BudgetBucket, entry => entry.Balance); - Dictionary previousBalances = ledgerLine.Entries.ToDictionary(entry => entry.LedgerBucket.BudgetBucket, _ => 0M); + var runningBalances = ledgerLine.Entries.ToDictionary(entry => entry.LedgerBucket.BudgetBucket, entry => entry.Balance); + var previousBalances = ledgerLine.Entries.ToDictionary(entry => entry.LedgerBucket.BudgetBucket, _ => 0M); do { @@ -233,12 +233,9 @@ public virtual decimal LocateApplicableLedgerBalance([NotNull] LedgerBook ledger } var line = LocateApplicableLedgerLine(ledgerBook, filter); - if (line is null) - { - return 0; - } - - return line.Entries + return line is null + ? 0 + : line.Entries .Where(ledgerEntry => ledgerEntry.LedgerBucket.BudgetBucket.Code == bucketCode) .Select(ledgerEntry => ledgerEntry.Balance) .FirstOrDefault(); @@ -261,12 +258,9 @@ public virtual LedgerEntryLine LocateApplicableLedgerLine(LedgerBook ledgerBook, throw new ArgumentNullException(nameof(filter)); } - if (filter.Cleared) - { - return ledgerBook.Reconciliations.FirstOrDefault(); - } - - return LocateApplicableLedgerLine(ledgerBook, filter.BeginDate, filter.EndDate); + return filter.Cleared + ? ledgerBook.Reconciliations.FirstOrDefault() + : LocateApplicableLedgerLine(ledgerBook, filter.BeginDate, filter.EndDate); } public virtual LedgerEntryLine LocateApplicableLedgerLine(LedgerBook ledgerBook, DateTime? inclBeginDate, DateTime? inclEndDate) @@ -282,12 +276,9 @@ public virtual LedgerEntryLine LocateApplicableLedgerLine(LedgerBook ledgerBook, return null; } - if (inclEndDate == default || inclEndDate.Value == DateTime.MinValue) - { - return null; - } - - return LocateLedgerEntryLine(ledgerBook, inclBeginDate.Value, inclEndDate.Value); + return inclEndDate == default || inclEndDate.Value == DateTime.MinValue + ? null + : LocateLedgerEntryLine(ledgerBook, inclBeginDate.Value, inclEndDate.Value); } private static string BuildCacheKey(object dependency1, object dependency2, DateTime dependentDate) @@ -317,9 +308,9 @@ private Dictionary CalculateLedgersCurrentBalances(Ledger private decimal CalculateTransactionTotal(DateTime inclBeginDate, DateTime inclEndDate, StatementModel statement, LedgerEntryLine entryLine, string bucketCode) { - IEnumerable autoMatchLedgerTransactions = GetAutoMatchingTransactions(statement, entryLine, inclBeginDate); + var autoMatchLedgerTransactions = GetAutoMatchingTransactions(statement, entryLine, inclBeginDate); // This needs to query .AllTransactions, not just .Transactions, when changing the date range the statement may not have had its internal filter changed when this runs. - IEnumerable transactions = statement.AllTransactions + var transactions = statement.AllTransactions .Where(t => t.Date >= inclBeginDate && t.Date <= inclEndDate) .Where(txn => !ReconciliationBuilder.IsAutoMatchingTransaction(txn, autoMatchLedgerTransactions)); @@ -405,7 +396,7 @@ private static void ProcessOverdrawnLedgers( List overSpendTransactions, DateTime currentDate) { - foreach (KeyValuePair runningBalance in runningBalances) + foreach (var runningBalance in runningBalances) { var previousBalance = previousBalances[runningBalance.Key]; @@ -466,4 +457,4 @@ private static void ProcessOverdrawnLedgers( } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerEntry.cs b/BudgetAnalyser.Engine/Ledger/LedgerEntry.cs index 9a12a1b9..23785d1a 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerEntry.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerEntry.cs @@ -167,4 +167,4 @@ internal bool Validate(StringBuilder validationMessages, decimal openingBalance) return result; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerEntryLine.cs b/BudgetAnalyser.Engine/Ledger/LedgerEntryLine.cs index d3b12ef2..002c2533 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerEntryLine.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerEntryLine.cs @@ -64,7 +64,8 @@ internal LedgerEntryLine(DateTime reconciliationDate, [NotNull] IEnumerable BankBalanceAdjustments { get => this.bankBalanceAdjustments; - [UsedImplicitly] private set => this.bankBalanceAdjustments = value.ToList(); + [UsedImplicitly] + private set => this.bankBalanceAdjustments = value.ToList(); } /// @@ -74,7 +75,8 @@ public IEnumerable BankBalanceAdjustments public IEnumerable BankBalances { get => this.bankBalancesList; - [UsedImplicitly] private set => this.bankBalancesList = value.ToList(); + [UsedImplicitly] + private set => this.bankBalancesList = value.ToList(); } /// @@ -130,10 +132,10 @@ public IEnumerable SurplusBalances { get { - IEnumerable adjustedBalances = + var adjustedBalances = BankBalances.Select( b => new BankBalance(b.Account, b.Balance + TotalBankBalanceAdjustmentForAccount(b.Account))); - IEnumerable results = Entries.GroupBy( + var results = Entries.GroupBy( e => e.LedgerBucket.StoredInAccount, (accountType, ledgerEntries) => new BankBalance(accountType, ledgerEntries.Sum(e => e.Balance))); return @@ -285,4 +287,4 @@ private decimal TotalBankBalanceAdjustmentForAccount(Account account) return BankBalanceAdjustments.Where(a => a.BankAccount == account).Sum(a => a.Amount); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/LedgerTransaction.cs b/BudgetAnalyser.Engine/Ledger/LedgerTransaction.cs index c32a9157..5a70f3bd 100644 --- a/BudgetAnalyser.Engine/Ledger/LedgerTransaction.cs +++ b/BudgetAnalyser.Engine/Ledger/LedgerTransaction.cs @@ -90,4 +90,4 @@ internal virtual LedgerTransaction WithNarrative([NotNull] string narrative) return this; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationBuilder.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationBuilder.cs index 4d926c8f..ca658db7 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationBuilder.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationBuilder.cs @@ -1,4 +1,4 @@ -using System; +using System; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Statement; using JetBrains.Annotations; @@ -27,4 +27,4 @@ ReconciliationResult CreateNewMonthlyReconciliation( [NotNull] StatementModel statement, [NotNull] params BankBalance[] bankBalances); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationConsistency.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationConsistency.cs index 18d41f7b..ec16359b 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationConsistency.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationConsistency.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.Engine.Ledger.Reconciliation { @@ -6,4 +6,4 @@ internal interface IReconciliationConsistency { IDisposable EnsureConsistency(LedgerBook book); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationCreationManager.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationCreationManager.cs index 521f6649..239f42c8 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationCreationManager.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/IReconciliationCreationManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Statement; using JetBrains.Annotations; @@ -45,4 +45,4 @@ ReconciliationResult PeriodEndReconciliation([NotNull] LedgerBook ledgerBook, /// void ValidateAgainstOrphanedAutoMatchingTransactions([NotNull] LedgerBook ledgerBook, [NotNull] StatementModel statement); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBalanceAdjustsForFutureTransactions.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBalanceAdjustsForFutureTransactions.cs index df933b61..b0fc8d04 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBalanceAdjustsForFutureTransactions.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBalanceAdjustsForFutureTransactions.cs @@ -69,4 +69,4 @@ private void AddBalanceAdjustmentsForFutureTransactions(StatementModel statement } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBudgetAmountBalanceAdjustments.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBudgetAmountBalanceAdjustments.cs index 2583ff12..0989425c 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBudgetAmountBalanceAdjustments.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourBudgetAmountBalanceAdjustments.cs @@ -38,9 +38,9 @@ public void ApplyBehaviour() private void CreateBalanceAdjustmentForBudgetAmounts() { - List transferTasks = TodoTasks.OfType().ToList(); - foreach (IGrouping grouping in transferTasks.GroupBy(t => t.SourceAccount, tasks => tasks)) - // Rather than create a task, just do it + var transferTasks = TodoTasks.OfType().ToList(); + foreach (var grouping in transferTasks.GroupBy(t => t.SourceAccount, tasks => tasks)) + // Rather than create a task, just do it { NewReconLine.BalanceAdjustment( -grouping.Sum(t => t.Amount), @@ -48,8 +48,8 @@ private void CreateBalanceAdjustmentForBudgetAmounts() grouping.Key); } - foreach (IGrouping grouping in transferTasks.GroupBy(t => t.DestinationAccount, tasks => tasks)) - // Rather than create a task, just do it + foreach (var grouping in transferTasks.GroupBy(t => t.DestinationAccount, tasks => tasks)) + // Rather than create a task, just do it { NewReconLine.BalanceAdjustment( grouping.Sum(t => t.Amount), @@ -58,4 +58,4 @@ private void CreateBalanceAdjustmentForBudgetAmounts() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourFactory.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourFactory.cs index 52603abc..0dda7be2 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourFactory.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourFactory.cs @@ -22,11 +22,11 @@ public static IEnumerable ListAllBehaviours() return new IReconciliationBehaviour[] { new ReconciliationBehaviourBudgetAmountBalanceAdjustments(), - new ReconciliationBehaviourBalanceAdjustsForFutureTransactions(), - new ReconciliationBehaviourForLedgerBucket(), + new ReconciliationBehaviourBalanceAdjustsForFutureTransactions(), + new ReconciliationBehaviourForLedgerBucket(), new ReconciliationBehaviourPaidFromWrongAccount(), - new ReconciliationBehaviourOverdrawnSurplus(), + new ReconciliationBehaviourOverdrawnSurplus(), }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourLedgerBucket.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourLedgerBucket.cs index 5c26ec72..20f39b71 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourLedgerBucket.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourLedgerBucket.cs @@ -26,7 +26,7 @@ public void ApplyBehaviour() { foreach (var ledger in NewReconLine.Entries) { - List transactions = ledger.Transactions.ToList(); + var transactions = ledger.Transactions.ToList(); if (ledger.LedgerBucket.ApplyReconciliationBehaviour(transactions, NewReconLine.Date, ledger.Balance)) { ledger.SetTransactionsForReconciliation(transactions); @@ -34,4 +34,4 @@ public void ApplyBehaviour() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourOverdrawnSurplus.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourOverdrawnSurplus.cs index 8325cdc0..ce4d5d1f 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourOverdrawnSurplus.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourOverdrawnSurplus.cs @@ -54,4 +54,4 @@ private void CreateToDoForAnyOverdrawnSurplusBalance() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourPaidFromWrongAccount.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourPaidFromWrongAccount.cs index ed24c720..1ec26c3d 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourPaidFromWrongAccount.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBehaviourPaidFromWrongAccount.cs @@ -29,7 +29,7 @@ internal class ReconciliationBehaviourPaidFromWrongAccount : IReconciliationBeha /// public void ApplyBehaviour() { - IList wrongAccountPayments = DiscoverWrongAccountPaymentTransactions(); + var wrongAccountPayments = DiscoverWrongAccountPaymentTransactions(); var reference = ReferenceNumberGenerator.IssueTransactionReferenceNumber(); @@ -91,7 +91,7 @@ private void CreateLedgerTransactionsShowingTransfer(IEnumerable wr Narrative = "Transfer to rectify payment made from wrong account." }; var ledger = NewReconLine.Entries.Single(l => l.LedgerBucket.BudgetBucket == transaction.BudgetBucket); - List replacementTransactions = ledger.Transactions.ToList(); + var replacementTransactions = ledger.Transactions.ToList(); replacementTransactions.Add(journal1); replacementTransactions.Add(journal2); ledger.SetTransactionsForReconciliation(replacementTransactions); @@ -124,7 +124,7 @@ private void CreateUserTasks(IEnumerable wrongAccountPayments, stri private IList DiscoverWrongAccountPaymentTransactions() { - List debitAccountTransactionsOnly = Transactions.Where(t => t.Account.AccountType != AccountType.CreditCard).ToList(); + var debitAccountTransactionsOnly = Transactions.Where(t => t.Account.AccountType != AccountType.CreditCard).ToList(); var wrongAccountPayments = new List(); @@ -173,4 +173,4 @@ private IList DiscoverWrongAccountPaymentTransactions() return wrongAccountPayments; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBuilder.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBuilder.cs index cb76df8f..f79c76a8 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBuilder.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationBuilder.cs @@ -70,12 +70,9 @@ public ReconciliationResult CreateNewMonthlyReconciliation( public static IEnumerable FindAutoMatchingTransactions([CanBeNull] LedgerEntryLine recon, bool includeMatchedTransactions = false) { - if (recon is null) - { - return new List(); - } - - return recon.Entries.SelectMany(e => FindAutoMatchingTransactions(e, includeMatchedTransactions)); + return recon is null + ? new List() + : recon.Entries.SelectMany(e => FindAutoMatchingTransactions(e, includeMatchedTransactions)); } public static bool IsAutoMatchingTransaction(Transaction statementTransaction, IEnumerable ledgerTransactions) @@ -114,7 +111,7 @@ internal static DateTime CalculateBeginDateForReconciliationPeriod(LedgerBook le internal static IEnumerable TransactionsToAutoMatch(IEnumerable transactions, string autoMatchingReference) { - IOrderedEnumerable sortedTransactions = transactions.Where(t => + var sortedTransactions = transactions.Where(t => t.Reference1?.TrimEnd() == autoMatchingReference || t.Reference2?.TrimEnd() == autoMatchingReference || t.Reference3?.TrimEnd() == autoMatchingReference) @@ -134,9 +131,9 @@ private void AddNew(LedgerEntryLine line, BudgetModel budget, StatementModel sta // For example for a monthly budget if this is a reconciliation for the 20/Feb then the start date is 20/Jan and the finish date is 20/Feb. So transactions pulled from statement are between // 20/Jan (inclusive) and 19/Feb (inclusive) but not including anything for the 20th of Feb. // Why? Because the new ledger entry is intended to show the starting balances for the new period, so you can plan for the upcoming period. - List filteredStatementTransactions = statement?.AllTransactions.Where(t => t.Date >= startDateIncl && t.Date < reconciliationDate).ToList() ?? new List(); + var filteredStatementTransactions = statement?.AllTransactions.Where(t => t.Date >= startDateIncl && t.Date < reconciliationDate).ToList() ?? new List(); - IEnumerable previousLedgerBalances = CompileLedgersAndBalances(LedgerBook); + var previousLedgerBalances = CompileLedgersAndBalances(LedgerBook); var entries = new List(); foreach (var previousLedgerEntry in previousLedgerBalances) @@ -158,7 +155,7 @@ private void AddNew(LedgerEntryLine line, BudgetModel budget, StatementModel sta // Start by adding the budgeted amount to a list of transactions. var salaryAccount = line.BankBalances.Single(b => b.Account.IsSalaryAccount).Account; - List transactions = IncludeBudgetedAmount(salaryAccount, budget, ledgerBucket, reconciliationDate); + var transactions = IncludeBudgetedAmount(salaryAccount, budget, ledgerBucket, reconciliationDate); // Append all other transactions for this bucket, if any, to the transaction list. transactions.AddRange(IncludeStatementTransactions(newEntry, filteredStatementTransactions)); @@ -190,7 +187,7 @@ private void AddNew(LedgerEntryLine line, BudgetModel budget, StatementModel sta /// private void AutoMatchTransactionsAlreadyInPreviousPeriod(DateTime lineDate, List transactions, LedgerEntry previousLedgerEntry, List newLedgerTransactions) { - List ledgerAutoMatchTransactions = FindAutoMatchingTransactions(previousLedgerEntry).ToList(); + var ledgerAutoMatchTransactions = FindAutoMatchingTransactions(previousLedgerEntry).ToList(); var checkMatchedTxns = new List(); var checkMatchCount = 0; foreach (var lastMonthLedgerTransaction in ledgerAutoMatchTransactions) @@ -232,7 +229,7 @@ private void AutoMatchTransactionsAlreadyInPreviousPeriod(DateTime lineDate, Lis "Ledger Reconciliation - WARNING {0} ledger transactions appear to be waiting to be auto-matched, but no statement transactions were found. {1}", ledgerAutoMatchTransactions.Count(), ledgerAutoMatchTransactions.First().AutoMatchingReference)); - IEnumerable unmatchedTxns = ledgerAutoMatchTransactions.Except(checkMatchedTxns); + var unmatchedTxns = ledgerAutoMatchTransactions.Except(checkMatchedTxns); foreach (var txn in unmatchedTxns) { this.toDoList.Add( @@ -307,11 +304,14 @@ private static string ExtractNarrative(Transaction t) peices.Add("[No Description]"); } } - - if (peices.Count == 1) return peices[0]; + + if (peices.Count == 1) + { + return peices[0]; + } var builder = new StringBuilder(); - for (int index = 0; index < peices.Count; index++) + for (var index = 0; index < peices.Count; index++) { var firstOne = index == 0; if (firstOne) @@ -340,12 +340,9 @@ private static IEnumerable FindAutoMatchingTransactions(Ledge return new List(); } - if (includeMatchedTransactions) - { - return ledgerEntry.Transactions.Where(t => !string.IsNullOrWhiteSpace(t.AutoMatchingReference)); - } - - return ledgerEntry.Transactions.Where(t => + return includeMatchedTransactions + ? ledgerEntry.Transactions.Where(t => !string.IsNullOrWhiteSpace(t.AutoMatchingReference)) + : ledgerEntry.Transactions.Where(t => t.AutoMatchingReference.IsSomething() && !t.AutoMatchingReference.StartsWith(MatchedPrefix, StringComparison.Ordinal)); } @@ -409,28 +406,25 @@ private static IEnumerable IncludeStatementTransactions(Ledge return new List(); } - List transactions = filteredStatementTransactions.Where(t => t.BudgetBucket == newEntry.LedgerBucket.BudgetBucket).ToList(); + var transactions = filteredStatementTransactions.Where(t => t.BudgetBucket == newEntry.LedgerBucket.BudgetBucket).ToList(); if (transactions.Any()) { IEnumerable newLedgerTransactions = transactions.Select( t => { - if (t.Amount < 0) - { - return new CreditLedgerTransaction(t.Id) + return t.Amount < 0 + ? new CreditLedgerTransaction(t.Id) + { + Amount = t.Amount, + Narrative = ExtractNarrative(t), + Date = t.Date + } + : new CreditLedgerTransaction(t.Id) { Amount = t.Amount, Narrative = ExtractNarrative(t), Date = t.Date }; - } - - return new CreditLedgerTransaction(t.Id) - { - Amount = t.Amount, - Narrative = ExtractNarrative(t), - Date = t.Date - }; }); return newLedgerTransactions.ToList(); @@ -438,4 +432,4 @@ private static IEnumerable IncludeStatementTransactions(Ledge return new List(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistency.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistency.cs index 851a7c7c..2a290732 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistency.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistency.cs @@ -11,4 +11,4 @@ public IDisposable EnsureConsistency(LedgerBook book) return new ReconciliationConsistencyChecker(book); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistencyChecker.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistencyChecker.cs index d1f24c81..8c8db507 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistencyChecker.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationConsistencyChecker.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using NotNull = JetBrains.Annotations.NotNullAttribute; @@ -43,4 +43,4 @@ public void Dispose() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationCreationManager.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationCreationManager.cs index 2d77dcc2..423277cd 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationCreationManager.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationCreationManager.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -170,7 +170,7 @@ public void ValidateAgainstOrphanedAutoMatchingTransactions(LedgerBook ledgerBoo return; } - List unmatchedTxns = lastLine.Entries + var unmatchedTxns = lastLine.Entries .SelectMany(e => e.Transactions) .Where( t => @@ -184,10 +184,10 @@ public void ValidateAgainstOrphanedAutoMatchingTransactions(LedgerBook ledgerBoo return; } - List statementSubSet = statement.AllTransactions.Where(t => t.Date >= lastLine.Date).ToList(); + var statementSubSet = statement.AllTransactions.Where(t => t.Date >= lastLine.Date).ToList(); foreach (var ledgerTransaction in unmatchedTxns) { - IEnumerable statementTxns = ReconciliationBuilder.TransactionsToAutoMatch(statementSubSet, + var statementTxns = ReconciliationBuilder.TransactionsToAutoMatch(statementSubSet, ledgerTransaction.AutoMatchingReference); if (statementTxns.None()) { @@ -255,7 +255,7 @@ private void PerformBankTransfer(LedgerBook ledgerBook, TransferFundsCommand tra if (!(transferDetails.FromLedger.BudgetBucket is SurplusBucket)) { var ledgerEntry = ledgerEntryLine.Entries.Single(e => e.LedgerBucket == transferDetails.FromLedger); - List replacementTxns = ledgerEntry.Transactions.ToList(); + var replacementTxns = ledgerEntry.Transactions.ToList(); replacementTxns.Add(sourceTransaction); ledgerEntry.SetTransactionsForReconciliation(replacementTxns); ledgerEntry.RecalculateClosingBalance(ledgerBook); @@ -265,7 +265,7 @@ private void PerformBankTransfer(LedgerBook ledgerBook, TransferFundsCommand tra if (!(transferDetails.ToLedger.BudgetBucket is SurplusBucket)) { var ledgerEntry = ledgerEntryLine.Entries.Single(e => e.LedgerBucket == transferDetails.ToLedger); - List replacementTxns = ledgerEntry.Transactions.ToList(); + var replacementTxns = ledgerEntry.Transactions.ToList(); replacementTxns.Add(destinationTransaction); ledgerEntry.SetTransactionsForReconciliation(replacementTxns); ledgerEntry.RecalculateClosingBalance(ledgerBook); @@ -284,12 +284,12 @@ private void PreReconciliationValidation(LedgerBook ledgerBook, DateTime reconci { throw new InvalidOperationException("No budget can be found with an effective date before " + reconciliationDate); } - + if (!budget.Validate(messages)) { throw new InvalidOperationException($"Current budget ({budget.Name}) is in an invalid state. Cannot add new reconciliation.\n" + messages); } - + var startDate = ReconciliationBuilder.CalculateBeginDateForReconciliationPeriod(ledgerBook, reconciliationDate, budget.BudgetCycle); ValidateDates(ledgerBook, startDate, reconciliationDate, statement, budget.BudgetCycle); @@ -340,7 +340,7 @@ private void ValidateAgainstUncategorisedTransactions(DateTime startDate, DateTi t.BudgetBucket is null || (t.BudgetBucket is not null && string.IsNullOrWhiteSpace(t.BudgetBucket.Code)))) { - IEnumerable uncategorised = + var uncategorised = statement.AllTransactions.Where( t => t.BudgetBucket is null || @@ -399,7 +399,7 @@ private static void ValidateDates(LedgerBook ledgerBook, DateTime startDate, Dat } break; - + case BudgetCycle.Fortnightly: if (reconciliationDate.Subtract(previousEntry.Date).Days != 14) { @@ -417,4 +417,4 @@ private static void ValidateDates(LedgerBook ledgerBook, DateTime startDate, Dat }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationResult.cs b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationResult.cs index e7a78c61..1e455ed4 100644 --- a/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationResult.cs +++ b/BudgetAnalyser.Engine/Ledger/Reconciliation/ReconciliationResult.cs @@ -17,4 +17,4 @@ public class ReconciliationResult /// public IEnumerable Tasks { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/SavedUpForLedger.cs b/BudgetAnalyser.Engine/Ledger/SavedUpForLedger.cs index b0f9d202..5c15f172 100644 --- a/BudgetAnalyser.Engine/Ledger/SavedUpForLedger.cs +++ b/BudgetAnalyser.Engine/Ledger/SavedUpForLedger.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using BudgetAnalyser.Engine.Budget; @@ -74,4 +74,4 @@ protected override void ValidateBucketSet(BudgetBucket bucket) throw new NotSupportedException("Invalid budget bucket used, only Saved-Up-For-Expense-Buckets can be used with an instance of Saved-Up-For-Ledger."); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/SpentPerPeriodLedger.cs b/BudgetAnalyser.Engine/Ledger/SpentPerPeriodLedger.cs index a631b8a0..a2f4db7c 100644 --- a/BudgetAnalyser.Engine/Ledger/SpentPerPeriodLedger.cs +++ b/BudgetAnalyser.Engine/Ledger/SpentPerPeriodLedger.cs @@ -52,12 +52,9 @@ public override bool ApplyReconciliationBehaviour(IList trans // Remove-excess if (closingBalance > openingBalance || closingBalance > budgetTransaction.Amount) { - if (openingBalance > budgetTransaction.Amount) - { - return transactions.AddIfSomething(RemoveExcessToOpeningBalance(closingBalance, reconciliationDate, openingBalance)); - } - - return transactions.AddIfSomething(RemoveExcessToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount)); + return openingBalance > budgetTransaction.Amount + ? transactions.AddIfSomething(RemoveExcessToOpeningBalance(closingBalance, reconciliationDate, openingBalance)) + : transactions.AddIfSomething(RemoveExcessToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount)); } return false; @@ -84,72 +81,62 @@ protected override void ValidateBucketSet(BudgetBucket bucket) private static LedgerTransaction RemoveExcessToBudgetAmount(decimal closingBalance, DateTime reconciliationDate, decimal budgetAmount) { - if (closingBalance - budgetAmount == 0) - { - return null; - } - return new CreditLedgerTransaction - { - Amount = -(closingBalance - budgetAmount), - Date = reconciliationDate, - Narrative = RemoveExcessText - }; + return closingBalance - budgetAmount == 0 + ? null + : (LedgerTransaction)new CreditLedgerTransaction + { + Amount = -(closingBalance - budgetAmount), + Date = reconciliationDate, + Narrative = RemoveExcessText + }; } private static LedgerTransaction RemoveExcessToOpeningBalance(decimal closingBalance, DateTime reconciliationDate, decimal openingBalance) { - if (closingBalance - openingBalance == 0) - { - return null; - } - return new CreditLedgerTransaction - { - Amount = -(closingBalance - openingBalance), - Date = reconciliationDate, - Narrative = RemoveExcessText - }; + return closingBalance - openingBalance == 0 + ? null + : (LedgerTransaction)new CreditLedgerTransaction + { + Amount = -(closingBalance - openingBalance), + Date = reconciliationDate, + Narrative = RemoveExcessText + }; } private static LedgerTransaction SupplementToBudgetAmount(decimal closingBalance, DateTime reconciliationDate, decimal budgetAmount) { - if (budgetAmount - closingBalance == 0) - { - return null; - } - return new CreditLedgerTransaction - { - Amount = budgetAmount - closingBalance, - Date = reconciliationDate, - Narrative = SupplementLessThanBudgetText - }; + return budgetAmount - closingBalance == 0 + ? null + : (LedgerTransaction)new CreditLedgerTransaction + { + Amount = budgetAmount - closingBalance, + Date = reconciliationDate, + Narrative = SupplementLessThanBudgetText + }; } private static LedgerTransaction SupplementToOpeningBalance(decimal closingBalance, DateTime reconciliationDate, decimal openingBalance) { - if (openingBalance - closingBalance == 0) - { - return null; - } - return new CreditLedgerTransaction - { - Amount = openingBalance - closingBalance, - Date = reconciliationDate, - Narrative = SupplementLessThanOpeningBalance - }; + return openingBalance - closingBalance == 0 + ? null + : (LedgerTransaction)new CreditLedgerTransaction + { + Amount = openingBalance - closingBalance, + Date = reconciliationDate, + Narrative = SupplementLessThanOpeningBalance + }; } private static CreditLedgerTransaction SupplementToZero(decimal closingBalance, DateTime reconciliationDate) { - if (closingBalance == 0) - { - return null; - } - return new CreditLedgerTransaction - { - Amount = 0 - closingBalance, - Date = reconciliationDate, - Narrative = RemoveExcessNoBudgetAmountText - }; + return closingBalance == 0 + ? null + : new CreditLedgerTransaction + { + Amount = 0 - closingBalance, + Date = reconciliationDate, + Narrative = RemoveExcessNoBudgetAmountText + }; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/SurplusLedger.cs b/BudgetAnalyser.Engine/Ledger/SurplusLedger.cs index 39634993..d09781e4 100644 --- a/BudgetAnalyser.Engine/Ledger/SurplusLedger.cs +++ b/BudgetAnalyser.Engine/Ledger/SurplusLedger.cs @@ -46,4 +46,4 @@ protected override void ValidateBucketSet(BudgetBucket bucket) "Invalid budget bucket used, only the Surplus bucket can be used with an instance of Surplus-Ledger."); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/ToDoCollection.cs b/BudgetAnalyser.Engine/Ledger/ToDoCollection.cs index 485c8af6..b4df6f6d 100644 --- a/BudgetAnalyser.Engine/Ledger/ToDoCollection.cs +++ b/BudgetAnalyser.Engine/Ledger/ToDoCollection.cs @@ -22,12 +22,7 @@ public class ToDoCollection : ObservableCollection throw new ArgumentNullException(nameof(task)); } - if (task.CanDelete) - { - return base.Remove(task); - } - - return false; + return task.CanDelete ? base.Remove(task) : false; } /// @@ -69,4 +64,4 @@ protected override void RemoveItem(int index) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/ToDoTaskType.cs b/BudgetAnalyser.Engine/Ledger/ToDoTaskType.cs index afa94020..19b629ed 100644 --- a/BudgetAnalyser.Engine/Ledger/ToDoTaskType.cs +++ b/BudgetAnalyser.Engine/Ledger/ToDoTaskType.cs @@ -1,8 +1,8 @@ -namespace BudgetAnalyser.Engine.Ledger +namespace BudgetAnalyser.Engine.Ledger { internal enum ToDoTaskType { Other = 0, TransferBudgetedAmount } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/TodoTask.cs b/BudgetAnalyser.Engine/Ledger/TodoTask.cs index 2bcd96eb..fb570415 100644 --- a/BudgetAnalyser.Engine/Ledger/TodoTask.cs +++ b/BudgetAnalyser.Engine/Ledger/TodoTask.cs @@ -1,4 +1,4 @@ -namespace BudgetAnalyser.Engine.Ledger +namespace BudgetAnalyser.Engine.Ledger { /// /// A task item for use with the . @@ -37,4 +37,4 @@ public ToDoTask(string description, bool systemGenerated = false, bool canDelete /// public bool SystemGenerated { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/TransferFundsCommand.cs b/BudgetAnalyser.Engine/Ledger/TransferFundsCommand.cs index 0d5e56ec..1b6c6086 100644 --- a/BudgetAnalyser.Engine/Ledger/TransferFundsCommand.cs +++ b/BudgetAnalyser.Engine/Ledger/TransferFundsCommand.cs @@ -35,7 +35,11 @@ public string AutoMatchingReference get => this.doNotUseAutoMatchingReference; set { - if (value == this.doNotUseAutoMatchingReference) return; + if (value == this.doNotUseAutoMatchingReference) + { + return; + } + this.doNotUseAutoMatchingReference = value; OnPropertyChanged(); } @@ -51,7 +55,11 @@ public bool BankTransferRequired get => this.doNotUseBankTransferRequired; set { - if (value == this.doNotUseBankTransferRequired) return; + if (value == this.doNotUseBankTransferRequired) + { + return; + } + this.doNotUseBankTransferRequired = value; OnPropertyChanged(); if (BankTransferRequired && AutoMatchingReference.IsNothing()) @@ -69,7 +77,11 @@ public LedgerBucket? FromLedger get => this.doNotUseFromLedger; set { - if (Equals(value, this.doNotUseFromLedger)) return; + if (Equals(value, this.doNotUseFromLedger)) + { + return; + } + this.doNotUseFromLedger = value; OnPropertyChanged(); SetBankTransferRequired(); @@ -89,7 +101,11 @@ public string Narrative get => this.doNotUseNarrative; set { - if (value == this.doNotUseNarrative) return; + if (value == this.doNotUseNarrative) + { + return; + } + this.doNotUseNarrative = value; OnPropertyChanged(); if (IsValid != this.isValid) @@ -108,7 +124,11 @@ public LedgerBucket? ToLedger get => this.doNotUseToLedger; set { - if (Equals(value, this.doNotUseToLedger)) return; + if (Equals(value, this.doNotUseToLedger)) + { + return; + } + this.doNotUseToLedger = value; OnPropertyChanged(); SetBankTransferRequired(); @@ -128,7 +148,11 @@ public decimal TransferAmount get => this.doNotUseTransferAmount; set { - if (value == this.doNotUseTransferAmount) return; + if (value == this.doNotUseTransferAmount) + { + return; + } + this.doNotUseTransferAmount = value; OnPropertyChanged(); if (IsValid != this.isValid) @@ -190,4 +214,4 @@ private void SetBankTransferRequired() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/TransferTask.cs b/BudgetAnalyser.Engine/Ledger/TransferTask.cs index 037ddbf3..0d993abf 100644 --- a/BudgetAnalyser.Engine/Ledger/TransferTask.cs +++ b/BudgetAnalyser.Engine/Ledger/TransferTask.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.BankAccount; +using BudgetAnalyser.Engine.BankAccount; namespace BudgetAnalyser.Engine.Ledger { @@ -41,4 +41,4 @@ public TransferTask(string description, bool systemGenerated = false, bool canDe /// public Account SourceAccount { get; internal set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Ledger/XamlOnDiskLedgerBookRepository.cs b/BudgetAnalyser.Engine/Ledger/XamlOnDiskLedgerBookRepository.cs index f81a54a1..dd799c1a 100644 --- a/BudgetAnalyser.Engine/Ledger/XamlOnDiskLedgerBookRepository.cs +++ b/BudgetAnalyser.Engine/Ledger/XamlOnDiskLedgerBookRepository.cs @@ -1,9 +1,9 @@ using System.Globalization; using System.Text; -using Portable.Xaml; using BudgetAnalyser.Engine.Ledger.Data; using BudgetAnalyser.Engine.Statement; using JetBrains.Annotations; +using Portable.Xaml; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.Ledger @@ -163,12 +163,7 @@ protected virtual async Task SaveDtoToDiskAsync([NotNull] LedgerBookDto dataEnti /// protected virtual string Serialise(LedgerBookDto dataEntity) { - if (dataEntity is null) - { - throw new ArgumentNullException(nameof(dataEntity)); - } - - return XamlServices.Save(dataEntity); + return dataEntity is null ? throw new ArgumentNullException(nameof(dataEntity)) : XamlServices.Save(dataEntity); } private static double CalculateChecksum(LedgerBook dataEntity) @@ -176,9 +171,9 @@ private static double CalculateChecksum(LedgerBook dataEntity) // ReSharper disable once EnumerableSumInExplicitUncheckedContext - Used to calculate a checksum and revolving (overflowing) integers are ok here. return dataEntity.Reconciliations.Sum( l => - (double) l.LedgerBalance - + l.BankBalanceAdjustments.Sum(b => (double) b.Amount) - + l.Entries.Sum(e => (double) e.Balance)); + (double)l.LedgerBalance + + l.BankBalanceAdjustments.Sum(b => (double)b.Amount) + + l.Entries.Sum(e => (double)e.Balance)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ListExtension.cs b/BudgetAnalyser.Engine/ListExtension.cs index 63210b78..610bd33d 100644 --- a/BudgetAnalyser.Engine/ListExtension.cs +++ b/BudgetAnalyser.Engine/ListExtension.cs @@ -17,7 +17,10 @@ public static class ListExtension /// The new element to add if its not null. public static bool AddIfSomething([NotNull] this IList instance, T newElement) where T : class { - if (instance is null) throw new ArgumentNullException(nameof(instance)); + if (instance is null) + { + throw new ArgumentNullException(nameof(instance)); + } if (newElement is not null) { @@ -28,4 +31,4 @@ public static bool AddIfSomething([NotNull] this IList instance, T newElem return false; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/MainApplicationState.cs b/BudgetAnalyser.Engine/MainApplicationState.cs index b6a5273f..cc55f42a 100644 --- a/BudgetAnalyser.Engine/MainApplicationState.cs +++ b/BudgetAnalyser.Engine/MainApplicationState.cs @@ -19,4 +19,4 @@ public class MainApplicationState : IPersistentApplicationStateObject /// public int LoadSequence => 1; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/CriteriaT.cs b/BudgetAnalyser.Engine/Matching/CriteriaT.cs index 11895ac4..62e3b27b 100644 --- a/BudgetAnalyser.Engine/Matching/CriteriaT.cs +++ b/BudgetAnalyser.Engine/Matching/CriteriaT.cs @@ -29,7 +29,7 @@ public abstract class Criteria : INotifyPropertyChanged /// public bool Applicable { - get { return this.doNotUseApplicable; } + get => this.doNotUseApplicable; set { if (value == this.doNotUseApplicable) @@ -46,7 +46,7 @@ public bool Applicable /// public T Value { - get { return this.doNotUseValue; } + get => this.doNotUseValue; set { if (Equals(value, this.doNotUseValue)) @@ -106,12 +106,7 @@ public class DecimalCriteria : Criteria /// public override bool IsEqualButNotBlank(decimal? operand2) { - if (Value == default(decimal)) - { - return false; - } - - return Value == operand2; + return Value == default(decimal) ? false : Value == operand2; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.cs b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.cs index 4d94ee88..cf96230a 100644 --- a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.cs +++ b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.cs @@ -5,15 +5,9 @@ namespace BudgetAnalyser.Engine.Matching.Data { [AutoRegisterWithIoC] - internal partial class Mapper_MatchingRuleDto_MatchingRule + internal partial class MapperMatchingRuleDto2MatchingRule(IBudgetBucketRepository bucketRepo) { - private readonly IBudgetBucketRepository bucketRepo; - - public Mapper_MatchingRuleDto_MatchingRule([NotNull] IBudgetBucketRepository bucketRepo) - { - if (bucketRepo is null) throw new ArgumentNullException(nameof(bucketRepo)); - this.bucketRepo = bucketRepo; - } + private readonly IBudgetBucketRepository bucketRepo = bucketRepo ?? throw new ArgumentNullException(nameof(bucketRepo)); // ReSharper disable once RedundantAssignment partial void ModelFactory(MatchingRuleDto dto, ref MatchingRule model) @@ -31,4 +25,4 @@ partial void ToModelPostprocessing(MatchingRuleDto dto, ref MatchingRule model) model.BucketCode = dto.BucketCode; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.generated.cs b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.generated.cs index e3f106b8..3a3d5c76 100644 --- a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.generated.cs +++ b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDomainToDataMapper.generated.cs @@ -11,7 +11,7 @@ namespace BudgetAnalyser.Engine.Matching.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 2:10:07 AM UTC")] - internal partial class Mapper_MatchingRuleDto_MatchingRule : IDtoMapper + internal partial class MapperMatchingRuleDto2MatchingRule : IDtoMapper { public virtual MatchingRule ToModel(MatchingRuleDto dto) diff --git a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDto.cs b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDto.cs index 17115ca3..27709805 100644 --- a/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDto.cs +++ b/BudgetAnalyser.Engine/Matching/Data/MatchingRuleDto.cs @@ -75,4 +75,4 @@ public MatchingRuleDto() /// public string TransactionType { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/Data/SingleUseMatchingRuleDto.cs b/BudgetAnalyser.Engine/Matching/Data/SingleUseMatchingRuleDto.cs index 4d21819b..2825d2e9 100644 --- a/BudgetAnalyser.Engine/Matching/Data/SingleUseMatchingRuleDto.cs +++ b/BudgetAnalyser.Engine/Matching/Data/SingleUseMatchingRuleDto.cs @@ -8,4 +8,4 @@ public class SingleUseMatchingRuleDto : MatchingRuleDto { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/IMatchMaker.cs b/BudgetAnalyser.Engine/Matching/IMatchMaker.cs index 4277bbf7..ef7de36c 100644 --- a/BudgetAnalyser.Engine/Matching/IMatchMaker.cs +++ b/BudgetAnalyser.Engine/Matching/IMatchMaker.cs @@ -7,4 +7,4 @@ internal interface IMatchmaker { bool Match(IEnumerable transactions, IEnumerable rules); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/IMatchingRuleFactory.cs b/BudgetAnalyser.Engine/Matching/IMatchingRuleFactory.cs index 774fe69f..7f7c3efd 100644 --- a/BudgetAnalyser.Engine/Matching/IMatchingRuleFactory.cs +++ b/BudgetAnalyser.Engine/Matching/IMatchingRuleFactory.cs @@ -23,4 +23,4 @@ SingleUseMatchingRule CreateNewSingleUseRule( MatchingRule CreateRuleForPersistence([NotNull] string budgetBucketCode); SingleUseMatchingRule CreateSingleUseRuleForPersistence([NotNull] string budgetBucketCode); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/IMatchingRuleRepository.cs b/BudgetAnalyser.Engine/Matching/IMatchingRuleRepository.cs index 1d6f523f..a7eb4839 100644 --- a/BudgetAnalyser.Engine/Matching/IMatchingRuleRepository.cs +++ b/BudgetAnalyser.Engine/Matching/IMatchingRuleRepository.cs @@ -48,4 +48,4 @@ public interface IMatchingRuleRepository /// Will be thrown if any arguments are null. Task SaveAsync([NotNull] IEnumerable rules, [NotNull] string storageKey, bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/MatchMaker.cs b/BudgetAnalyser.Engine/Matching/MatchMaker.cs index 0bc11724..478ef4a8 100644 --- a/BudgetAnalyser.Engine/Matching/MatchMaker.cs +++ b/BudgetAnalyser.Engine/Matching/MatchMaker.cs @@ -110,4 +110,4 @@ private bool MatchToRules(IEnumerable rules, Transaction transacti return matchesOccured; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/MatchingRule.cs b/BudgetAnalyser.Engine/Matching/MatchingRule.cs index 707a0880..319ae630 100644 --- a/BudgetAnalyser.Engine/Matching/MatchingRule.cs +++ b/BudgetAnalyser.Engine/Matching/MatchingRule.cs @@ -89,7 +89,7 @@ public bool And /// public BudgetBucket Bucket { - get { return this.bucketRepository.GetByCode(BucketCode); } + get => this.bucketRepository.GetByCode(BucketCode); [UsedImplicitly] private set @@ -230,30 +230,25 @@ public string TransactionType /// public bool Equals(MatchingRule other) { - if (ReferenceEquals(null, other)) + if (other is null) { return false; } - if (ReferenceEquals(this, other)) - { - return true; - } - - return RuleId.Equals(other.RuleId); + return ReferenceEquals(this, other) ? true : RuleId.Equals(other.RuleId); } /// - /// Determines whether the specified , is equal to this instance. + /// Determines whether the specified , is equal to this instance. /// Delegates to . /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -261,11 +256,7 @@ public override bool Equals(object obj) { return true; } - if (obj.GetType() != GetType()) - { - return false; - } - return Equals((MatchingRule) obj); + return obj.GetType() != GetType() ? false : Equals((MatchingRule)obj); } /// @@ -380,10 +371,10 @@ public bool Match([NotNull] Transaction transaction) } /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// public override string ToString() { @@ -411,4 +402,4 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/MatchingRuleFactory.cs b/BudgetAnalyser.Engine/Matching/MatchingRuleFactory.cs index bf54be75..693fce53 100644 --- a/BudgetAnalyser.Engine/Matching/MatchingRuleFactory.cs +++ b/BudgetAnalyser.Engine/Matching/MatchingRuleFactory.cs @@ -91,4 +91,4 @@ private static T CreateAnyNewRule(Func ruleCtor, string bucketCode return newRule; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/RulesGroupedByBucket.cs b/BudgetAnalyser.Engine/Matching/RulesGroupedByBucket.cs index bef35b2b..a530c9b3 100644 --- a/BudgetAnalyser.Engine/Matching/RulesGroupedByBucket.cs +++ b/BudgetAnalyser.Engine/Matching/RulesGroupedByBucket.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; @@ -52,4 +52,4 @@ public RulesGroupedByBucket([NotNull] BudgetBucket bucket, [NotNull] IEnumerable /// public int RulesCount => Rules.Count(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/SimilarMatchedRule.cs b/BudgetAnalyser.Engine/Matching/SimilarMatchedRule.cs index 699cf5e3..19253bb6 100644 --- a/BudgetAnalyser.Engine/Matching/SimilarMatchedRule.cs +++ b/BudgetAnalyser.Engine/Matching/SimilarMatchedRule.cs @@ -45,7 +45,7 @@ public SimilarMatchedRule([NotNull] IBudgetBucketRepository bucketRepository, [N /// public bool AmountMatched { - get { return this.doNotUseAmountMatched; } + get => this.doNotUseAmountMatched; set { if (value == this.doNotUseAmountMatched) @@ -62,7 +62,7 @@ public bool AmountMatched /// public bool DescriptionMatched { - get { return this.doNotUseDescriptionMatched; } + get => this.doNotUseDescriptionMatched; set { if (value == this.doNotUseDescriptionMatched) @@ -79,7 +79,7 @@ public bool DescriptionMatched /// public bool Reference1Matched { - get { return this.doNotUseReference1Matched; } + get => this.doNotUseReference1Matched; set { if (value == this.doNotUseReference1Matched) @@ -96,7 +96,7 @@ public bool Reference1Matched /// public bool Reference2Matched { - get { return this.doNotUseReference2Matched; } + get => this.doNotUseReference2Matched; set { if (value == this.doNotUseReference2Matched) @@ -113,7 +113,7 @@ public bool Reference2Matched /// public bool Reference3Matched { - get { return this.doNotUseReference3Matched; } + get => this.doNotUseReference3Matched; set { if (value == this.doNotUseReference3Matched) @@ -128,25 +128,19 @@ public bool Reference3Matched /// /// Gets the sort order. /// - public int SortOrder - { - get - { - return (AmountMatched ? 100 : 0) + public int SortOrder => (AmountMatched ? 100 : 0) + (DescriptionMatched ? 90 : 0) + (Reference1Matched ? 70 : 0) + (Reference2Matched ? 60 : 0) + (Reference3Matched ? 50 : 0) + (TransactionTypeMatched ? 10 : 0); - } - } /// /// Gets or sets a value indicating whether the transaction type property was used to match. /// public bool TransactionTypeMatched { - get { return this.doNotUseTransactionTypeMatched; } + get => this.doNotUseTransactionTypeMatched; set { if (value == this.doNotUseTransactionTypeMatched) @@ -158,4 +152,4 @@ public bool TransactionTypeMatched } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/SingleUseMatchingRule.cs b/BudgetAnalyser.Engine/Matching/SingleUseMatchingRule.cs index 3c47a051..07a7957d 100644 --- a/BudgetAnalyser.Engine/Matching/SingleUseMatchingRule.cs +++ b/BudgetAnalyser.Engine/Matching/SingleUseMatchingRule.cs @@ -18,4 +18,4 @@ public SingleUseMatchingRule([NotNull] IBudgetBucketRepository bucketRepository) Hidden = true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Matching/XamlOnDiskMatchingRuleRepository.cs b/BudgetAnalyser.Engine/Matching/XamlOnDiskMatchingRuleRepository.cs index 052b5d00..9e6cac77 100644 --- a/BudgetAnalyser.Engine/Matching/XamlOnDiskMatchingRuleRepository.cs +++ b/BudgetAnalyser.Engine/Matching/XamlOnDiskMatchingRuleRepository.cs @@ -1,7 +1,7 @@ using System.Diagnostics.CodeAnalysis; -using Portable.Xaml; using BudgetAnalyser.Engine.Matching.Data; using JetBrains.Annotations; +using Portable.Xaml; using Rees.TangyFruitMapper; using NotNull = JetBrains.Annotations.NotNullAttribute; @@ -25,8 +25,15 @@ public XamlOnDiskMatchingRuleRepository([NotNull] IDtoMapper> LoadAsync(string storageKey, bool i throw new DataFormatException("Deserialised Matching-Rules are not of type List"); } - IEnumerable realModel = dataEntities.Select(d => this.mapper.ToModel(d)); + var realModel = dataEntities.Select(d => this.mapper.ToModel(d)); return Validate(realModel.ToList()); } @@ -94,7 +101,7 @@ public async Task SaveAsync(IEnumerable rules, string storageKey, } IEnumerable model = Validate(rules.ToList()); - IEnumerable dataEntities = model.Select(r => this.mapper.ToDto(r)); + var dataEntities = model.Select(r => this.mapper.ToDto(r)); await SaveToDiskAsync(storageKey, dataEntities, isEncrypted); } @@ -119,12 +126,7 @@ protected virtual async Task SaveToDiskAsync(string fileName, IEnumerable dataEntity) { - if (dataEntity is null) - { - throw new ArgumentNullException(nameof(dataEntity)); - } - - return XamlServices.Save(dataEntity.ToList()); + return dataEntity is null ? throw new ArgumentNullException(nameof(dataEntity)) : XamlServices.Save(dataEntity.ToList()); } private IList Validate(IList model) @@ -165,4 +167,4 @@ private IList Validate(IList model) return model; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/IMobileDataExporter.cs b/BudgetAnalyser.Engine/Mobile/IMobileDataExporter.cs index aa09a7a3..b768503c 100644 --- a/BudgetAnalyser.Engine/Mobile/IMobileDataExporter.cs +++ b/BudgetAnalyser.Engine/Mobile/IMobileDataExporter.cs @@ -26,4 +26,4 @@ public interface IMobileDataExporter /// string Serialise(SummarisedLedgerMobileData dataExport); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/IMobileDataUploader.cs b/BudgetAnalyser.Engine/Mobile/IMobileDataUploader.cs index 5197651a..93a32afb 100644 --- a/BudgetAnalyser.Engine/Mobile/IMobileDataUploader.cs +++ b/BudgetAnalyser.Engine/Mobile/IMobileDataUploader.cs @@ -19,4 +19,4 @@ public interface IMobileDataUploader /// Will be thrown for any other kind of communications failure. Task UploadDataFileAsync(string data, string storageKeyId, string storageSecret, string region); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/MobileDataExporter.cs b/BudgetAnalyser.Engine/Mobile/MobileDataExporter.cs index c6004337..3f5d1a05 100644 --- a/BudgetAnalyser.Engine/Mobile/MobileDataExporter.cs +++ b/BudgetAnalyser.Engine/Mobile/MobileDataExporter.cs @@ -73,7 +73,7 @@ public SummarisedLedgerMobileData CreateExportObject( var ledgerList = new List(); var ledgerLine = this.calculator.LocateApplicableLedgerLine(ledgerBook, filter.BeginDate.Value, filter.EndDate.Value); - IDictionary currentBalances = this.calculator.CalculateCurrentPeriodLedgerBalances(ledgerLine, filter, transactions); + var currentBalances = this.calculator.CalculateCurrentPeriodLedgerBalances(ledgerLine, filter, transactions); foreach (var entry in latestRecon.Entries) { ledgerList.Add(new SummarisedLedgerBucket @@ -128,4 +128,4 @@ private async Task GetFileName() return Path.Combine(await this.environmentFolders.LogFolder(), "MobileDataExport.json"); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/MobileStorageSettings.cs b/BudgetAnalyser.Engine/Mobile/MobileStorageSettings.cs index d1375a18..ee1c9567 100644 --- a/BudgetAnalyser.Engine/Mobile/MobileStorageSettings.cs +++ b/BudgetAnalyser.Engine/Mobile/MobileStorageSettings.cs @@ -20,4 +20,4 @@ public class MobileStorageSettings /// public string AmazonS3Region { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/S3MobileDataUploader.cs b/BudgetAnalyser.Engine/Mobile/S3MobileDataUploader.cs index 4136e47a..94d67f4d 100644 --- a/BudgetAnalyser.Engine/Mobile/S3MobileDataUploader.cs +++ b/BudgetAnalyser.Engine/Mobile/S3MobileDataUploader.cs @@ -54,4 +54,4 @@ public async Task UploadDataFileAsync(string data, string storageKeyId, string s } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/SummarisedLedgerBucket.cs b/BudgetAnalyser.Engine/Mobile/SummarisedLedgerBucket.cs index 307a9f48..a0555ba8 100644 --- a/BudgetAnalyser.Engine/Mobile/SummarisedLedgerBucket.cs +++ b/BudgetAnalyser.Engine/Mobile/SummarisedLedgerBucket.cs @@ -40,4 +40,4 @@ public class SummarisedLedgerBucket /// public decimal RemainingBalance { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Mobile/SummarisedLedgerMobileData.cs b/BudgetAnalyser.Engine/Mobile/SummarisedLedgerMobileData.cs index dbb08e00..10e36096 100644 --- a/BudgetAnalyser.Engine/Mobile/SummarisedLedgerMobileData.cs +++ b/BudgetAnalyser.Engine/Mobile/SummarisedLedgerMobileData.cs @@ -40,4 +40,4 @@ public SummarisedLedgerMobileData() /// public string Title { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/NewZealandPublicHolidays.cs b/BudgetAnalyser.Engine/NewZealandPublicHolidays.cs index 71bf2663..c50eb10f 100644 --- a/BudgetAnalyser.Engine/NewZealandPublicHolidays.cs +++ b/BudgetAnalyser.Engine/NewZealandPublicHolidays.cs @@ -128,10 +128,10 @@ public override DateTime CalculateDate(DateTime start, DateTime end) var goldenNumber = year % 19; var century = year / 100; - var h = (century - century / 4 - (8 * century + 13) / 25 + 19 * goldenNumber + 15) % 30; - var i = h - h / 28 * (1 - h / 28 * (29 / (h + 1)) * ((21 - goldenNumber) / 11)); + var h = (century - (century / 4) - (((8 * century) + 13) / 25) + (19 * goldenNumber) + 15) % 30; + var i = h - (h / 28 * (1 - (h / 28 * (29 / (h + 1)) * ((21 - goldenNumber) / 11)))); - var day = i - (year + year / 4 + i + 2 - century + century / 4) % 7 + 28; + var day = i - ((year + (year / 4) + i + 2 - century + (century / 4)) % 7) + 28; var month = 3; if (day > 31) @@ -201,13 +201,10 @@ public override DateTime CalculateDate(DateTime start, DateTime end) } while (proposed.DayOfWeek != DayOfWeek.Monday); } - if (proposed < DateTime.MinValue.AddMonths(1)) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, - "Cannot find a suitable date between {0} and {1}", start, end)); - } - - return proposed; + return proposed < DateTime.MinValue.AddMonths(1) + ? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, + "Cannot find a suitable date between {0} and {1}", start, end)) + : proposed; } } @@ -260,4 +257,4 @@ private DateTime ProposeDate(int year) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/NullLogger.cs b/BudgetAnalyser.Engine/NullLogger.cs index 7f2704db..72c0e4b4 100644 --- a/BudgetAnalyser.Engine/NullLogger.cs +++ b/BudgetAnalyser.Engine/NullLogger.cs @@ -52,4 +52,4 @@ public void LogWarning(Func logEntryBuilder) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/ApplicationDatabase.cs b/BudgetAnalyser.Engine/Persistence/ApplicationDatabase.cs index 21a8eda0..864593e0 100644 --- a/BudgetAnalyser.Engine/Persistence/ApplicationDatabase.cs +++ b/BudgetAnalyser.Engine/Persistence/ApplicationDatabase.cs @@ -93,4 +93,4 @@ public virtual string FullPath(string fileName) return Path.Combine(StoragePath, fileName); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.cs b/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.cs index 5fbac83d..c4747830 100644 --- a/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.cs +++ b/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.cs @@ -3,13 +3,13 @@ namespace BudgetAnalyser.Engine.Persistence { [AutoRegisterWithIoC] - internal partial class Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase + internal partial class MapperBudgetAnalyserStorageRoot2ApplicationDatabase { partial void ToDtoPostprocessing(ref BudgetAnalyserStorageRoot dto, ApplicationDatabase model) { dto.BudgetCollectionRootDto = new StorageBranch { Source = model.BudgetCollectionStorageKey }; dto.LedgerBookRootDto = new StorageBranch { Source = model.LedgerBookStorageKey }; - var mapper = new Mapper_ListToDoTaskDto_ToDoCollection(); + var mapper = new MapperListToDoTaskDto2ToDoCollection(); dto.LedgerReconciliationToDoCollection = mapper.ToDto(model.LedgerReconciliationToDoCollection); dto.MatchingRulesCollectionRootDto = new StorageBranch { Source = model.MatchingRulesCollectionStorageKey }; dto.StatementModelRootDto = new StorageBranch { Source = model.StatementModelStorageKey }; @@ -19,10 +19,10 @@ partial void ToModelPostprocessing(BudgetAnalyserStorageRoot dto, ref Applicatio { model.BudgetCollectionStorageKey = dto.BudgetCollectionRootDto.Source; model.LedgerBookStorageKey = dto.LedgerBookRootDto.Source; - var taskMapper = new Mapper_ListToDoTaskDto_ToDoCollection(); + var taskMapper = new MapperListToDoTaskDto2ToDoCollection(); model.LedgerReconciliationToDoCollection = taskMapper.ToModel(dto.LedgerReconciliationToDoCollection); model.MatchingRulesCollectionStorageKey = dto.MatchingRulesCollectionRootDto.Source; model.StatementModelStorageKey = dto.StatementModelRootDto.Source; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.generated.cs b/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.generated.cs index 7f74944f..25baa5a7 100644 --- a/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.generated.cs +++ b/BudgetAnalyser.Engine/Persistence/ApplicationDatabaseToStorageRootMapper.generated.cs @@ -12,7 +12,7 @@ namespace BudgetAnalyser.Engine.Persistence { [GeneratedCode("1.0", "Tangy Fruit Mapper 7/01/2016 3:19:51 AM UTC")] - internal partial class Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase : IDtoMapper + internal partial class MapperBudgetAnalyserStorageRoot2ApplicationDatabase : IDtoMapper { public virtual ApplicationDatabase ToModel(BudgetAnalyserStorageRoot dto) diff --git a/BudgetAnalyser.Engine/Persistence/BadApplicationStateFileFormatException.cs b/BudgetAnalyser.Engine/Persistence/BadApplicationStateFileFormatException.cs index b1dab412..99ff14cb 100644 --- a/BudgetAnalyser.Engine/Persistence/BadApplicationStateFileFormatException.cs +++ b/BudgetAnalyser.Engine/Persistence/BadApplicationStateFileFormatException.cs @@ -35,4 +35,4 @@ public BadApplicationStateFileFormatException(string message, Exception innerExc { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/BudgetAnalyserStorageRoot.cs b/BudgetAnalyser.Engine/Persistence/BudgetAnalyserStorageRoot.cs index 9cd0ea16..4db0fb26 100644 --- a/BudgetAnalyser.Engine/Persistence/BudgetAnalyserStorageRoot.cs +++ b/BudgetAnalyser.Engine/Persistence/BudgetAnalyserStorageRoot.cs @@ -54,4 +54,4 @@ public BudgetAnalyserStorageRoot() /// public StorageBranch StatementModelRootDto { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/IApplicationDatabaseRepository.cs b/BudgetAnalyser.Engine/Persistence/IApplicationDatabaseRepository.cs index 276ff9f2..6bb8f3cf 100644 --- a/BudgetAnalyser.Engine/Persistence/IApplicationDatabaseRepository.cs +++ b/BudgetAnalyser.Engine/Persistence/IApplicationDatabaseRepository.cs @@ -13,4 +13,4 @@ internal interface IApplicationDatabaseRepository Task LoadAsync([NotNull] string storageKey); Task SaveAsync([NotNull] ApplicationDatabase budgetAnalyserDatabase); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/ICredentialStore.cs b/BudgetAnalyser.Engine/Persistence/ICredentialStore.cs index d2f68216..4f674f6e 100644 --- a/BudgetAnalyser.Engine/Persistence/ICredentialStore.cs +++ b/BudgetAnalyser.Engine/Persistence/ICredentialStore.cs @@ -22,4 +22,4 @@ public interface ICredentialStore /// Will return true if the two keys are non-null and are equivalent, otherwise false. bool AreEqual(object compareTo); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/IFileReaderWriter.cs b/BudgetAnalyser.Engine/Persistence/IFileReaderWriter.cs index c52f20ae..68ca20e6 100644 --- a/BudgetAnalyser.Engine/Persistence/IFileReaderWriter.cs +++ b/BudgetAnalyser.Engine/Persistence/IFileReaderWriter.cs @@ -39,4 +39,4 @@ public interface IFileReaderWriter /// Task WriteToDiskAsync(string fileName, string data); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/IPersistentApplicationStateObject.cs b/BudgetAnalyser.Engine/Persistence/IPersistentApplicationStateObject.cs index 3715dac4..256f935c 100644 --- a/BudgetAnalyser.Engine/Persistence/IPersistentApplicationStateObject.cs +++ b/BudgetAnalyser.Engine/Persistence/IPersistentApplicationStateObject.cs @@ -11,4 +11,4 @@ public interface IPersistentApplicationStateObject /// int LoadSequence { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/LocalDiskReaderWriter.cs b/BudgetAnalyser.Engine/Persistence/LocalDiskReaderWriter.cs index 1c682b81..dab2d9e8 100644 --- a/BudgetAnalyser.Engine/Persistence/LocalDiskReaderWriter.cs +++ b/BudgetAnalyser.Engine/Persistence/LocalDiskReaderWriter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text; using System.Threading.Tasks; @@ -23,13 +23,16 @@ public Stream CreateWritableStream(string fileName) public bool FileExists(string fileName) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); - return File.Exists(fileName); + return fileName.IsNothing() ? throw new ArgumentNullException(nameof(fileName)) : File.Exists(fileName); } public async Task LoadFromDiskAsync(string fileName) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); + if (fileName.IsNothing()) + { + throw new ArgumentNullException(nameof(fileName)); + } + using (var reader = File.OpenText(fileName)) { try @@ -46,7 +49,11 @@ public async Task LoadFromDiskAsync(string fileName) public async Task LoadFirstLinesFromDiskAsync(string fileName, int lineCount) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); + if (fileName.IsNothing()) + { + throw new ArgumentNullException(nameof(fileName)); + } + using (var reader = File.OpenText(fileName)) { try @@ -74,11 +81,15 @@ public async Task LoadFirstLinesFromDiskAsync(string fileName, int lineC public async Task WriteToDiskAsync(string fileName, string data) { - if (fileName.IsNothing()) throw new ArgumentNullException(nameof(fileName)); + if (fileName.IsNothing()) + { + throw new ArgumentNullException(nameof(fileName)); + } + using (var fileStream = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))) { await fileStream.WriteAsync(data); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/StorageBranch.cs b/BudgetAnalyser.Engine/Persistence/StorageBranch.cs index 27fa79a1..f8115304 100644 --- a/BudgetAnalyser.Engine/Persistence/StorageBranch.cs +++ b/BudgetAnalyser.Engine/Persistence/StorageBranch.cs @@ -11,4 +11,4 @@ public class StorageBranch /// public string Source { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Persistence/XamlOnDiskApplicationDatabaseRepository.cs b/BudgetAnalyser.Engine/Persistence/XamlOnDiskApplicationDatabaseRepository.cs index ac24057f..0c5f4d15 100644 --- a/BudgetAnalyser.Engine/Persistence/XamlOnDiskApplicationDatabaseRepository.cs +++ b/BudgetAnalyser.Engine/Persistence/XamlOnDiskApplicationDatabaseRepository.cs @@ -1,7 +1,7 @@ -using Portable.Xaml; -using BudgetAnalyser.Engine.Ledger; +using BudgetAnalyser.Engine.Ledger; using BudgetAnalyser.Engine.Ledger.Data; using JetBrains.Annotations; +using Portable.Xaml; using Rees.TangyFruitMapper; namespace BudgetAnalyser.Engine.Persistence @@ -168,4 +168,4 @@ private async Task LoadXmlFromDiskAsync(string fileNa return result as BudgetAnalyserStorageRoot; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/PropertyInjectionAttribute.cs b/BudgetAnalyser.Engine/PropertyInjectionAttribute.cs index ec21605a..054f8848 100644 --- a/BudgetAnalyser.Engine/PropertyInjectionAttribute.cs +++ b/BudgetAnalyser.Engine/PropertyInjectionAttribute.cs @@ -12,4 +12,4 @@ namespace BudgetAnalyser.Engine public sealed class PropertyInjectionAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/PropertyInjectionDependencyRequirement.cs b/BudgetAnalyser.Engine/PropertyInjectionDependencyRequirement.cs index 0dde538e..f9dcaeba 100644 --- a/BudgetAnalyser.Engine/PropertyInjectionDependencyRequirement.cs +++ b/BudgetAnalyser.Engine/PropertyInjectionDependencyRequirement.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.Engine { @@ -19,4 +19,4 @@ public class PropertyInjectionDependencyRequirement /// public Action PropertyInjectionAssignment { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ReferenceNumberGenerator.cs b/BudgetAnalyser.Engine/ReferenceNumberGenerator.cs index bfe9be55..36180542 100644 --- a/BudgetAnalyser.Engine/ReferenceNumberGenerator.cs +++ b/BudgetAnalyser.Engine/ReferenceNumberGenerator.cs @@ -31,4 +31,4 @@ public static string IssueTransactionReferenceNumber() return reference.ToString().Substring(0, 7); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/BucketPerformanceResult.cs b/BudgetAnalyser.Engine/Reports/BucketPerformanceResult.cs index a47353cc..86e66f89 100644 --- a/BudgetAnalyser.Engine/Reports/BucketPerformanceResult.cs +++ b/BudgetAnalyser.Engine/Reports/BucketPerformanceResult.cs @@ -42,17 +42,7 @@ public class BucketPerformanceResult /// /// Gets the calculated percentage. /// - public double Percent - { - get - { - if (BudgetTotal < 0.01M) - { - return (double) Math.Round(TotalSpent / 0.01M, 2); - } - return (double) Math.Round(TotalSpent / BudgetTotal, 2); - } - } + public double Percent => BudgetTotal < 0.01M ? (double)Math.Round(TotalSpent / 0.01M, 2) : (double)Math.Round(TotalSpent / BudgetTotal, 2); /// /// Gets the summary. @@ -62,19 +52,16 @@ public string Summary get { var difference = BudgetTotal - TotalSpent; - if (Percent > 1) - { - return string.Format( + return Percent > 1 + ? string.Format( CultureInfo.CurrentCulture, "{0:P} ({1:C}) OVER Budget of {2:C}. Total Spent: {3:C}. Single Month Budget: {4:C}", Percent - 1, difference, BudgetTotal, TotalSpent, - Budget); - } - - return string.Format( + Budget) + : string.Format( CultureInfo.CurrentCulture, "{0:P} ({1:C}) under Budget of {2:C}. Total Spent: {3:C}. Single Month Budget: {4:C}", Percent, @@ -90,4 +77,4 @@ public string Summary /// public decimal TotalSpent { get; internal set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyser.cs b/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyser.cs index 79a6a1aa..82b5c2fb 100644 --- a/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyser.cs +++ b/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using BudgetAnalyser.Engine.Budget; @@ -28,10 +28,10 @@ public BurnDownChartAnalyser([NotNull] LedgerCalculation ledgerCalculator, [NotN } public BurnDownChartAnalyserResult Analyse( - StatementModel statementModel, + StatementModel statementModel, BudgetModel budgetModel, - IEnumerable bucketsSubset, - LedgerBook ledgerBook, + IEnumerable bucketsSubset, + LedgerBook ledgerBook, DateTime inclBeginDate, DateTime inclEndDate) { @@ -45,12 +45,12 @@ public BurnDownChartAnalyserResult Analyse( throw new ArgumentNullException(nameof(budgetModel)); } - List bucketsCopy = bucketsSubset.ToList(); + var bucketsCopy = bucketsSubset.ToList(); this.logger.LogInfo(l => "BurnDownChartAnalyser.Analyse: " + string.Join(" ", bucketsCopy.Select(b => b.Code))); var result = new BurnDownChartAnalyserResult(); - List datesOfTheMonth = YieldAllDaysInDateRange(inclBeginDate); + var datesOfTheMonth = YieldAllDaysInDateRange(inclBeginDate); var lastDate = datesOfTheMonth.Last(); CreateZeroLine(datesOfTheMonth, result); @@ -58,13 +58,13 @@ public BurnDownChartAnalyserResult Analyse( var openingBalance = GetBudgetedTotal(budgetModel, ledgerBook, bucketsCopy, inclBeginDate, inclEndDate); CalculateBudgetLineValues(openingBalance, datesOfTheMonth, result); - List spendingTransactions = CollateStatementTransactions(statementModel, bucketsCopy, inclBeginDate, lastDate, openingBalance); + var spendingTransactions = CollateStatementTransactions(statementModel, bucketsCopy, inclBeginDate, lastDate, openingBalance); // Only relevant when calculating surplus burndown - overspent ledgers are supplemented from surplus so affect its burndown. if (ledgerBook is not null && bucketsCopy.OfType().Any()) { var ledgerLine = this.ledgerCalculator.LocateApplicableLedgerLine(ledgerBook, inclBeginDate, inclEndDate); - List overSpentLedgers = this.ledgerCalculator.CalculateOverSpentLedgers(statementModel, ledgerLine, inclBeginDate, inclEndDate).ToList(); + var overSpentLedgers = this.ledgerCalculator.CalculateOverSpentLedgers(statementModel, ledgerLine, inclBeginDate, inclEndDate).ToList(); if (overSpentLedgers.Any()) { spendingTransactions.AddRange(overSpentLedgers.Select(t => new ReportTransactionWithRunningBalance(t))); @@ -112,7 +112,7 @@ private static void CalculateBudgetLineValues(decimal budgetTotal, List CollateStatementTransac decimal openingBalance) { // The below query has to cater for special Surplus buckets which are intended to be equivelent but use a type hierarchy with inheritance. - List query = statementModel.Transactions + var query = statementModel.Transactions .Join(bucketsToInclude, t => t.BudgetBucket, b => b, (t, b) => t, new SurplusAgnosticBucketComparer()) .Where(t => t.Date >= beginDate && t.Date <= lastDate) .OrderBy(t => t.Date) @@ -180,7 +180,7 @@ private decimal GetBudgetedTotal( DateTime inclEndDate) { decimal budgetTotal = 0; - List bucketsCopy = buckets.ToList(); + var bucketsCopy = buckets.ToList(); var ledgerLine = this.ledgerCalculator.LocateApplicableLedgerLine(ledgerBook, inclBeginDate, inclEndDate); if (ledgerLine is null) @@ -217,12 +217,7 @@ private static decimal GetBudgetModelTotalForBucket(BudgetModel budgetModel, Bud } var budget = budgetModel.Expenses.FirstOrDefault(e => e.Bucket == bucket); - if (budget is not null) - { - return budget.Amount; - } - - return 0; + return budget is not null ? budget.Amount : 0; } private static decimal GetDayClosingBalance( @@ -278,4 +273,4 @@ private static List YieldAllDaysInDateRange(DateTime beginDate) return data; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyserResult.cs b/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyserResult.cs index 8a5f4ffe..fbb3edb7 100644 --- a/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyserResult.cs +++ b/BudgetAnalyser.Engine/Reports/BurnDownChartAnalyserResult.cs @@ -55,4 +55,4 @@ public BurnDownChartAnalyserResult() /// public IEnumerable ReportTransactions { get; internal set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/BurnDownCharts.cs b/BudgetAnalyser.Engine/Reports/BurnDownCharts.cs index 732486d1..48a29a0e 100644 --- a/BudgetAnalyser.Engine/Reports/BurnDownCharts.cs +++ b/BudgetAnalyser.Engine/Reports/BurnDownCharts.cs @@ -45,4 +45,4 @@ public BurnDownCharts(DateTime beginDate, DateTime endDate, string dateRangeDesc /// public string DateRangeDescription { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/BurnDownChartsBuilder.cs b/BudgetAnalyser.Engine/Reports/BurnDownChartsBuilder.cs index e70dee6e..be14ddc3 100644 --- a/BudgetAnalyser.Engine/Reports/BurnDownChartsBuilder.cs +++ b/BudgetAnalyser.Engine/Reports/BurnDownChartsBuilder.cs @@ -66,7 +66,7 @@ public void Build( // Put any custom charts on top. foreach (var customChart in CustomCharts) { - IEnumerable buckets = this.budgetBucketRepository.Buckets + var buckets = this.budgetBucketRepository.Buckets .Join(customChart.BucketIds, bucket => bucket.Code, code => code, (bucket, code) => bucket); var analysis = AnalyseDataForChart(statementModel, budgetModel, ledgerBookModel, buckets, inclBeginDate, inclEndDate); @@ -79,10 +79,10 @@ public void Build( } private BurnDownChartAnalyserResult AnalyseDataForChart( - StatementModel statementModel, + StatementModel statementModel, BudgetModel budgetModel, - LedgerBook ledgerBookModel, - BudgetBucket bucket, + LedgerBook ledgerBookModel, + BudgetBucket bucket, DateTime inclBeginDate, DateTime inclEndDate) { @@ -116,12 +116,7 @@ private static DateTime CalculateBeginDate(GlobalFilterCriteria criteria) return criteria.BeginDate.Value; } - if (criteria.EndDate is null) - { - return DateTime.Today.AddMonths(-1); - } - - return criteria.EndDate.Value.AddMonths(-1); + return criteria.EndDate is null ? DateTime.Today.AddMonths(-1) : criteria.EndDate.Value.AddMonths(-1); } private static DateTime CalculateEndDate(GlobalFilterCriteria criteria) { @@ -135,13 +130,8 @@ private static DateTime CalculateEndDate(GlobalFilterCriteria criteria) return criteria.EndDate.Value; } - if (criteria.EndDate is null) - { - return DateTime.Today.AddMonths(-1); - } - - return criteria.EndDate.Value.AddMonths(-1); + return criteria.EndDate is null ? DateTime.Today.AddMonths(-1) : criteria.EndDate.Value.AddMonths(-1); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/CustomAggregateBurnDownGraph.cs b/BudgetAnalyser.Engine/Reports/CustomAggregateBurnDownGraph.cs index a10911ae..159f2b55 100644 --- a/BudgetAnalyser.Engine/Reports/CustomAggregateBurnDownGraph.cs +++ b/BudgetAnalyser.Engine/Reports/CustomAggregateBurnDownGraph.cs @@ -22,4 +22,4 @@ public class CustomAggregateBurnDownGraph /// public string Name { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/CustomBurnDownChartApplicationState.cs b/BudgetAnalyser.Engine/Reports/CustomBurnDownChartApplicationState.cs index 09f8a6d6..6241f0fd 100644 --- a/BudgetAnalyser.Engine/Reports/CustomBurnDownChartApplicationState.cs +++ b/BudgetAnalyser.Engine/Reports/CustomBurnDownChartApplicationState.cs @@ -23,4 +23,4 @@ public class CustomBurnDownChartApplicationState : IPersistentApplicationStateOb /// public int LoadSequence => 100; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/DatedGraphPlot.cs b/BudgetAnalyser.Engine/Reports/DatedGraphPlot.cs index e3f396f3..779ea1e1 100644 --- a/BudgetAnalyser.Engine/Reports/DatedGraphPlot.cs +++ b/BudgetAnalyser.Engine/Reports/DatedGraphPlot.cs @@ -27,4 +27,4 @@ public class DatedGraphPlot Justification = "Ok for now, only english is supported")] public string Month => Date.ToString("MMM yy"); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/GraphData.cs b/BudgetAnalyser.Engine/Reports/GraphData.cs index 6cf2e98a..db0c91e2 100644 --- a/BudgetAnalyser.Engine/Reports/GraphData.cs +++ b/BudgetAnalyser.Engine/Reports/GraphData.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; namespace BudgetAnalyser.Engine.Reports @@ -33,4 +33,4 @@ public GraphData() internal IList SeriesList { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/IBurnDownChartAnalyser.cs b/BudgetAnalyser.Engine/Reports/IBurnDownChartAnalyser.cs index 1bd0e20f..f6664ae3 100644 --- a/BudgetAnalyser.Engine/Reports/IBurnDownChartAnalyser.cs +++ b/BudgetAnalyser.Engine/Reports/IBurnDownChartAnalyser.cs @@ -22,4 +22,4 @@ BurnDownChartAnalyserResult Analyse( DateTime inclBeginDate, DateTime inclEndDate); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/LedgerBucketHistoryAnalyser.cs b/BudgetAnalyser.Engine/Reports/LedgerBucketHistoryAnalyser.cs index ba43f09a..da9b9f2a 100644 --- a/BudgetAnalyser.Engine/Reports/LedgerBucketHistoryAnalyser.cs +++ b/BudgetAnalyser.Engine/Reports/LedgerBucketHistoryAnalyser.cs @@ -61,4 +61,4 @@ public void Analyse([NotNull] LedgerBucket ledger, [NotNull] LedgerBook book) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/LongTermSpendingTrendAnalyser.cs b/BudgetAnalyser.Engine/Reports/LongTermSpendingTrendAnalyser.cs index 41db8ba0..f69d3d0f 100644 --- a/BudgetAnalyser.Engine/Reports/LongTermSpendingTrendAnalyser.cs +++ b/BudgetAnalyser.Engine/Reports/LongTermSpendingTrendAnalyser.cs @@ -62,7 +62,7 @@ public void Analyse([NotNull] StatementModel statement, [NotNull] GlobalFilterCr var currentMonth = minDate; var nextMonth = currentMonth.AddMonths(1); var subTotals = new Dictionary(); - List allSeriesData = InitialiseSeriesData(minDate, maxDate); + var allSeriesData = InitialiseSeriesData(minDate, maxDate); foreach (var transaction in statement.AllTransactions) { @@ -129,7 +129,7 @@ private static void GetOrAdd(IDictionary dictionary, string key private List InitialiseSeriesData(DateTime minDate, DateTime maxDate) { - List allSeriesData = this.budgetBucketRepo.Buckets + var allSeriesData = this.budgetBucketRepo.Buckets .Select(bucket => new SeriesData { SeriesName = bucket.Code, Description = bucket.Description }) .ToList(); @@ -149,7 +149,7 @@ private List InitialiseSeriesData(DateTime minDate, DateTime maxDate private void RemoveSeriesWithNoData() { - List zeroSeries = Graph.SeriesList.Where(s => s.PlotsList.Sum(p => p.Amount) == 0).ToList(); + var zeroSeries = Graph.SeriesList.Where(s => s.PlotsList.Sum(p => p.Amount) == 0).ToList(); foreach (var removeMe in zeroSeries) { Graph.SeriesList.Remove(removeMe); @@ -160,7 +160,7 @@ private static void StoreSummarisedMonthData(Dictionary subTota List allSeriesData, DateTime currentMonth) { // Current month's data is complete - update totals and advance to next month - foreach (KeyValuePair subTotal in subTotals) + foreach (var subTotal in subTotals) { // Find appropriate bucket series var series = allSeriesData.Single(a => a.SeriesName == subTotal.Key); @@ -171,4 +171,4 @@ private static void StoreSummarisedMonthData(Dictionary subTota } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetAnalyser.cs b/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetAnalyser.cs index e88283cf..5633f26a 100644 --- a/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetAnalyser.cs +++ b/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetAnalyser.cs @@ -40,12 +40,11 @@ public OverallPerformanceBudgetAnalyser([NotNull] IBudgetBucketRepository bucket public virtual OverallPerformanceBudgetResult Analyse(StatementModel statementModel, BudgetCollection budgets, [NotNull] GlobalFilterCriteria criteria) { - DateTime endDate, beginDate; - AnalysisPreconditions(criteria, statementModel, budgets, out beginDate, out endDate); + AnalysisPreconditions(criteria, statementModel, budgets, out var beginDate, out var endDate); var result = new OverallPerformanceBudgetResult(); - List budgetsInvolved = budgets.ForDates(beginDate, endDate).ToList(); + var budgetsInvolved = budgets.ForDates(beginDate, endDate).ToList(); result.UsesMultipleBudgets = budgetsInvolved.Count() > 1; var currentBudget = budgetsInvolved.Last(); // Use most recent budget as the current @@ -58,7 +57,7 @@ public virtual OverallPerformanceBudgetResult Analyse(StatementModel statementMo foreach (var bucket in this.bucketRepository.Buckets) { var bucketCopy = bucket; - List query = statementModel.Transactions.Where(t => t.BudgetBucket == bucketCopy).ToList(); + var query = statementModel.Transactions.Where(t => t.BudgetBucket == bucketCopy).ToList(); var totalSpent = query.Sum(t => t.Amount); var averageSpend = totalSpent / result.DurationInMonths; @@ -171,12 +170,7 @@ private static Func BuildExpenseFinder(BudgetBucket bucket return b => { var first = b.Expenses.FirstOrDefault(e => e.Bucket == bucket); - if (first is null) - { - return 0; - } - - return first.Amount; + return first is null ? 0 : first.Amount; }; } @@ -185,12 +179,7 @@ private static Func BuildIncomeFinder(BudgetBucket bucket) return b => { var first = b.Incomes.FirstOrDefault(e => e.Bucket == bucket); - if (first is null) - { - return 0; - } - - return first.Amount; + return first is null ? 0 : first.Amount; }; } @@ -237,4 +226,4 @@ private static void CalculateTotalsAndAverage(DateTime beginDate, StatementModel result.OverallPerformance = result.AverageSpend + result.TotalBudgetExpenses; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetResult.cs b/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetResult.cs index f4ee03d1..8a80389e 100644 --- a/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetResult.cs +++ b/BudgetAnalyser.Engine/Reports/OverallPerformanceBudgetResult.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace BudgetAnalyser.Engine.Reports { @@ -45,4 +45,4 @@ public class OverallPerformanceBudgetResult /// public bool UsesMultipleBudgets { get; internal set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/ReportTransaction.cs b/BudgetAnalyser.Engine/Reports/ReportTransaction.cs index 19814ec9..bd095885 100644 --- a/BudgetAnalyser.Engine/Reports/ReportTransaction.cs +++ b/BudgetAnalyser.Engine/Reports/ReportTransaction.cs @@ -22,4 +22,4 @@ public class ReportTransaction /// public string Narrative { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/ReportTransactionWithRunningBalance.cs b/BudgetAnalyser.Engine/Reports/ReportTransactionWithRunningBalance.cs index e4ca20d8..1c871412 100644 --- a/BudgetAnalyser.Engine/Reports/ReportTransactionWithRunningBalance.cs +++ b/BudgetAnalyser.Engine/Reports/ReportTransactionWithRunningBalance.cs @@ -38,4 +38,4 @@ public ReportTransactionWithRunningBalance([NotNull] ReportTransaction transacti /// public decimal Balance { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Reports/SeriesData.cs b/BudgetAnalyser.Engine/Reports/SeriesData.cs index e5c4584d..f48be14e 100644 --- a/BudgetAnalyser.Engine/Reports/SeriesData.cs +++ b/BudgetAnalyser.Engine/Reports/SeriesData.cs @@ -56,7 +56,7 @@ public SeriesData() /// public bool Visible { - get { return this.doNotUseVisible; } + get => this.doNotUseVisible; set { this.doNotUseVisible = value; @@ -71,4 +71,4 @@ private void OnPropertyChanged([CallerMemberName] string propertyName = null) handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/AdditionalInformationRequestedEventArgs.cs b/BudgetAnalyser.Engine/Services/AdditionalInformationRequestedEventArgs.cs index 95600ccc..83b1c4c3 100644 --- a/BudgetAnalyser.Engine/Services/AdditionalInformationRequestedEventArgs.cs +++ b/BudgetAnalyser.Engine/Services/AdditionalInformationRequestedEventArgs.cs @@ -1,4 +1,4 @@ -namespace BudgetAnalyser.Engine.Services +namespace BudgetAnalyser.Engine.Services { /// /// A set or event arguments for the event. @@ -12,4 +12,4 @@ public class AdditionalInformationRequestedEventArgs : ValidatingEventArgs /// public object? Context { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ApplicationDatabaseService.cs b/BudgetAnalyser.Engine/Services/ApplicationDatabaseService.cs index 92908d54..8404fc47 100644 --- a/BudgetAnalyser.Engine/Services/ApplicationDatabaseService.cs +++ b/BudgetAnalyser.Engine/Services/ApplicationDatabaseService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -37,9 +37,20 @@ public ApplicationDatabaseService( throw new ArgumentNullException(nameof(databaseDependents)); } - if (monitorableDependencies is null) throw new ArgumentNullException(nameof(monitorableDependencies)); - if (credentialStore is null) throw new ArgumentNullException(nameof(credentialStore)); - if (logger is null) throw new ArgumentNullException(nameof(logger)); + if (monitorableDependencies is null) + { + throw new ArgumentNullException(nameof(monitorableDependencies)); + } + + if (credentialStore is null) + { + throw new ArgumentNullException(nameof(credentialStore)); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger)); + } this.applicationRepository = applicationRepository; this.monitorableDependencies = monitorableDependencies; @@ -100,7 +111,7 @@ public async Task CreateNewDatabaseAsync(string storageKey) } public async Task EncryptFilesAsync() - { + { if (this.credentialStore.RetrievePasskey() is null) { throw new EncryptionKeyNotProvidedException("Attempt to use encryption but no password is set."); @@ -188,15 +199,12 @@ public void NotifyOfChange(ApplicationDataType dataType) public MainApplicationState PreparePersistentStateData() { - if (this.budgetAnalyserDatabase is null) - { - return new MainApplicationState(); - } - - return new MainApplicationState - { - BudgetAnalyserDataStorageKey = this.budgetAnalyserDatabase.FileName - }; + return this.budgetAnalyserDatabase is null + ? new MainApplicationState() + : new MainApplicationState + { + BudgetAnalyserDataStorageKey = this.budgetAnalyserDatabase.FileName + }; } public async Task SaveAsync() @@ -229,7 +237,7 @@ public async Task SaveAsync() await this.applicationRepository.SaveAsync(this.budgetAnalyserDatabase); // Save all remaining service's data. - foreach(var service in this.databaseDependents.Where(s => this.dirtyData[s.DataType])) + foreach (var service in this.databaseDependents.Where(s => this.dirtyData[s.DataType])) { await service.SaveAsync(this.budgetAnalyserDatabase); } @@ -302,7 +310,7 @@ private void InitialiseDirtyDataTable() { foreach (int value in Enum.GetValues(typeof(ApplicationDataType))) { - var enumValue = (ApplicationDataType) value; + var enumValue = (ApplicationDataType)value; this.dirtyData.Add(enumValue, false); } } @@ -312,8 +320,8 @@ private void SetAllDirtyFlags() // Ensure all data types are marked as requiring a save. foreach (var dataType in Enum.GetValues(typeof(ApplicationDataType))) { - this.dirtyData[(ApplicationDataType) dataType] = true; + this.dirtyData[(ApplicationDataType)dataType] = true; } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/BudgetMaintenanceService.cs b/BudgetAnalyser.Engine/Services/BudgetMaintenanceService.cs index ccf60a66..92f67672 100644 --- a/BudgetAnalyser.Engine/Services/BudgetMaintenanceService.cs +++ b/BudgetAnalyser.Engine/Services/BudgetMaintenanceService.cs @@ -161,7 +161,7 @@ public void SavePreview() public bool ValidateModel(StringBuilder messages) { - EventHandler handler = Validating; + var handler = Validating; var args = new ValidatingEventArgs(); handler?.Invoke(this, args); @@ -196,7 +196,7 @@ private void CreateNewBudgetCollection() private void EnsureAllBucketsUsedAreInBucketRepo() { // Make sure all buckets are in the bucket repo. - IEnumerable buckets = Budgets.SelectMany(b => b.Expenses.Select(e => e.Bucket)) + var buckets = Budgets.SelectMany(b => b.Expenses.Select(e => e.Bucket)) .Union(Budgets.SelectMany(b => b.Incomes.Select(i => i.Bucket))) .Distinct(); @@ -213,4 +213,4 @@ private void UpdateServiceMonitor() this.monitorableDependencies.NotifyOfDependencyChange(new BudgetCurrencyContext(Budgets, Budgets.CurrentActiveBudget)); this.monitorableDependencies.NotifyOfDependencyChange(Budgets); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/DashboardService.cs b/BudgetAnalyser.Engine/Services/DashboardService.cs index 68b7068f..9c8a2b71 100644 --- a/BudgetAnalyser.Engine/Services/DashboardService.cs +++ b/BudgetAnalyser.Engine/Services/DashboardService.cs @@ -46,7 +46,10 @@ public DashboardService( { throw new ArgumentNullException(nameof(logger)); } - if (monitorableDependencies is null) throw new ArgumentNullException(nameof(monitorableDependencies)); + if (monitorableDependencies is null) + { + throw new ArgumentNullException(nameof(monitorableDependencies)); + } this.widgetService = widgetService; this.bucketRepository = bucketRepository; @@ -79,7 +82,7 @@ public Widget CreateNewBucketMonitorWidget(string bucketCode) } var widget = this.widgetService.Create(typeof(BudgetBucketMonitorWidget).FullName, bucketCode); - return UpdateWidgetCollectionWithNewAddition((Widget) widget); + return UpdateWidgetCollectionWithNewAddition((Widget)widget); } public Widget CreateNewFixedBudgetMonitorWidget(string bucketCode, string description, decimal fixedBudgetAmount) @@ -102,7 +105,7 @@ public Widget CreateNewFixedBudgetMonitorWidget(string bucketCode, string descri var bucket = this.bucketRepository.CreateNewFixedBudgetProject(bucketCode, description, fixedBudgetAmount); this.budgetRepository.SaveAsync(); var widget = this.widgetService.Create(typeof(FixedBudgetMonitorWidget).FullName, bucket.Code); - return UpdateWidgetCollectionWithNewAddition((Widget) widget); + return UpdateWidgetCollectionWithNewAddition((Widget)widget); } public Widget CreateNewSurprisePaymentMonitorWidget(string bucketCode, DateTime paymentDate, @@ -118,19 +121,14 @@ public Widget CreateNewSurprisePaymentMonitorWidget(string bucketCode, DateTime throw new ArgumentException("Payment date is not set.", nameof(paymentDate)); } - var bucket = this.bucketRepository.GetByCode(bucketCode); - if (bucket is null) - { - throw new ArgumentException( + var bucket = this.bucketRepository.GetByCode(bucketCode) ?? throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, "No Bucket with code {0} exists", bucketCode), nameof(bucketCode)); - } - var widget = this.widgetService.Create(typeof(SurprisePaymentWidget).FullName, bucket.Code); - var paymentWidget = (SurprisePaymentWidget) widget; + var paymentWidget = (SurprisePaymentWidget)widget; paymentWidget.StartPaymentDate = paymentDate; paymentWidget.Frequency = frequency; - return UpdateWidgetCollectionWithNewAddition((Widget) widget); + return UpdateWidgetCollectionWithNewAddition((Widget)widget); } public ObservableCollection LoadPersistedStateData(WidgetsApplicationState storedState) @@ -168,9 +166,7 @@ public void RemoveUserDefinedWidget(IUserDefinedWidget widgetToRemove) if (fixedProjectWidget is not null) { // Reassign transactions to Surplus - var projectBucket = - this.bucketRepository.GetByCode(fixedProjectWidget.BucketCode) as FixedBudgetProjectBucket; - if (projectBucket is null) + if (this.bucketRepository.GetByCode(fixedProjectWidget.BucketCode) is not FixedBudgetProjectBucket projectBucket) { throw new InvalidOperationException( "The fixed project bucket provided doesn't actually appear to be a Fixed Budget Project Bucket"); @@ -189,7 +185,7 @@ public void RemoveUserDefinedWidget(IUserDefinedWidget widgetToRemove) this.widgetService.Remove(widgetToRemove); - var baseWidget = (Widget) widgetToRemove; + var baseWidget = (Widget)widgetToRemove; var widgetGroup = WidgetGroups.FirstOrDefault(group => group.Heading == baseWidget.Category); widgetGroup?.Widgets.Remove(baseWidget); @@ -207,25 +203,21 @@ private static WidgetPersistentState CreateWidgetState(Widget widget) var multiInstanceWidget = widget as IUserDefinedWidget; if (multiInstanceWidget is not null) { - var surprisePaymentWidget = multiInstanceWidget as SurprisePaymentWidget; - if (surprisePaymentWidget is null) - { - return new MultiInstanceWidgetState + return multiInstanceWidget is not SurprisePaymentWidget surprisePaymentWidget + ? new MultiInstanceWidgetState { Id = multiInstanceWidget.Id, Visible = multiInstanceWidget.Visibility, WidgetType = multiInstanceWidget.WidgetType.FullName + } + : (WidgetPersistentState)new SurprisePaymentWidgetPersistentState + { + Id = surprisePaymentWidget.Id, + Visible = surprisePaymentWidget.Visibility, + WidgetType = surprisePaymentWidget.WidgetType.FullName, + PaymentStartDate = surprisePaymentWidget.StartPaymentDate, + Frequency = surprisePaymentWidget.Frequency }; - } - - return new SurprisePaymentWidgetPersistentState - { - Id = surprisePaymentWidget.Id, - Visible = surprisePaymentWidget.Visibility, - WidgetType = surprisePaymentWidget.WidgetType.FullName, - PaymentStartDate = surprisePaymentWidget.StartPaymentDate, - Frequency = surprisePaymentWidget.Frequency - }; } return new WidgetPersistentState @@ -278,7 +270,7 @@ private void UpdateAllWidgets(params Type[] filterDependencyTypes) if (filterDependencyTypes is not null && filterDependencyTypes.Length > 0) { // targeted update - List affectedWidgets = WidgetGroups.SelectMany(group => group.Widgets) + var affectedWidgets = WidgetGroups.SelectMany(group => group.Widgets) .Where(w => w.Dependencies.Any(filterDependencyTypes.Contains)) .ToList(); affectedWidgets.ForEach(UpdateWidget); @@ -339,4 +331,4 @@ private Widget UpdateWidgetCollectionWithNewAddition(Widget baseWidget) return baseWidget; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/DependencyChangedEventArgs.cs b/BudgetAnalyser.Engine/Services/DependencyChangedEventArgs.cs index 1320a0c6..08690abd 100644 --- a/BudgetAnalyser.Engine/Services/DependencyChangedEventArgs.cs +++ b/BudgetAnalyser.Engine/Services/DependencyChangedEventArgs.cs @@ -11,4 +11,4 @@ public DependencyChangedEventArgs(Type dependencyType) public Type DependencyType { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/EncryptionKeyIncorrectException.cs b/BudgetAnalyser.Engine/Services/EncryptionKeyIncorrectException.cs index 60d89f79..5a8a01d9 100644 --- a/BudgetAnalyser.Engine/Services/EncryptionKeyIncorrectException.cs +++ b/BudgetAnalyser.Engine/Services/EncryptionKeyIncorrectException.cs @@ -34,4 +34,4 @@ public EncryptionKeyIncorrectException(string message, Exception innerException) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/EncryptionKeyNotProvidedException.cs b/BudgetAnalyser.Engine/Services/EncryptionKeyNotProvidedException.cs index d09b0021..ff4a88a0 100644 --- a/BudgetAnalyser.Engine/Services/EncryptionKeyNotProvidedException.cs +++ b/BudgetAnalyser.Engine/Services/EncryptionKeyNotProvidedException.cs @@ -34,4 +34,4 @@ public EncryptionKeyNotProvidedException(string message, Exception innerExceptio { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IApplicationDatabaseService.cs b/BudgetAnalyser.Engine/Services/IApplicationDatabaseService.cs index 72e9fb7c..df207917 100644 --- a/BudgetAnalyser.Engine/Services/IApplicationDatabaseService.cs +++ b/BudgetAnalyser.Engine/Services/IApplicationDatabaseService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; @@ -112,4 +112,4 @@ public interface IApplicationDatabaseService : IServiceFoundation /// True if valid, otherwise false. bool ValidateAll(StringBuilder messages); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IBudgetMaintenanceService.cs b/BudgetAnalyser.Engine/Services/IBudgetMaintenanceService.cs index c7cc1ed7..50892704 100644 --- a/BudgetAnalyser.Engine/Services/IBudgetMaintenanceService.cs +++ b/BudgetAnalyser.Engine/Services/IBudgetMaintenanceService.cs @@ -47,4 +47,4 @@ public interface IBudgetMaintenanceService : INotifyDatabaseChanges, IServiceFou /// All expense objects that may have changed in the UI. void UpdateIncomesAndExpenses(BudgetModel model, IEnumerable allIncomes, IEnumerable allExpenses); -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IDashboardService.cs b/BudgetAnalyser.Engine/Services/IDashboardService.cs index b2c82f46..b08fb9c1 100644 --- a/BudgetAnalyser.Engine/Services/IDashboardService.cs +++ b/BudgetAnalyser.Engine/Services/IDashboardService.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Widgets; @@ -76,4 +76,4 @@ Widget CreateNewSurprisePaymentMonitorWidget([NotNull] string bucketCode, DateTi /// void ShowAllWidgets(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ILedgerService.cs b/BudgetAnalyser.Engine/Services/ILedgerService.cs index 8333a0b8..eb333105 100644 --- a/BudgetAnalyser.Engine/Services/ILedgerService.cs +++ b/BudgetAnalyser.Engine/Services/ILedgerService.cs @@ -43,4 +43,4 @@ public interface ILedgerService : INotifyDatabaseChanges, IServiceFoundation /// IEnumerable ValidLedgerAccounts(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/INotifyDatabaseChanges.cs b/BudgetAnalyser.Engine/Services/INotifyDatabaseChanges.cs index 8031f58a..cfd1a08b 100644 --- a/BudgetAnalyser.Engine/Services/INotifyDatabaseChanges.cs +++ b/BudgetAnalyser.Engine/Services/INotifyDatabaseChanges.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.Engine.Services { @@ -35,4 +35,4 @@ public interface INotifyDatabaseChanges /// event EventHandler Validating; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IOverallPerformanceChartService.cs b/BudgetAnalyser.Engine/Services/IOverallPerformanceChartService.cs index 97b1d18c..6c3ca6bc 100644 --- a/BudgetAnalyser.Engine/Services/IOverallPerformanceChartService.cs +++ b/BudgetAnalyser.Engine/Services/IOverallPerformanceChartService.cs @@ -20,4 +20,4 @@ public interface IOverallPerformanceChartService : IServiceFoundation OverallPerformanceBudgetResult BuildChart([NotNull] StatementModel statementModel, [NotNull] BudgetCollection budgets, [NotNull] GlobalFilterCriteria criteria); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IReconciliationService.cs b/BudgetAnalyser.Engine/Services/IReconciliationService.cs index bde55e3d..b8863e0a 100644 --- a/BudgetAnalyser.Engine/Services/IReconciliationService.cs +++ b/BudgetAnalyser.Engine/Services/IReconciliationService.cs @@ -87,4 +87,4 @@ LedgerEntryLine PeriodEndReconciliation([NotNull] LedgerBook ledgerBook, /// Updates the remarks for the given Ledger Entry Line. /// void UpdateRemarks([NotNull] LedgerEntryLine entryLine, [NotNull] string remarks); -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IServiceFoundation.cs b/BudgetAnalyser.Engine/Services/IServiceFoundation.cs index 370198e6..d4add169 100644 --- a/BudgetAnalyser.Engine/Services/IServiceFoundation.cs +++ b/BudgetAnalyser.Engine/Services/IServiceFoundation.cs @@ -14,4 +14,4 @@ namespace BudgetAnalyser.Engine.Services public interface IServiceFoundation { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ISupportsModelPersistence.cs b/BudgetAnalyser.Engine/Services/ISupportsModelPersistence.cs index 713c4e0e..060f68df 100644 --- a/BudgetAnalyser.Engine/Services/ISupportsModelPersistence.cs +++ b/BudgetAnalyser.Engine/Services/ISupportsModelPersistence.cs @@ -55,4 +55,4 @@ public interface ISupportsModelPersistence /// bool ValidateModel([NotNull] StringBuilder messages); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ITransactionManagerService.cs b/BudgetAnalyser.Engine/Services/ITransactionManagerService.cs index 7a44bb9d..d556cce6 100644 --- a/BudgetAnalyser.Engine/Services/ITransactionManagerService.cs +++ b/BudgetAnalyser.Engine/Services/ITransactionManagerService.cs @@ -148,4 +148,4 @@ void SplitTransaction( /// Task ValidateWithCurrentBudgetsAsync(BudgetCollection budgets = null); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ITransactionRuleService.cs b/BudgetAnalyser.Engine/Services/ITransactionRuleService.cs index 37b3de53..d9cdb6e8 100644 --- a/BudgetAnalyser.Engine/Services/ITransactionRuleService.cs +++ b/BudgetAnalyser.Engine/Services/ITransactionRuleService.cs @@ -101,4 +101,4 @@ bool IsRuleSimilar( /// bool RemoveRule([NotNull] MatchingRule ruleToRemove); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/IWidgetService.cs b/BudgetAnalyser.Engine/Services/IWidgetService.cs index 26bce0b3..c01db441 100644 --- a/BudgetAnalyser.Engine/Services/IWidgetService.cs +++ b/BudgetAnalyser.Engine/Services/IWidgetService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using BudgetAnalyser.Engine.Widgets; using JetBrains.Annotations; @@ -28,4 +28,4 @@ public interface IWidgetService /// void Remove(IUserDefinedWidget widget); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/LedgerService.cs b/BudgetAnalyser.Engine/Services/LedgerService.cs index 6c368250..c94bb69e 100644 --- a/BudgetAnalyser.Engine/Services/LedgerService.cs +++ b/BudgetAnalyser.Engine/Services/LedgerService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; @@ -40,7 +40,10 @@ public LedgerService( throw new ArgumentNullException(nameof(ledgerBucketFactory)); } - if (monitorableDependencies is null) throw new ArgumentNullException(nameof(monitorableDependencies)); + if (monitorableDependencies is null) + { + throw new ArgumentNullException(nameof(monitorableDependencies)); + } this.ledgerRepository = ledgerRepository; this.accountTypeRepository = accountTypeRepository; @@ -154,10 +157,10 @@ public void SavePreview() public bool ValidateModel(StringBuilder messages) { - EventHandler handler = Validating; + var handler = Validating; handler?.Invoke(this, new ValidatingEventArgs()); return LedgerBook.Validate(messages); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/MonitorableDependencies.cs b/BudgetAnalyser.Engine/Services/MonitorableDependencies.cs index fac96691..c3c43a0b 100644 --- a/BudgetAnalyser.Engine/Services/MonitorableDependencies.cs +++ b/BudgetAnalyser.Engine/Services/MonitorableDependencies.cs @@ -66,7 +66,11 @@ internal virtual bool NotifyOfDependencyChange([CanBeNull] T dependency) /// A boolean value indicating if the dependency has significantly change, true if so, otherwise false. internal virtual bool NotifyOfDependencyChange([CanBeNull] object dependency, Type typeKey) { - if (dependency is null) return false; + if (dependency is null) + { + return false; + } + this.availableDependencies[typeKey] = dependency; if (HasDependencySignificantlyChanged(dependency, typeKey)) { @@ -90,8 +94,7 @@ internal virtual object RetrieveDependency(Type key) private bool HasDependencySignificantlyChanged(object dependency, Type typeKey) { - var supportsDataChangeDetection = dependency as IDataChangeDetection; - if (supportsDataChangeDetection is null) + if (dependency is not IDataChangeDetection supportsDataChangeDetection) { // Dependency doesn't support change hashes so every change is deemed worthy to trigger an update the UI. return true; @@ -109,4 +112,4 @@ private bool HasDependencySignificantlyChanged(object dependency, Type typeKey) return result; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/OverallPerformanceChartService.cs b/BudgetAnalyser.Engine/Services/OverallPerformanceChartService.cs index 672d0374..3a0f4cc4 100644 --- a/BudgetAnalyser.Engine/Services/OverallPerformanceChartService.cs +++ b/BudgetAnalyser.Engine/Services/OverallPerformanceChartService.cs @@ -34,12 +34,9 @@ public OverallPerformanceBudgetResult BuildChart(StatementModel statementModel, throw new ArgumentNullException(nameof(budgets)); } - if (criteria is null) - { - throw new ArgumentNullException(nameof(criteria)); - } - - return this.analyser.Analyse(statementModel, budgets, criteria); + return criteria is null + ? throw new ArgumentNullException(nameof(criteria)) + : this.analyser.Analyse(statementModel, budgets, criteria); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ReconciliationService.cs b/BudgetAnalyser.Engine/Services/ReconciliationService.cs index afc8a2ba..56f8594f 100644 --- a/BudgetAnalyser.Engine/Services/ReconciliationService.cs +++ b/BudgetAnalyser.Engine/Services/ReconciliationService.cs @@ -111,7 +111,7 @@ public LedgerTransaction CreateLedgerTransaction(LedgerBook ledgerBook, LedgerEn newTransaction.Date = reconciliation.Date; // ledgerEntry.AddTransactionForPersistenceOnly(newTransaction); - List replacementTxns = ledgerEntry.Transactions.ToList(); + var replacementTxns = ledgerEntry.Transactions.ToList(); replacementTxns.Add(newTransaction); ledgerEntry.SetTransactionsForReconciliation(replacementTxns); ledgerEntry.RecalculateClosingBalance(ledgerBook); @@ -168,12 +168,7 @@ public void TransferFunds(LedgerBook ledgerBook, LedgerEntryLine reconciliation, public LedgerEntryLine UnlockCurrentPeriod(LedgerBook ledgerBook) { - if (ledgerBook is null) - { - throw new ArgumentNullException(nameof(ledgerBook)); - } - - return ledgerBook.UnlockMostRecentLine(); + return ledgerBook is null ? throw new ArgumentNullException(nameof(ledgerBook)) : ledgerBook.UnlockMostRecentLine(); } public void UpdateRemarks(LedgerEntryLine entryLine, string remarks) @@ -243,4 +238,4 @@ public bool ValidateModel(StringBuilder messages) { return true; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/TransactionConstants.cs b/BudgetAnalyser.Engine/Services/TransactionConstants.cs index f25db75e..f9461198 100644 --- a/BudgetAnalyser.Engine/Services/TransactionConstants.cs +++ b/BudgetAnalyser.Engine/Services/TransactionConstants.cs @@ -10,4 +10,4 @@ public static class TransactionConstants /// public const string UncategorisedFilter = "[Uncategorised Only]"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/TransactionManagerService.cs b/BudgetAnalyser.Engine/Services/TransactionManagerService.cs index 4dc28b72..678a6158 100644 --- a/BudgetAnalyser.Engine/Services/TransactionManagerService.cs +++ b/BudgetAnalyser.Engine/Services/TransactionManagerService.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Globalization; using System.Text; using BudgetAnalyser.Engine.BankAccount; @@ -56,7 +56,10 @@ public TransactionManagerService( throw new ArgumentNullException(nameof(logger)); } - if (monitorableDependencies is null) throw new ArgumentNullException(nameof(monitorableDependencies)); + if (monitorableDependencies is null) + { + throw new ArgumentNullException(nameof(monitorableDependencies)); + } this.bucketRepository = bucketRepository; this.statementRepository = statementRepository; @@ -95,18 +98,9 @@ public TransactionManagerService( /// /// Gets the calculated average debit. /// - public decimal AverageDebit - { - get - { - if (this.transactions is null || this.transactions.None()) - { - return 0; - } - - return this.transactions.Where(t => t.Amount < 0).SafeAverage(t => t.Amount); - } - } + public decimal AverageDebit => this.transactions is null || this.transactions.None() + ? 0 + : this.transactions.Where(t => t.Amount < 0).SafeAverage(t => t.Amount); /// /// Gets the type of the data the implementation deals with. @@ -126,50 +120,17 @@ public decimal AverageDebit /// /// Gets the calculated total count. /// - public decimal TotalCount - { - get - { - if (this.transactions is null || this.transactions.None()) - { - return 0; - } - - return this.transactions.Count(); - } - } + public decimal TotalCount => this.transactions is null || this.transactions.None() ? 0 : this.transactions.Count(); /// /// Gets the calculated total credits. /// - public decimal TotalCredits - { - get - { - if (this.transactions is null || this.transactions.None()) - { - return 0; - } - - return this.transactions.Where(t => t.Amount > 0).Sum(t => t.Amount); - } - } + public decimal TotalCredits => this.transactions is null || this.transactions.None() ? 0 : this.transactions.Where(t => t.Amount > 0).Sum(t => t.Amount); /// /// Gets the calculated total debits. /// - public decimal TotalDebits - { - get - { - if (this.transactions is null || this.transactions.None()) - { - return 0; - } - - return this.transactions.Where(t => t.Amount < 0).Sum(t => t.Amount); - } - } + public decimal TotalDebits => this.transactions is null || this.transactions.None() ? 0 : this.transactions.Where(t => t.Amount < 0).Sum(t => t.Amount); /// /// Closes the currently loaded file. No warnings will be raised if there is unsaved data. @@ -239,7 +200,7 @@ public async Task SaveAsync(ApplicationDatabase applicationDatabase) return; } - EventHandler handler = Saving; + var handler = Saving; handler?.Invoke(this, new AdditionalInformationRequestedEventArgs()); var messages = new StringBuilder(); @@ -300,7 +261,7 @@ public string DetectDuplicateTransactions() return null; } - List> duplicates = StatementModel.ValidateAgainstDuplicates().ToList(); + var duplicates = StatementModel.ValidateAgainstDuplicates().ToList(); return duplicates.Any() ? string.Format(CultureInfo.CurrentCulture, "{0} suspected duplicates!", duplicates.Sum(group => group.Count())) @@ -421,7 +382,7 @@ public async Task ImportAndMergeBankStatementAsync(string storageKey, Account ac var additionalModel = await this.statementRepository.ImportBankStatementAsync(storageKey, account); var combinedModel = StatementModel.Merge(additionalModel); - var minDate = additionalModel.AllTransactions.Min(t => t.Date); + var minDate = additionalModel.AllTransactions.Min(t => t.Date); var maxDate = additionalModel.AllTransactions.Max(t => t.Date); IEnumerable> duplicates = combinedModel.ValidateAgainstDuplicates(minDate, maxDate).ToList(); if (duplicates.Count() == additionalModel.AllTransactions.Count()) @@ -622,4 +583,4 @@ private void ResetTransactionsCollection() : new ObservableCollection(StatementModel.Transactions); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/TransactionRuleService.cs b/BudgetAnalyser.Engine/Services/TransactionRuleService.cs index 9b1d996f..0d4b28f6 100644 --- a/BudgetAnalyser.Engine/Services/TransactionRuleService.cs +++ b/BudgetAnalyser.Engine/Services/TransactionRuleService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -127,13 +127,13 @@ public async Task SaveAsync(ApplicationDatabase applicationDatabase) public void SavePreview() { - EventHandler handler = Saving; + var handler = Saving; handler?.Invoke(this, new AdditionalInformationRequestedEventArgs()); } public bool ValidateModel(StringBuilder messages) { - EventHandler handler = Validating; + var handler = Validating; handler?.Invoke(this, new ValidatingEventArgs()); return true; } @@ -313,7 +313,7 @@ private void InitialiseTheRulesCollections(List repoRules) .Select(group => new RulesGroupedByBucket(group.Key, group)) .OrderBy(group => group.Bucket.Code); - IOrderedEnumerable allBuckets = this.bucketRepo.Buckets.OrderBy(b => b); + var allBuckets = this.bucketRepo.Buckets.OrderBy(b => b); foreach (var bucket in allBuckets) { var group = grouped.FirstOrDefault(g => g.Bucket == bucket); @@ -358,4 +358,4 @@ private static void IsSimilarRulePreconditions(SimilarMatchedRule rule, DecimalC } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/ValidatingEventArgs.cs b/BudgetAnalyser.Engine/Services/ValidatingEventArgs.cs index 84d659a2..9ba42949 100644 --- a/BudgetAnalyser.Engine/Services/ValidatingEventArgs.cs +++ b/BudgetAnalyser.Engine/Services/ValidatingEventArgs.cs @@ -9,4 +9,4 @@ namespace BudgetAnalyser.Engine.Services public class ValidatingEventArgs : EventArgs { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Services/WidgetService.cs b/BudgetAnalyser.Engine/Services/WidgetService.cs index 9531828b..9b74ae90 100644 --- a/BudgetAnalyser.Engine/Services/WidgetService.cs +++ b/BudgetAnalyser.Engine/Services/WidgetService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; @@ -45,7 +45,7 @@ public IEnumerable PrepareWidgets(IEnumerable widgets = this.widgetRepo.GetAll().ToList(); + var widgets = this.widgetRepo.GetAll().ToList(); foreach (var widgetState in storedStates) { var stateClone = widgetState; @@ -104,4 +104,4 @@ private void CreateMultiInstanceWidget(MultiInstanceWidgetState multiInstanceSta newIdWidget.Initialise(multiInstanceState, this.logger); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/AnzAccountStatementImporterV1.cs b/BudgetAnalyser.Engine/Statement/AnzAccountStatementImporterV1.cs index cf65de66..da7901c9 100644 --- a/BudgetAnalyser.Engine/Statement/AnzAccountStatementImporterV1.cs +++ b/BudgetAnalyser.Engine/Statement/AnzAccountStatementImporterV1.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using BudgetAnalyser.Engine.BankAccount; using JetBrains.Annotations; @@ -77,7 +77,7 @@ public async Task LoadAsync(string fileName, Account account) continue; } - string[] split = line.Split(','); + var split = line.Split(','); var transaction = new Transaction { Account = account, @@ -109,7 +109,7 @@ public async Task TasteTestAsync(string fileName) { this.importUtilities.AbortIfFileDoesntExist(fileName); - string[]? lines = await ReadFirstTwoLinesAsync(fileName); + var lines = await ReadFirstTwoLinesAsync(fileName); if (lines is null || lines.Length != 2 || lines[0].IsNothing() || lines[1].IsNothing()) { return false; @@ -117,8 +117,15 @@ public async Task TasteTestAsync(string fileName) try { - if (!VerifyColumnHeaderLine(lines[0])) return false; - if (!VerifyFirstDataLine(lines[1])) return false; + if (!VerifyColumnHeaderLine(lines[0])) + { + return false; + } + + if (!VerifyFirstDataLine(lines[1])) + { + return false; + } } catch (Exception) { @@ -168,12 +175,7 @@ private TransactionType FetchTransactionType(string[] array, decimal amount) private async Task ReadFirstTwoLinesAsync(string fileName) { var chunk = await ReadTextChunkAsync(fileName); - if (chunk.IsNothing()) - { - return null; - } - - return chunk.SplitLines(2); + return chunk.IsNothing() ? null : chunk.SplitLines(2); } private static bool VerifyColumnHeaderLine(string line) @@ -184,7 +186,7 @@ private static bool VerifyColumnHeaderLine(string line) private bool VerifyFirstDataLine(string line) { - string[] split = line.Split(','); + var split = line.Split(','); var type = this.importUtilities.FetchString(split, 0); if (string.IsNullOrWhiteSpace(type)) { @@ -208,12 +210,7 @@ private bool VerifyFirstDataLine(string line) return false; } - if (split.Length != 9) - { - return false; - } - - return true; + return split.Length == 9; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/AnzVisaStatementImporterV1.cs b/BudgetAnalyser.Engine/Statement/AnzVisaStatementImporterV1.cs index 2af2b237..ad966a42 100644 --- a/BudgetAnalyser.Engine/Statement/AnzVisaStatementImporterV1.cs +++ b/BudgetAnalyser.Engine/Statement/AnzVisaStatementImporterV1.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using BudgetAnalyser.Engine.BankAccount; using JetBrains.Annotations; @@ -33,7 +33,7 @@ public AnzVisaStatementImporterV1([NotNull] BankImportUtilities importUtilities, ArgumentNullException.ThrowIfNull(importUtilities, nameof(importUtilities)); ArgumentNullException.ThrowIfNull(logger, nameof(logger)); ArgumentNullException.ThrowIfNull(readerWriterSelector, nameof(readerWriterSelector)); - + this.importUtilities = importUtilities; this.importUtilities.ConfigureLocale(new CultureInfo("en-NZ")); // ANZ importers are NZ specific at this stage. @@ -77,7 +77,7 @@ public async Task LoadAsync(string fileName, Account account) continue; } - string[] split = line.Split(','); + var split = line.Split(','); var transactionType = FetchTransactionType(split); var transaction = new Transaction { @@ -85,9 +85,9 @@ public async Task LoadAsync(string fileName, Account account) Reference1 = this.importUtilities.FetchString(split, Reference1Index), TransactionType = transactionType, Description = this.importUtilities.FetchString(split, DescriptionIndex), - Date = this.importUtilities.FetchDate(split, DateIndex) + Date = this.importUtilities.FetchDate(split, DateIndex), + Amount = FetchAmount(split, transactionType) }; - transaction.Amount = FetchAmount(split, transactionType); transactions.Add(transaction); } @@ -105,7 +105,7 @@ public async Task LoadAsync(string fileName, Account account) public async Task TasteTestAsync(string fileName) { this.importUtilities.AbortIfFileDoesntExist(fileName); - string[]? lines = await ReadFirstTwoLinesAsync(fileName); + var lines = await ReadFirstTwoLinesAsync(fileName); if (lines is null || lines.Length != 2 || lines[0].IsNothing() || lines[1].IsNothing()) { return false; @@ -113,8 +113,15 @@ public async Task TasteTestAsync(string fileName) try { - if (!VerifyColumnHeaderLine(lines[0])) return false; - if (!VerifyFirstDataLine(lines[1])) return false; + if (!VerifyColumnHeaderLine(lines[0])) + { + return false; + } + + if (!VerifyFirstDataLine(lines[1])) + { + return false; + } } catch (Exception) { @@ -158,7 +165,8 @@ private decimal FetchAmount(string[] array, NamedTransaction transaction) } return amount; - } catch (InvalidDataException ex) + } + catch (InvalidDataException ex) { this.logger.LogError(ex, l => l.Format("Unable to convert provided string to a decimal. Probable format change in bank file.")); throw; @@ -187,11 +195,7 @@ private NamedTransaction FetchTransactionType(string[] array) private async Task ReadFirstTwoLinesAsync(string fileName) { var chunk = await ReadTextChunkAsync(fileName); - if (chunk.IsNothing()) - { - return null; - } - return chunk.SplitLines(2); + return chunk.IsNothing() ? null : chunk.SplitLines(2); } private static bool VerifyColumnHeaderLine(string line) @@ -202,7 +206,7 @@ private static bool VerifyColumnHeaderLine(string line) private bool VerifyFirstDataLine(string line) { - string[] split = line.Split(','); + var split = line.Split(','); var card = this.importUtilities.FetchString(split, Reference1Index); if (card.IsSomething()) { @@ -219,11 +223,7 @@ private bool VerifyFirstDataLine(string line) } var date = this.importUtilities.FetchDate(split, DateIndex); - if (date == DateTime.MinValue) - { - return false; - } - return true; + return date != DateTime.MinValue; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/BankImportUtilities.cs b/BudgetAnalyser.Engine/Statement/BankImportUtilities.cs index fd6b8328..16267dcc 100644 --- a/BudgetAnalyser.Engine/Statement/BankImportUtilities.cs +++ b/BudgetAnalyser.Engine/Statement/BankImportUtilities.cs @@ -80,8 +80,7 @@ internal DateTime FetchDate([NotNull] string[] array, int index) } var stringToParse = array[index]; - DateTime retval; - if (!DateTime.TryParse(stringToParse, this.locale, DateTimeStyles.None, out retval)) + if (!DateTime.TryParse(stringToParse, this.locale, DateTimeStyles.None, out var retval)) { this.logger.LogError(l => "BankImportUtilities: Unable to parse date: " + stringToParse); throw new InvalidDataException("Expected date, but provided data is invalid. " + stringToParse); @@ -103,8 +102,7 @@ internal decimal FetchDecimal([NotNull] string[] array, int index) } var stringToParse = array[index]; - decimal retval; - if (!decimal.TryParse(stringToParse, out retval)) + if (!decimal.TryParse(stringToParse, out var retval)) { this.logger.LogError(l => "BankImportUtilities: Unable to parse decimal: " + stringToParse); throw new InvalidDataException("Expected decimal, but provided data is invalid. " + stringToParse); @@ -127,8 +125,7 @@ internal Guid FetchGuid([NotNull] string[] array, int index) } var stringToParse = array[index]; - Guid result; - if (!Guid.TryParse(stringToParse, out result)) + if (!Guid.TryParse(stringToParse, out var result)) { this.logger.LogError(l => "BankImportUtilities: Unable to parse Guid: " + stringToParse); throw new InvalidDataException("Expected Guid, but provided data is invalid. " + stringToParse); @@ -150,8 +147,7 @@ internal long FetchLong([NotNull] string[] array, int index) } var stringToParse = array[index]; - long retval; - if (!long.TryParse(stringToParse, out retval)) + if (!long.TryParse(stringToParse, out var retval)) { this.logger.LogError(l => "BankImportUtilities: Unable to parse long: " + stringToParse); throw new InvalidDataException("Expected long, but provided data is invalid. " + stringToParse); @@ -175,12 +171,7 @@ internal string FetchString([NotNull] string[] array, int index) var result = array[index].Trim(); var chars = result.ToCharArray(); - if (chars.Length > 0 && chars[0] == '"') - { - return result.Replace("\"", string.Empty); - } - - return result; + return chars.Length > 0 && chars[0] == '"' ? result.Replace("\"", string.Empty) : result; } private static void ThrowIndexOutOfRangeException(string[] array, int index) @@ -188,4 +179,4 @@ private static void ThrowIndexOutOfRangeException(string[] array, int index) throw new UnexpectedIndexException(string.Format(CultureInfo.CurrentCulture, "Index {0} is out of range for array with length {1}.", index, array.Length)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/BankStatementImporterRepository.cs b/BudgetAnalyser.Engine/Statement/BankStatementImporterRepository.cs index dfd4b91f..07f99083 100644 --- a/BudgetAnalyser.Engine/Statement/BankStatementImporterRepository.cs +++ b/BudgetAnalyser.Engine/Statement/BankStatementImporterRepository.cs @@ -70,4 +70,4 @@ public async Task ImportAsync(string fullFileName, Account accou throw new NotSupportedException("The requested file name cannot be loaded. It is not of any known format."); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/CsvOnDiskStatementModelRepositoryV1.cs b/BudgetAnalyser.Engine/Statement/CsvOnDiskStatementModelRepositoryV1.cs index 8c1cfa82..3c60728d 100644 --- a/BudgetAnalyser.Engine/Statement/CsvOnDiskStatementModelRepositoryV1.cs +++ b/BudgetAnalyser.Engine/Statement/CsvOnDiskStatementModelRepositoryV1.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using BudgetAnalyser.Engine.Statement.Data; @@ -41,7 +41,10 @@ public CsvOnDiskStatementModelRepositoryV1( { throw new ArgumentNullException(nameof(mapper)); } - if (readerWriterSelector is null) throw new ArgumentNullException(nameof(readerWriterSelector)); + if (readerWriterSelector is null) + { + throw new ArgumentNullException(nameof(readerWriterSelector)); + } this.importUtilities = importUtilities; this.logger = logger; @@ -81,14 +84,14 @@ public async Task LoadAsync(string storageKey, bool isEncrypted) throw new NotSupportedException("The CSV file is not supported by this version of the Budget Analyser."); } - List allLines = (await ReadLinesAsync(storageKey, isEncrypted)).ToList(); + var allLines = (await ReadLinesAsync(storageKey, isEncrypted)).ToList(); var totalLines = allLines.LongCount(); if (totalLines < 2) { return new StatementModel(this.logger) { StorageKey = storageKey }.LoadTransactions(new List()); } - List transactions = ReadTransactions(totalLines, allLines); + var transactions = ReadTransactions(totalLines, allLines); var transactionSet = CreateTransactionSet(storageKey, allLines, transactions); ValidateChecksumIntegrity(transactionSet); @@ -124,11 +127,9 @@ public async Task SaveAsync(StatementModel model, string storageKey, bool isEncr } var selector = this.readerWriterSelector.SelectReaderWriter(isEncrypted); - using (var stream = selector.CreateWritableStream(storageKey)) - using (var streamWriter = new StreamWriter(stream)) - { - await WriteToStream(transactionSet, streamWriter); - } + await using var stream = selector.CreateWritableStream(storageKey); + await using var streamWriter = new StreamWriter(stream); + await WriteToStream(transactionSet, streamWriter); } protected async Task WriteToStream(TransactionSetDto transactionSet, StreamWriter writer) @@ -191,7 +192,7 @@ protected virtual async Task> ReadLinesAsync(string fileName { var reader = this.readerWriterSelector.SelectReaderWriter(isEncrypted); var textData = await reader.LoadFirstLinesFromDiskAsync(fileName, lines); - string[] firstLines = textData.SplitLines(lines); + var firstLines = textData.SplitLines(lines); return firstLines; } @@ -203,13 +204,8 @@ internal async Task IsStatementModelAsync(string storageKey, bool isEncryp } this.importUtilities.AbortIfFileDoesntExist(storageKey); - List allLines = (await ReadLinesAsync(storageKey, 2, isEncrypted)).ToList(); - if (!VersionCheck(allLines)) - { - return false; - } - - return true; + var allLines = (await ReadLinesAsync(storageKey, 2, isEncrypted)).ToList(); + return VersionCheck(allLines); } private static long CalculateTransactionCheckSum(TransactionSetDto setDto) @@ -217,7 +213,7 @@ private static long CalculateTransactionCheckSum(TransactionSetDto setDto) long txnCheckSum = 37; // prime unchecked { - txnCheckSum *= 397; // also prime + txnCheckSum *= 397; // also prime foreach (var txn in setDto.Transactions) { txnCheckSum += (long)txn.Amount * 100; @@ -236,7 +232,7 @@ private TransactionSetDto CreateTransactionSet(string fileName, List all throw new DataFormatException("The Budget Analyser file does not have a valid header row."); } - string[] headerSplit = header.Split(','); + var headerSplit = header.Split(','); var transactionSet = new TransactionSetDto { Checksum = this.importUtilities.FetchLong(headerSplit, 3), @@ -259,7 +255,7 @@ private List ReadTransactions(long totalLines, List allL continue; } - string[] split = line.Split(','); + var split = line.Split(','); TransactionDto transaction; try { @@ -323,18 +319,13 @@ private void ValidateChecksumIntegrity(TransactionSetDto transactionSet) private static bool VersionCheck(List allLines) { var firstLine = allLines[0]; - string[] split = firstLine.Split(','); + var split = firstLine.Split(','); if (split.Length != 5) { return false; } - if (split[1] != VersionHash) - { - return false; - } - - return true; + return split[1] == VersionHash; } private static void WriteHeader(StreamWriter writer, TransactionSetDto setDto) @@ -344,7 +335,11 @@ private static void WriteHeader(StreamWriter writer, TransactionSetDto setDto) private string SanitiseString(string data, string property) { - if (string.IsNullOrWhiteSpace(data)) return data; + if (string.IsNullOrWhiteSpace(data)) + { + return data; + } + var result = data.Replace(",", string.Empty); if (result.Length != data.Length) { @@ -354,4 +349,4 @@ private string SanitiseString(string data, string property) return result; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.cs b/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.cs index 33163fdf..c13daaf9 100644 --- a/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.cs +++ b/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.cs @@ -6,15 +6,23 @@ namespace BudgetAnalyser.Engine.Statement.Data { [AutoRegisterWithIoC] - internal partial class Mapper_TransactionSetDto_StatementModel + internal partial class MapperTransactionSetDto2StatementModel { private readonly ILogger logger; private readonly IDtoMapper transactionMapper; - public Mapper_TransactionSetDto_StatementModel([NotNull] ILogger logger, [NotNull] IDtoMapper transactionMapper) + public MapperTransactionSetDto2StatementModel([NotNull] ILogger logger, [NotNull] IDtoMapper transactionMapper) { - if (logger is null) throw new ArgumentNullException(nameof(logger)); - if (transactionMapper is null) throw new ArgumentNullException(nameof(transactionMapper)); + if (logger is null) + { + throw new ArgumentNullException(nameof(logger)); + } + + if (transactionMapper is null) + { + throw new ArgumentNullException(nameof(transactionMapper)); + } + this.logger = logger; this.transactionMapper = transactionMapper; } @@ -36,4 +44,4 @@ partial void ToModelPostprocessing(TransactionSetDto dto, ref StatementModel mod model.LoadTransactions(dto.Transactions.Select(t => this.transactionMapper.ToModel(t))); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.generated.cs b/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.generated.cs index 25ec5b08..b8f457ff 100644 --- a/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.generated.cs +++ b/BudgetAnalyser.Engine/Statement/Data/StatementModelToDtoMapper.generated.cs @@ -11,7 +11,7 @@ namespace BudgetAnalyser.Engine.Statement.Data { [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 1:54:58 AM UTC")] - internal partial class Mapper_TransactionSetDto_StatementModel : IDtoMapper + internal partial class MapperTransactionSetDto2StatementModel : IDtoMapper { public virtual StatementModel ToModel(TransactionSetDto dto) @@ -54,7 +54,7 @@ public virtual TransactionSetDto ToDto(StatementModel model) } // End Class [GeneratedCode("1.0", "Tangy Fruit Mapper 2/01/2016 1:41:11 AM UTC")] - internal partial class Mapper_TransactionDto_Transaction : IDtoMapper + internal partial class MapperTransactionDto2Transaction : IDtoMapper { public virtual Transaction ToModel(TransactionDto dto) diff --git a/BudgetAnalyser.Engine/Statement/Data/TransactionDto.cs b/BudgetAnalyser.Engine/Statement/Data/TransactionDto.cs index 7b750637..25d83d45 100644 --- a/BudgetAnalyser.Engine/Statement/Data/TransactionDto.cs +++ b/BudgetAnalyser.Engine/Statement/Data/TransactionDto.cs @@ -58,4 +58,4 @@ public class TransactionDto /// public string TransactionType { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/Data/TransactionSetDto.cs b/BudgetAnalyser.Engine/Statement/Data/TransactionSetDto.cs index a8dd3b68..582ba695 100644 --- a/BudgetAnalyser.Engine/Statement/Data/TransactionSetDto.cs +++ b/BudgetAnalyser.Engine/Statement/Data/TransactionSetDto.cs @@ -38,4 +38,4 @@ public class TransactionSetDto /// public string VersionHash { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs b/BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs index 37e727c9..5af59de8 100644 --- a/BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs +++ b/BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs @@ -6,17 +6,29 @@ namespace BudgetAnalyser.Engine.Statement.Data { [AutoRegisterWithIoC] - internal partial class Mapper_TransactionDto_Transaction + internal partial class MapperTransactionDto2Transaction { private readonly IAccountTypeRepository accountRepo; private readonly IBudgetBucketRepository bucketRepo; private readonly ITransactionTypeRepository transactionTypeRepo; - public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo) + public MapperTransactionDto2Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo) { - if (accountRepo is null) throw new ArgumentNullException(nameof(accountRepo)); - if (bucketRepo is null) throw new ArgumentNullException(nameof(bucketRepo)); - if (transactionTypeRepo is null) throw new ArgumentNullException(nameof(transactionTypeRepo)); + if (accountRepo is null) + { + throw new ArgumentNullException(nameof(accountRepo)); + } + + if (bucketRepo is null) + { + throw new ArgumentNullException(nameof(bucketRepo)); + } + + if (transactionTypeRepo is null) + { + throw new ArgumentNullException(nameof(transactionTypeRepo)); + } + this.accountRepo = accountRepo; this.bucketRepo = bucketRepo; this.transactionTypeRepo = transactionTypeRepo; @@ -36,4 +48,4 @@ partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model) model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/IBankStatementImporter.cs b/BudgetAnalyser.Engine/Statement/IBankStatementImporter.cs index 3da3b41a..795a7318 100644 --- a/BudgetAnalyser.Engine/Statement/IBankStatementImporter.cs +++ b/BudgetAnalyser.Engine/Statement/IBankStatementImporter.cs @@ -29,4 +29,4 @@ public interface IBankStatementImporter /// Task TasteTestAsync(string fileName); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/IBankStatementImporterRepository.cs b/BudgetAnalyser.Engine/Statement/IBankStatementImporterRepository.cs index 0a0eab72..26319aa8 100644 --- a/BudgetAnalyser.Engine/Statement/IBankStatementImporterRepository.cs +++ b/BudgetAnalyser.Engine/Statement/IBankStatementImporterRepository.cs @@ -22,4 +22,4 @@ public interface IBankStatementImporterRepository /// Task ImportAsync(string fullFileName, Account account); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/IStatementRepository.cs b/BudgetAnalyser.Engine/Statement/IStatementRepository.cs index fbf48f69..8ddbf513 100644 --- a/BudgetAnalyser.Engine/Statement/IStatementRepository.cs +++ b/BudgetAnalyser.Engine/Statement/IStatementRepository.cs @@ -62,4 +62,4 @@ Task ImportBankStatementAsync( /// A boolean to indicate if the data file should be encrypted or not. Task SaveAsync(StatementModel statementModel, bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/ITransactionTypeRepository.cs b/BudgetAnalyser.Engine/Statement/ITransactionTypeRepository.cs index 949a444a..c65f691a 100644 --- a/BudgetAnalyser.Engine/Statement/ITransactionTypeRepository.cs +++ b/BudgetAnalyser.Engine/Statement/ITransactionTypeRepository.cs @@ -10,4 +10,4 @@ public interface ITransactionTypeRepository /// TransactionType GetOrCreateNew(string name); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/IVersionedStatementModelRepository.cs b/BudgetAnalyser.Engine/Statement/IVersionedStatementModelRepository.cs index 0a9fd0f1..5d609e6f 100644 --- a/BudgetAnalyser.Engine/Statement/IVersionedStatementModelRepository.cs +++ b/BudgetAnalyser.Engine/Statement/IVersionedStatementModelRepository.cs @@ -53,4 +53,4 @@ public interface IVersionedStatementModelRepository /// Task SaveAsync([NotNull] StatementModel model, [NotNull] string storageKey, bool isEncrypted); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/InMemoryTransactionTypeRepository.cs b/BudgetAnalyser.Engine/Statement/InMemoryTransactionTypeRepository.cs index d148a8f9..e7364f95 100644 --- a/BudgetAnalyser.Engine/Statement/InMemoryTransactionTypeRepository.cs +++ b/BudgetAnalyser.Engine/Statement/InMemoryTransactionTypeRepository.cs @@ -17,12 +17,7 @@ public class InMemoryTransactionTypeRepository : ITransactionTypeRepository /// public TransactionType GetOrCreateNew(string name) { - if (string.IsNullOrWhiteSpace(name)) - { - return null; - } - - return this.transactionTypes.GetOrAdd(name, n => new NamedTransaction(n)); + return string.IsNullOrWhiteSpace(name) ? null : this.transactionTypes.GetOrAdd(name, n => new NamedTransaction(n)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/NamedTransaction.cs b/BudgetAnalyser.Engine/Statement/NamedTransaction.cs index f66e49ed..131d0577 100644 --- a/BudgetAnalyser.Engine/Statement/NamedTransaction.cs +++ b/BudgetAnalyser.Engine/Statement/NamedTransaction.cs @@ -49,4 +49,4 @@ public override int GetHashCode() return this.name.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/PersistentApplicationStateFiltersApplicationState.cs b/BudgetAnalyser.Engine/Statement/PersistentApplicationStateFiltersApplicationState.cs index 747d7ecb..2572f1a2 100644 --- a/BudgetAnalyser.Engine/Statement/PersistentApplicationStateFiltersApplicationState.cs +++ b/BudgetAnalyser.Engine/Statement/PersistentApplicationStateFiltersApplicationState.cs @@ -24,4 +24,4 @@ public class PersistentFiltersApplicationState : IPersistentApplicationStateObje /// public int LoadSequence => 50; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/StatementApplicationState.cs b/BudgetAnalyser.Engine/Statement/StatementApplicationState.cs index dbecab39..38605ec7 100644 --- a/BudgetAnalyser.Engine/Statement/StatementApplicationState.cs +++ b/BudgetAnalyser.Engine/Statement/StatementApplicationState.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.Persistence; +using BudgetAnalyser.Engine.Persistence; namespace BudgetAnalyser.Engine.Statement { @@ -19,4 +19,4 @@ public class StatementApplicationState : IPersistentApplicationStateObject /// public bool? SortByBucket { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/StatementModel.cs b/BudgetAnalyser.Engine/Statement/StatementModel.cs index 1ee987ce..d064cceb 100644 --- a/BudgetAnalyser.Engine/Statement/StatementModel.cs +++ b/BudgetAnalyser.Engine/Statement/StatementModel.cs @@ -1,4 +1,4 @@ -using System.ComponentModel; +using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; @@ -70,7 +70,7 @@ public StatementModel([NotNull] ILogger logger) /// public IEnumerable AllTransactions { - get { return this.doNotUseAllTransactions; } + get => this.doNotUseAllTransactions; private set { @@ -84,7 +84,7 @@ private set /// public int DurationInMonths { - get { return this.doNotUseDurationInMonths; } + get => this.doNotUseDurationInMonths; private set { @@ -113,7 +113,7 @@ private set /// public IEnumerable Transactions { - get { return this.doNotUseTransactions; } + get => this.doNotUseTransactions; private set { @@ -158,7 +158,7 @@ public void Dispose() /// The list of transactions to use to determine duration. public static int CalculateDuration(GlobalFilterCriteria criteria, IEnumerable transactions) { - List list = transactions.ToList(); + var list = transactions.ToList(); DateTime minDate = DateTime.MaxValue, maxDate = DateTime.MinValue; if (criteria is not null && !criteria.Cleared) @@ -233,7 +233,7 @@ internal virtual void Filter(GlobalFilterCriteria criteria) return; } - IEnumerable query = BaseFilterQuery(criteria); + var query = BaseFilterQuery(criteria); Transactions = query.ToList(); DurationInMonths = CalculateDuration(criteria, Transactions); @@ -251,16 +251,7 @@ internal virtual StatementModel LoadTransactions(IEnumerable transa ThrowIfDisposed(); UnsubscribeToTransactionChangedEvents(); this.changeHash = Guid.NewGuid(); - List listOfTransactions; - if (transactions is null) - { - listOfTransactions = new List(); - } - else - { - listOfTransactions = transactions.OrderBy(t => t.Date).ToList(); - } - + var listOfTransactions = transactions is null ? new List() : transactions.OrderBy(t => t.Date).ToList(); Transactions = listOfTransactions; AllTransactions = Transactions; if (listOfTransactions.Any()) @@ -294,7 +285,7 @@ internal virtual StatementModel Merge([NotNull] StatementModel additionalModel) StorageKey = StorageKey }; - List mergedTransactions = AllTransactions.ToList().Merge(additionalModel.AllTransactions).ToList(); + var mergedTransactions = AllTransactions.ToList().Merge(additionalModel.AllTransactions).ToList(); combinedModel.LoadTransactions(mergedTransactions); return combinedModel; } @@ -377,7 +368,7 @@ internal virtual void SplitTransaction( { AllTransactions = new List(); } - List mergedTransactions = + var mergedTransactions = AllTransactions.ToList().Merge(new[] { splinterTransaction1, splinterTransaction2 }).ToList(); AllTransactions = mergedTransactions; splinterTransaction1.PropertyChanged += OnTransactionPropertyChanged; @@ -398,7 +389,7 @@ internal IEnumerable> ValidateAgainstDuplicates(Date minDate ??= DateTime.MinValue; maxDate ??= DateTime.MaxValue; - List> query = + var query = Transactions .Where(t => t.Date >= minDate && t.Date <= maxDate) .GroupBy(t => t.GetEqualityHashCode(), t => t) @@ -425,7 +416,7 @@ private IEnumerable BaseFilterQuery(GlobalFilterCriteria criteria) return AllTransactions.ToList(); } - IEnumerable query = AllTransactions; + var query = AllTransactions; if (criteria.BeginDate is not null) { query = AllTransactions.Where(t => t.Date >= criteria.BeginDate.Value); @@ -498,4 +489,4 @@ private void UpdateDuration() Dispose(false); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/StatementModelCheckSumException.cs b/BudgetAnalyser.Engine/Statement/StatementModelCheckSumException.cs index 116319eb..24de2bc5 100644 --- a/BudgetAnalyser.Engine/Statement/StatementModelCheckSumException.cs +++ b/BudgetAnalyser.Engine/Statement/StatementModelCheckSumException.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Statement @@ -63,4 +63,4 @@ public StatementModelChecksumException(string checksum, string message, Exceptio /// public string FileChecksum { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/StatementRepository.cs b/BudgetAnalyser.Engine/Statement/StatementRepository.cs index 8f951c9c..806c9ce5 100644 --- a/BudgetAnalyser.Engine/Statement/StatementRepository.cs +++ b/BudgetAnalyser.Engine/Statement/StatementRepository.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using BudgetAnalyser.Engine.BankAccount; using JetBrains.Annotations; using NotNull = JetBrains.Annotations.NotNullAttribute; @@ -53,22 +53,16 @@ public async Task ImportBankStatementAsync( throw new ArgumentNullException(nameof(storageKey)); } - if (account is null) - { - throw new ArgumentNullException(nameof(account)); - } - - return await this.importerRepository.ImportAsync(storageKey, account); + return account is null + ? throw new ArgumentNullException(nameof(account)) + : await this.importerRepository.ImportAsync(storageKey, account); } public async Task LoadAsync(string storageKey, bool isEncrypted) { - if (storageKey is null) - { - throw new FileNotFoundException("storageKey"); - } - - return await this.statementModelRepository.LoadAsync(storageKey, isEncrypted); + return storageKey is null + ? throw new FileNotFoundException("storageKey") + : await this.statementModelRepository.LoadAsync(storageKey, isEncrypted); } public async Task SaveAsync([NotNull] StatementModel statementModel, bool isEncrypted) @@ -81,4 +75,4 @@ public async Task SaveAsync([NotNull] StatementModel statementModel, bool isEncr await this.statementModelRepository.SaveAsync(statementModel, statementModel.StorageKey, isEncrypted); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/Transaction.cs b/BudgetAnalyser.Engine/Statement/Transaction.cs index 2c6f72c1..5b72c57d 100644 --- a/BudgetAnalyser.Engine/Statement/Transaction.cs +++ b/BudgetAnalyser.Engine/Statement/Transaction.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -48,7 +48,7 @@ public Transaction() /// public Account Account { - get { return this.doNotUseAccount; } + get => this.doNotUseAccount; set { this.doNotUseAccount = value; @@ -61,7 +61,7 @@ public Account Account /// public decimal Amount { - get { return this.doNotUseAmount; } + get => this.doNotUseAmount; set { this.doNotUseAmount = value; @@ -78,7 +78,7 @@ public decimal Amount /// public BudgetBucket BudgetBucket { - get { return this.budgetBucket; } + get => this.budgetBucket; set { @@ -97,7 +97,7 @@ public BudgetBucket BudgetBucket /// public DateTime Date { - get { return this.doNotUseDate; } + get => this.doNotUseDate; set { this.doNotUseDate = value; @@ -110,7 +110,7 @@ public DateTime Date /// public string Description { - get { return this.doNotUseDescription; } + get => this.doNotUseDescription; set { this.doNotUseDescription = value; @@ -137,7 +137,7 @@ public string Description /// public string Reference1 { - get { return this.doNotUseReference1; } + get => this.doNotUseReference1; set { this.doNotUseReference1 = value; @@ -150,7 +150,7 @@ public string Reference1 /// public string Reference2 { - get { return this.doNotUseReference2; } + get => this.doNotUseReference2; set { this.doNotUseReference2 = value; @@ -163,7 +163,7 @@ public string Reference2 /// public string Reference3 { - get { return this.doNotUseReference3; } + get => this.doNotUseReference3; set { this.doNotUseReference3 = value; @@ -176,7 +176,7 @@ public string Reference3 /// public TransactionType? TransactionType { - get { return this.doNotUseTransactionType; } + get => this.doNotUseTransactionType; set { this.doNotUseTransactionType = value; @@ -208,18 +208,12 @@ public Transaction Clone() /// public int CompareTo(object obj) { - var otherTransaction = obj as Transaction; - if (otherTransaction is null) - { - return 1; - } - - return Date.CompareTo(otherTransaction.Date); + return obj is not Transaction otherTransaction ? 1 : Date.CompareTo(otherTransaction.Date); } /// /// Get a hash code that will indicate value based equivalence with another instance of . - /// cannot be used because it is intended to show instance reference equivalence. It + /// cannot be used because it is intended to show instance reference equivalence. It /// will give a different value (and it should) for every instance. If overriden changing hashcodes will cause problems /// with /// UI controls such as ListBox. @@ -288,4 +282,4 @@ private void OnPropertyChanged([CallerMemberName] string propertyName = null) handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/TransactionListExtension.cs b/BudgetAnalyser.Engine/Statement/TransactionListExtension.cs index 6f145e26..955ecca9 100644 --- a/BudgetAnalyser.Engine/Statement/TransactionListExtension.cs +++ b/BudgetAnalyser.Engine/Statement/TransactionListExtension.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; namespace BudgetAnalyser.Engine.Statement @@ -8,9 +8,9 @@ internal static class TransactionListExtension public static IEnumerable Merge(this IEnumerable instance, IEnumerable additionalTransactions) { - List result = instance.ToList(); + var result = instance.ToList(); result.AddRange(additionalTransactions); return result.OrderBy(t => t.Date); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/TransactionType.cs b/BudgetAnalyser.Engine/Statement/TransactionType.cs index 5e3a29c9..af0ae1dc 100644 --- a/BudgetAnalyser.Engine/Statement/TransactionType.cs +++ b/BudgetAnalyser.Engine/Statement/TransactionType.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace BudgetAnalyser.Engine.Statement { @@ -14,14 +14,14 @@ public abstract class TransactionType public abstract string Name { get; } /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// public override string ToString() { return Name; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/TransactionsAlreadyImportedException.cs b/BudgetAnalyser.Engine/Statement/TransactionsAlreadyImportedException.cs index 49573bd5..f5fd20db 100644 --- a/BudgetAnalyser.Engine/Statement/TransactionsAlreadyImportedException.cs +++ b/BudgetAnalyser.Engine/Statement/TransactionsAlreadyImportedException.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Statement @@ -35,4 +35,4 @@ public TransactionsAlreadyImportedException(string message, Exception innerExcep { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/UnexpectedIndexException.cs b/BudgetAnalyser.Engine/Statement/UnexpectedIndexException.cs index 92a1a096..50149d5a 100644 --- a/BudgetAnalyser.Engine/Statement/UnexpectedIndexException.cs +++ b/BudgetAnalyser.Engine/Statement/UnexpectedIndexException.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Statement @@ -34,4 +34,4 @@ public UnexpectedIndexException(string message, Exception innerException) : base { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Statement/WestpacAccountStatementImporterV1.cs b/BudgetAnalyser.Engine/Statement/WestpacAccountStatementImporterV1.cs index 84de92ce..39e88a30 100644 --- a/BudgetAnalyser.Engine/Statement/WestpacAccountStatementImporterV1.cs +++ b/BudgetAnalyser.Engine/Statement/WestpacAccountStatementImporterV1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -44,7 +44,10 @@ public WestpacAccountStatementImporterV1([NotNull] BankImportUtilities importUti { throw new ArgumentNullException(nameof(logger)); } - if (readerWriterSelector is null) throw new ArgumentNullException(nameof(readerWriterSelector)); + if (readerWriterSelector is null) + { + throw new ArgumentNullException(nameof(readerWriterSelector)); + } this.importUtilities = importUtilities; this.logger = logger; @@ -88,7 +91,7 @@ public async Task LoadAsync(string fileName, Account account) continue; } - string[] split = line.Split(','); + var split = line.Split(','); var transaction = new Transaction { Account = account, @@ -120,7 +123,7 @@ public async Task TasteTestAsync(string fileName) { this.importUtilities.AbortIfFileDoesntExist(fileName); - string[] lines = await ReadFirstTwoLinesAsync(fileName); + var lines = await ReadFirstTwoLinesAsync(fileName); if (lines is null || lines.Length != 2 || lines[0].IsNothing() || lines[1].IsNothing()) { return false; @@ -128,8 +131,15 @@ public async Task TasteTestAsync(string fileName) try { - if (!VerifyColumnHeaderLine(lines[0])) return false; - if (!VerifyFirstDataLine(lines[1])) return false; + if (!VerifyColumnHeaderLine(lines[0])) + { + return false; + } + + if (!VerifyFirstDataLine(lines[1])) + { + return false; + } } catch (Exception) { @@ -179,12 +189,7 @@ private TransactionType FetchTransactionType(string[] array, decimal amount) private async Task ReadFirstTwoLinesAsync(string fileName) { var chunk = await ReadTextChunkAsync(fileName); - if (chunk.IsNothing()) - { - return null; - } - - return chunk.SplitLines(2); + return chunk.IsNothing() ? null : chunk.SplitLines(2); } private static bool VerifyColumnHeaderLine(string line) @@ -195,7 +200,7 @@ private static bool VerifyColumnHeaderLine(string line) private bool VerifyFirstDataLine(string line) { - string[] split = line.Split(','); + var split = line.Split(','); var type = this.importUtilities.FetchString(split, TransactionTypeIndex); if (string.IsNullOrWhiteSpace(type)) { @@ -219,12 +224,7 @@ private bool VerifyFirstDataLine(string line) return false; } - if (split.Length != 7) - { - return false; - } - - return true; + return split.Length == 7; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/StringExtension.cs b/BudgetAnalyser.Engine/StringExtension.cs index 01b751d1..54201d9e 100644 --- a/BudgetAnalyser.Engine/StringExtension.cs +++ b/BudgetAnalyser.Engine/StringExtension.cs @@ -32,12 +32,7 @@ public static string AnOrA(this string instance, bool properCase = false) return "A"; } - if (useAn) - { - return "an"; - } - - return "a"; + return useAn ? "an" : "a"; } /// @@ -67,10 +62,13 @@ public static bool IsSomething(this string instance) public static string[] SplitLines(this string instance, int numberOfLines = 0) { ArgumentNullException.ThrowIfNull(instance); - if (numberOfLines < 0) throw new ArgumentOutOfRangeException(nameof(numberOfLines), "Number of Lines must be a positive integer."); + if (numberOfLines < 0) + { + throw new ArgumentOutOfRangeException(nameof(numberOfLines), "Number of Lines must be a positive integer."); + } - string[] split = instance.Split('\r', '\n'); - IEnumerable query = split.Where(l => l.Length > 0); + var split = instance.Split('\r', '\n'); + var query = split.Where(l => l.Length > 0); if (numberOfLines > 0) { query = query.Take(numberOfLines); @@ -95,12 +93,7 @@ public static string Truncate(this string instance, int truncateToLength, bool u return instance; } - if (useEllipses) - { - return instance.Substring(0, truncateToLength - 1) + "…"; - } - - return instance.Substring(0, truncateToLength); + return useEllipses ? instance.Substring(0, truncateToLength - 1) + "…" : instance.Substring(0, truncateToLength); } /// @@ -119,12 +112,9 @@ public static string TruncateLeft(this string instance, int truncateToLength, bo return instance; } - if (useEllipses) - { - return "…" + instance.Substring(instance.Length - truncateToLength + 1, truncateToLength - 1); - } - - return instance.Substring(instance.Length - truncateToLength, truncateToLength); + return useEllipses + ? "…" + instance.Substring(instance.Length - truncateToLength + 1, truncateToLength - 1) + : instance.Substring(instance.Length - truncateToLength, truncateToLength); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/TaskExtension.cs b/BudgetAnalyser.Engine/TaskExtension.cs index fb0a9d97..47d052c7 100644 --- a/BudgetAnalyser.Engine/TaskExtension.cs +++ b/BudgetAnalyser.Engine/TaskExtension.cs @@ -17,4 +17,4 @@ public static Task ContinueWhenAllTasksComplete([NotNull] this IEnumerable return Task.WhenAll(instance); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/TimespanExtension.cs b/BudgetAnalyser.Engine/TimespanExtension.cs index 4aaf37bd..1f63e2ee 100644 --- a/BudgetAnalyser.Engine/TimespanExtension.cs +++ b/BudgetAnalyser.Engine/TimespanExtension.cs @@ -23,4 +23,4 @@ public static TimeSpan Seconds(this long instance) return TimeSpan.FromSeconds(instance); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ToDo.cs b/BudgetAnalyser.Engine/ToDo.cs index df7a7893..387eeb1c 100644 --- a/BudgetAnalyser.Engine/ToDo.cs +++ b/BudgetAnalyser.Engine/ToDo.cs @@ -2,4 +2,4 @@ { // TODO Test creation of files using default names - folder storage is different in UWP. No access to the folder where the app is executing. Windows.Storage.ApplicationData.Current.LocalFolder // TODO Highly suspicious of reflection and how this will behave in UWP - see BudgetAnalyser.Engine.rd.xml -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/ValidationWarningException.cs b/BudgetAnalyser.Engine/ValidationWarningException.cs index 9a6a6d49..9848b8d4 100644 --- a/BudgetAnalyser.Engine/ValidationWarningException.cs +++ b/BudgetAnalyser.Engine/ValidationWarningException.cs @@ -1,4 +1,4 @@ -using System; +using System; using JetBrains.Annotations; namespace BudgetAnalyser.Engine @@ -35,4 +35,4 @@ public ValidationWarningException(string message, Exception innerException) { } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs b/BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs index 888f1a35..67e52d86 100644 --- a/BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs @@ -60,4 +60,4 @@ public override void Update(params object[] input) ToolTip = this.disabledToolTip; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/CurrentFileWidget.cs b/BudgetAnalyser.Engine/Widgets/CurrentFileWidget.cs index 34c7c394..3e64df0c 100644 --- a/BudgetAnalyser.Engine/Widgets/CurrentFileWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/CurrentFileWidget.cs @@ -38,8 +38,7 @@ public override void Update([NotNull] params object[] input) throw new ArgumentNullException(nameof(input)); } - var appDb = input[0] as ApplicationDatabase; - if (appDb is null || appDb.FileName.IsNothing()) + if (input[0] is not ApplicationDatabase appDb || appDb.FileName.IsNothing()) { ColourStyleName = WidgetWarningStyle; DetailedText = "Open"; @@ -67,12 +66,7 @@ private static string ShortenFileName([NotNull] string fileName) var proposed = Path.GetFileName(fileName); var drive = Path.GetPathRoot(fileName); - if (proposed.Length < 30) - { - return drive + "...\\" + proposed; - } - - return drive + "...\\" + proposed.Substring(proposed.Length - 30); + return proposed.Length < 30 ? drive + "...\\" + proposed : drive + "...\\" + proposed.Substring(proposed.Length - 30); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/DateFilterWidget.cs b/BudgetAnalyser.Engine/Widgets/DateFilterWidget.cs index fa040455..05cb03d7 100644 --- a/BudgetAnalyser.Engine/Widgets/DateFilterWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/DateFilterWidget.cs @@ -47,7 +47,7 @@ public override void Update([NotNull] params object[] input) return; } - var criteria = (GlobalFilterCriteria) input[0]; + var criteria = (GlobalFilterCriteria)input[0]; if (criteria.Cleared) { NoDateFilterApplied(); @@ -78,4 +78,4 @@ private void NoDateFilterApplied() ColourStyleName = WidgetWarningStyle; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/DaysSinceLastImport.cs b/BudgetAnalyser.Engine/Widgets/DaysSinceLastImport.cs index b3c5aa34..b67557ad 100644 --- a/BudgetAnalyser.Engine/Widgets/DaysSinceLastImport.cs +++ b/BudgetAnalyser.Engine/Widgets/DaysSinceLastImport.cs @@ -42,7 +42,7 @@ public override void Update([NotNull] params object[] input) } Enabled = true; - var statement = (StatementModel) input[0]; + var statement = (StatementModel)input[0]; var days = Convert.ToInt32(DateTime.Today.Subtract(statement.LastImport).TotalDays); if (days < 0) { @@ -52,14 +52,7 @@ public override void Update([NotNull] params object[] input) LargeNumber = days > 99 ? "99+" : days.ToString(CultureInfo.CurrentCulture); ToolTip = string.Format(CultureInfo.CurrentCulture, "It's been {0} days since new transactions have been imported.", LargeNumber); - if (days >= 7) - { - ColourStyleName = WidgetWarningStyle; - } - else - { - ColourStyleName = WidgetStandardStyle; - } + ColourStyleName = days >= 7 ? WidgetWarningStyle : WidgetStandardStyle; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/DisusedMatchingRuleWidget.cs b/BudgetAnalyser.Engine/Widgets/DisusedMatchingRuleWidget.cs index 195d5600..36e14ad4 100644 --- a/BudgetAnalyser.Engine/Widgets/DisusedMatchingRuleWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/DisusedMatchingRuleWidget.cs @@ -59,7 +59,7 @@ public override void Update(params object[] input) } Enabled = true; - var ruleService = (ITransactionRuleService) input[0]; + var ruleService = (ITransactionRuleService)input[0]; if (ruleService is null) { @@ -68,19 +68,12 @@ public override void Update(params object[] input) } CutOffDate = DateTime.Today.AddMonths(-18); - List rulesList = QueryRules(ruleService.MatchingRules).ToList(); + var rulesList = QueryRules(ruleService.MatchingRules).ToList(); DisusedMatchingRules = rulesList; var count = rulesList.Count(); LargeNumber = count.ToString(); ToolTip = $"{count}/{ruleService.MatchingRules.Count()} Rules that have not been used for more than a year."; - if (count >= 20) - { - ColourStyleName = WidgetWarningStyle; - } - else - { - ColourStyleName = WidgetStandardStyle; - } + ColourStyleName = count >= 20 ? WidgetWarningStyle : WidgetStandardStyle; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/EncryptWidget.cs b/BudgetAnalyser.Engine/Widgets/EncryptWidget.cs index 2fd468f7..06c882c0 100644 --- a/BudgetAnalyser.Engine/Widgets/EncryptWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/EncryptWidget.cs @@ -37,17 +37,14 @@ public override void Update([NotNull] params object[] input) throw new ArgumentNullException(nameof(input)); } - var newAppDb = (ApplicationDatabase) input[0]; - if (newAppDb is null) - { - this.appDb = null; - } - else + var newAppDb = (ApplicationDatabase)input[0]; + this.appDb = newAppDb is null ? null : newAppDb; + + if (this.appDb is null) { - this.appDb = newAppDb; + return; } - if (this.appDb is null) return; WidgetActivated(); } @@ -56,7 +53,11 @@ public override void Update([NotNull] params object[] input) /// public void WidgetActivated() { - if (this.appDb is null) return; + if (this.appDb is null) + { + return; + } + Enabled = true; if (this.appDb.IsEncrypted) { @@ -72,4 +73,4 @@ public void WidgetActivated() } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/FixedBudgetMonitorWidget.cs b/BudgetAnalyser.Engine/Widgets/FixedBudgetMonitorWidget.cs index 76f62c4e..a6a582e3 100644 --- a/BudgetAnalyser.Engine/Widgets/FixedBudgetMonitorWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/FixedBudgetMonitorWidget.cs @@ -42,7 +42,7 @@ public FixedBudgetMonitorWidget() /// public string BucketCode { - get { return this.doNotUseBucketCode; } + get => this.doNotUseBucketCode; set { this.doNotUseBucketCode = value; @@ -56,7 +56,7 @@ public string BucketCode /// public string Id { - get { return this.doNotUseId; } + get => this.doNotUseId; set { this.doNotUseId = value; @@ -101,8 +101,8 @@ public override void Update([NotNull] params object[] input) return; } - Statement = (StatementModel) input[0]; - this.bucketRepository = (IBudgetBucketRepository) input[1]; + Statement = (StatementModel)input[0]; + this.bucketRepository = (IBudgetBucketRepository)input[1]; if (!this.bucketRepository.IsValidCode(BucketCode)) { @@ -119,7 +119,7 @@ public override void Update([NotNull] params object[] input) } Enabled = true; - var bucket = (FixedBudgetProjectBucket) this.bucketRepository.GetByCode(BucketCode); + var bucket = (FixedBudgetProjectBucket)this.bucketRepository.GetByCode(BucketCode); var totalBudget = bucket.FixedBudgetAmount; Maximum = Convert.ToDouble(totalBudget); @@ -134,14 +134,7 @@ public override void Update([NotNull] params object[] input) remainingBudget, totalSpend); DetailedText = string.Format(CultureInfo.CurrentCulture, "{0} Project", bucket.SubCode); - if (remainingBudget < 0.1M * totalBudget) - { - ColourStyleName = WidgetWarningStyle; - } - else - { - ColourStyleName = this.standardStyle; - } + ColourStyleName = remainingBudget < 0.1M * totalBudget ? WidgetWarningStyle : this.standardStyle; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/IUserDefinedWidget.cs b/BudgetAnalyser.Engine/Widgets/IUserDefinedWidget.cs index c21d0bd9..5cbbf263 100644 --- a/BudgetAnalyser.Engine/Widgets/IUserDefinedWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/IUserDefinedWidget.cs @@ -31,4 +31,4 @@ public interface IUserDefinedWidget /// void Initialise(MultiInstanceWidgetState state, ILogger logger); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/IWidgetRepository.cs b/BudgetAnalyser.Engine/Widgets/IWidgetRepository.cs index b8095e9a..7415a219 100644 --- a/BudgetAnalyser.Engine/Widgets/IWidgetRepository.cs +++ b/BudgetAnalyser.Engine/Widgets/IWidgetRepository.cs @@ -28,4 +28,4 @@ public interface IWidgetRepository /// void Remove(IUserDefinedWidget widget); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/IWidgetWithAdditionalImage.cs b/BudgetAnalyser.Engine/Widgets/IWidgetWithAdditionalImage.cs index 88ac40f3..4cc491a2 100644 --- a/BudgetAnalyser.Engine/Widgets/IWidgetWithAdditionalImage.cs +++ b/BudgetAnalyser.Engine/Widgets/IWidgetWithAdditionalImage.cs @@ -15,4 +15,4 @@ public interface IWidgetWithAdditionalImage : INotifyPropertyChanged [UsedImplicitly] string ImageResourceName2 { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/MultiInstanceWidgetState.cs b/BudgetAnalyser.Engine/Widgets/MultiInstanceWidgetState.cs index 1bcd34ea..c4c9850d 100644 --- a/BudgetAnalyser.Engine/Widgets/MultiInstanceWidgetState.cs +++ b/BudgetAnalyser.Engine/Widgets/MultiInstanceWidgetState.cs @@ -15,4 +15,4 @@ public class MultiInstanceWidgetState : WidgetPersistentState /// public string Id { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/NewFileWidget.cs b/BudgetAnalyser.Engine/Widgets/NewFileWidget.cs index 86ea7977..4c85c5fa 100644 --- a/BudgetAnalyser.Engine/Widgets/NewFileWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/NewFileWidget.cs @@ -41,10 +41,9 @@ public override void Update([NotNull] params object[] input) return; } - var appDb = input[0] as ApplicationDatabase; ToolTip = "Create a new Budget Analyser File."; DetailedText = "Create new"; - ColourStyleName = appDb is null ? WidgetWarningStyle : WidgetStandardStyle; + ColourStyleName = input[0] is not ApplicationDatabase appDb ? WidgetWarningStyle : WidgetStandardStyle; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/OverspentWarning.cs b/BudgetAnalyser.Engine/Widgets/OverspentWarning.cs index ea17478d..1a62cc09 100644 --- a/BudgetAnalyser.Engine/Widgets/OverspentWarning.cs +++ b/BudgetAnalyser.Engine/Widgets/OverspentWarning.cs @@ -110,7 +110,7 @@ public override void Update([NotNull] params object[] input) Enabled = true; this.logger.LogInfo(l => l.Format("Using this LedgerEntryLine: {0}", ledgerLine?.Date)); - IDictionary currentLedgerBalances = ledgerCalculator.CalculateCurrentPeriodLedgerBalances(ledgerLine, filter, statement); + var currentLedgerBalances = ledgerCalculator.CalculateCurrentPeriodLedgerBalances(ledgerLine, filter, statement); this.logger.LogInfo(l => { var builder = new StringBuilder(); @@ -132,7 +132,7 @@ public override void Update([NotNull] params object[] input) LargeNumber = warnings.ToString(CultureInfo.CurrentCulture); var builder = new StringBuilder(); OverSpentSummary = currentLedgerBalances.Where(kvp => kvp.Value < -Tolerance).OrderBy(kvp => kvp.Key); - foreach (KeyValuePair ledger in OverSpentSummary) + foreach (var ledger in OverSpentSummary) { builder.AppendFormat(CultureInfo.CurrentCulture, "{0} is overspent by {1:C}", ledger.Key, ledger.Value); builder.AppendLine(); @@ -158,7 +158,7 @@ private int SearchForOtherNonLedgerBookOverspentBuckets( IDictionary currentLedgerBalances) { var warnings = 0; - List transactions = statement.Transactions.Where(t => t.Date >= inclBeginDate && t.Date <= inclEndDate).ToList(); + var transactions = statement.Transactions.Where(t => t.Date >= inclBeginDate && t.Date <= inclEndDate).ToList(); this.logger.LogInfo(l => l.Format("SearchForOtherNonLedgerBookOverSpentBuckets: {0} statement transactions found.", transactions.Count())); foreach (var expense in budget.Model.Expenses.Where(e => e.Bucket is BillToPayExpenseBucket)) { @@ -181,4 +181,4 @@ private int SearchForOtherNonLedgerBookOverspentBuckets( this.logger.LogInfo(l => l.Format("{0} warnings found for non-LedgerBook buckets.", warnings)); return warnings; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/ProgressBarWidget.cs b/BudgetAnalyser.Engine/Widgets/ProgressBarWidget.cs index e79cab4d..5f36c548 100644 --- a/BudgetAnalyser.Engine/Widgets/ProgressBarWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/ProgressBarWidget.cs @@ -19,7 +19,7 @@ public abstract class ProgressBarWidget : Widget /// public override bool Enabled { - get { return this.doNotUseEnabled; } + get => this.doNotUseEnabled; protected set { this.doNotUseEnabled = value; @@ -42,7 +42,7 @@ protected set /// public double Maximum { - get { return this.doNotUseMaximum; } + get => this.doNotUseMaximum; set { this.doNotUseMaximum = value; @@ -55,7 +55,7 @@ public double Maximum /// public double Minimum { - get { return this.doNotUseMinimum; } + get => this.doNotUseMinimum; set { this.doNotUseMinimum = value; @@ -70,7 +70,7 @@ public double Minimum Justification = "Required for Data binding")] public bool ProgressBarVisibility { - get { return this.doNotUseProgressBarVisibility; } + get => this.doNotUseProgressBarVisibility; protected set { this.doNotUseProgressBarVisibility = value; @@ -83,7 +83,7 @@ protected set /// public double Value { - get { return this.doNotUseValue; } + get => this.doNotUseValue; set { this.doNotUseValue = value; @@ -91,4 +91,4 @@ public double Value } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/ReflectionWidgetRepository.cs b/BudgetAnalyser.Engine/Widgets/ReflectionWidgetRepository.cs index 0ea5803d..c7f1d473 100644 --- a/BudgetAnalyser.Engine/Widgets/ReflectionWidgetRepository.cs +++ b/BudgetAnalyser.Engine/Widgets/ReflectionWidgetRepository.cs @@ -41,13 +41,8 @@ public ReflectionWidgetRepository() MessageId = "IUserDefinedWidget")] public IUserDefinedWidget Create(string widgetType, string id) { - var type = Type.GetType(widgetType); - if (type is null) - { - throw new NotSupportedException("The widget type specified " + widgetType + + var type = Type.GetType(widgetType) ?? throw new NotSupportedException("The widget type specified " + widgetType + " is not found in any known type library."); - } - if (!typeof(IUserDefinedWidget).IsAssignableFrom(type)) { throw new NotSupportedException("The widget type specified " + widgetType + @@ -64,7 +59,7 @@ public IUserDefinedWidget Create(string widgetType, string id) throw new ArgumentException("A widget with this key already exists.", nameof(id)); } - var baseWidget = (Widget) widget; + var baseWidget = (Widget)widget; this.cachedWidgets.Add(key, baseWidget); return widget; } @@ -76,7 +71,7 @@ public IEnumerable GetAll() { if (this.cachedWidgets.None()) { - List widgetTypes = GetType().GetTypeInfo().Assembly.GetExportedTypes() + var widgetTypes = GetType().GetTypeInfo().Assembly.GetExportedTypes() .Where(t => typeof(Widget).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract) .ToList(); @@ -106,8 +101,8 @@ public void Remove(IUserDefinedWidget widget) private static string BuildMultiUseWidgetKey(IUserDefinedWidget widget) { - var baseWidget = (Widget) widget; + var baseWidget = (Widget)widget; return baseWidget.Category + baseWidget.Name + widget.Id; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/RemainingActualSurplusWidget.cs b/BudgetAnalyser.Engine/Widgets/RemainingActualSurplusWidget.cs index ad30011c..6047c328 100644 --- a/BudgetAnalyser.Engine/Widgets/RemainingActualSurplusWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/RemainingActualSurplusWidget.cs @@ -20,7 +20,7 @@ public class RemainingActualSurplusWidget : ProgressBarWidget private StatementModel statement; private IBudgetCurrencyContext budget; private ILogger logger; - private ILogger nullLogger = new NullLogger(); + private readonly ILogger nullLogger = new NullLogger(); /// /// Initializes a new instance of the class. @@ -34,7 +34,7 @@ public RemainingActualSurplusWidget() this.standardStyle = "WidgetStandardStyle3"; } - private ILogger Logger { get => this.logger == this.nullLogger ? null : this.logger; } + private ILogger Logger => this.logger == this.nullLogger ? null : this.logger; /// /// Updates the widget with new input. @@ -101,16 +101,9 @@ public override void Update([NotNull] params object[] input) Maximum = Convert.ToDouble(openingBalance); Value = Convert.ToDouble(remainingBalance); Minimum = 0; - if (remainingBalance < 0.2M * openingBalance) - { - ColourStyleName = WidgetWarningStyle; - } - else - { - ColourStyleName = this.standardStyle; - } + ColourStyleName = remainingBalance < 0.2M * openingBalance ? WidgetWarningStyle : this.standardStyle; - ToolTip = $"Remaining Surplus for period is {remainingBalance:C} of {openingBalance:C} {remainingBalance/openingBalance:P0}"; + ToolTip = $"Remaining Surplus for period is {remainingBalance:C} of {openingBalance:C} {remainingBalance / openingBalance:P0}"; } private decimal CalculateOpeningBalance() @@ -118,4 +111,4 @@ private decimal CalculateOpeningBalance() var line = this.ledgerCalculator.LocateApplicableLedgerLine(this.ledgerBook, this.filter); return line?.CalculatedSurplus ?? 0; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/RemainingBudgetBucketWidget.cs b/BudgetAnalyser.Engine/Widgets/RemainingBudgetBucketWidget.cs index 20657afc..77cc2a6c 100644 --- a/BudgetAnalyser.Engine/Widgets/RemainingBudgetBucketWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/RemainingBudgetBucketWidget.cs @@ -151,14 +151,7 @@ public override void Update([NotNull] params object[] input) Value = Convert.ToDouble(remainingBalance); ToolTip = string.Format(CultureInfo.CurrentCulture, RemainingBudgetToolTip, remainingBalance, remainingBalance / totalBudget); - if (remainingBalance < 0.2M * totalBudget) - { - ColourStyleName = WidgetWarningStyle; - } - else - { - ColourStyleName = this.standardStyle; - } + ColourStyleName = remainingBalance < 0.2M * totalBudget ? WidgetWarningStyle : this.standardStyle; } /// @@ -171,12 +164,9 @@ protected virtual decimal LedgerBucketBalanceOrBudgetAmount() var ledgerLine = LedgerCalculation.LocateApplicableLedgerLine(LedgerBook, Filter); - if (LedgerBook is null || ledgerLine is null || ledgerLine.Entries.All(e => e.LedgerBucket.BudgetBucket.Code != BucketCode)) - { - return Budget.Model.Expenses.Single(b => b.Bucket.Code == BucketCode).Amount; - } - - return ledgerLine.Entries.First(e => e.LedgerBucket.BudgetBucket.Code == BucketCode).Balance; + return LedgerBook is null || ledgerLine is null || ledgerLine.Entries.All(e => e.LedgerBucket.BudgetBucket.Code != BucketCode) + ? Budget.Model.Expenses.Single(b => b.Bucket.Code == BucketCode).Amount + : ledgerLine.Entries.First(e => e.LedgerBucket.BudgetBucket.Code == BucketCode).Balance; } internal static bool ValidatePeriod(BudgetCycle budgetCycle, DateTime inclBeginDate, DateTime inclEndDate, out string validationMessage) @@ -202,4 +192,4 @@ internal static bool ValidatePeriod(BudgetCycle budgetCycle, DateTime inclBeginD validationMessage = string.Empty; return true; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/RemainingSurplusWidget.cs b/BudgetAnalyser.Engine/Widgets/RemainingSurplusWidget.cs index f039bdc7..9d8b3293 100644 --- a/BudgetAnalyser.Engine/Widgets/RemainingSurplusWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/RemainingSurplusWidget.cs @@ -29,4 +29,4 @@ protected override decimal LedgerBucketBalanceOrBudgetAmount() return Budget.Model.Surplus; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/SaveWidget.cs b/BudgetAnalyser.Engine/Widgets/SaveWidget.cs index aefd3305..ea946975 100644 --- a/BudgetAnalyser.Engine/Widgets/SaveWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/SaveWidget.cs @@ -40,12 +40,15 @@ public override void Update(params object[] input) return; } - var appDbService = (IApplicationDatabaseService) input[0]; - if (appDbService is null) return; + var appDbService = (IApplicationDatabaseService)input[0]; + if (appDbService is null) + { + return; + } Enabled = appDbService.HasUnsavedChanges; Clickable = Enabled; DetailedText = Enabled ? "Save" : "No changes"; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidget.cs b/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidget.cs index 2da6073b..fefc2689 100644 --- a/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidget.cs @@ -114,30 +114,30 @@ public override void Update(params object[] input) this.bucketRepository = (IBudgetBucketRepository)input[0]; this.filter = (GlobalFilterCriteria)input[1]; - var budgetCollection = ((BudgetCollection)input[2]); - - if (this.filter is null - || this.filter.Cleared - || this.filter.BeginDate is null - || this.filter.BeginDate == DateTime.MinValue - || this.filter.EndDate is null - || this.filter.EndDate.Value == DateTime.MinValue + var budgetCollection = (BudgetCollection)input[2]; + + if (this.filter is null + || this.filter.Cleared + || this.filter.BeginDate is null + || this.filter.BeginDate == DateTime.MinValue + || this.filter.EndDate is null + || this.filter.EndDate.Value == DateTime.MinValue || this.bucketRepository is null) { Enabled = false; - ToolTip = "The global filter dates are not set."; + ToolTip = "The global filter dates are not set."; return; } if (budgetCollection is null) { Enabled = false; - ToolTip = "The budget collection is empty or null."; + ToolTip = "The budget collection is empty or null."; return; } var budgetModel = budgetCollection.CurrentActiveBudget; - + if (!this.bucketRepository.IsValidCode(BucketCode)) { Enabled = false; @@ -237,7 +237,7 @@ private PaymentDate CalculateNextPaymentDate(PaymentDate paymentDate) var proposedDate = new PaymentDate(paymentDate.ScheduledDate.AddDays(7 * this.multiplier)); if (this.filter.BeginDate is not null) { - List holidays = + var holidays = NewZealandPublicHolidays.CalculateHolidays(this.filter.BeginDate.Value, this.filter.BeginDate.Value.AddYears(1)).ToList(); while (holidays.Contains(proposedDate.Date)) @@ -321,4 +321,4 @@ public PaymentDate(DateTime initial) public DateTime Date { get; set; } public DateTime ScheduledDate { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidgetPersistentState.cs b/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidgetPersistentState.cs index 445e3500..7113a1d5 100644 --- a/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidgetPersistentState.cs +++ b/BudgetAnalyser.Engine/Widgets/SurprisePaymentWidgetPersistentState.cs @@ -18,4 +18,4 @@ public class SurprisePaymentWidgetPersistentState : MultiInstanceWidgetState /// public DateTime PaymentStartDate { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/TimedUpdateCounterWidget.cs b/BudgetAnalyser.Engine/Widgets/TimedUpdateCounterWidget.cs index 4fb09d69..dba91825 100644 --- a/BudgetAnalyser.Engine/Widgets/TimedUpdateCounterWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/TimedUpdateCounterWidget.cs @@ -51,4 +51,4 @@ public override void Update([NotNull] params object[] input) LargeNumber = this.refreshCount.ToString(CultureInfo.CurrentCulture); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/UpdateMobileDataWidget.cs b/BudgetAnalyser.Engine/Widgets/UpdateMobileDataWidget.cs index def2942e..ffcd4763 100644 --- a/BudgetAnalyser.Engine/Widgets/UpdateMobileDataWidget.cs +++ b/BudgetAnalyser.Engine/Widgets/UpdateMobileDataWidget.cs @@ -73,16 +73,22 @@ public override void Update([NotNull] params object[] input) Enabled = false; - if (!ValidateUpdateInput(input)) return; + if (!ValidateUpdateInput(input)) + { + return; + } - LedgerBook = (LedgerBook) input[0]; - StatementModel = (StatementModel) input[1]; - BudgetCollection = (BudgetCollection) input[2]; - Filter = (GlobalFilterCriteria) input[3]; + LedgerBook = (LedgerBook)input[0]; + StatementModel = (StatementModel)input[1]; + BudgetCollection = (BudgetCollection)input[2]; + Filter = (GlobalFilterCriteria)input[3]; - if (LedgerBook is null || StatementModel is null || BudgetCollection is null || Filter is null) return; + if (LedgerBook is null || StatementModel is null || BudgetCollection is null || Filter is null) + { + return; + } Enabled = true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/WeeklyOrFortnightly.cs b/BudgetAnalyser.Engine/Widgets/WeeklyOrFortnightly.cs index 491868f8..bffc5abd 100644 --- a/BudgetAnalyser.Engine/Widgets/WeeklyOrFortnightly.cs +++ b/BudgetAnalyser.Engine/Widgets/WeeklyOrFortnightly.cs @@ -15,4 +15,4 @@ public enum WeeklyOrFortnightly /// Fortnightly } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/Widget.cs b/BudgetAnalyser.Engine/Widgets/Widget.cs index fe651deb..07cecde3 100644 --- a/BudgetAnalyser.Engine/Widgets/Widget.cs +++ b/BudgetAnalyser.Engine/Widgets/Widget.cs @@ -74,7 +74,7 @@ protected Widget() // ReSharper disable once DoNotCallOverridableMethodsInConstructor - ok here, simple bool property with straightforward usage. Enabled = true; Sequence = 99; - RecommendedTimeIntervalUpdate = 30.Seconds(); + RecommendedTimeIntervalUpdate = 30.Seconds(); } /// @@ -316,7 +316,7 @@ protected bool ValidateUpdateInput(object[] input) return false; } - List dependencies = Dependencies.ToList(); + var dependencies = Dependencies.ToList(); if (dependencies.Count() > input.Length) { return false; @@ -339,11 +339,6 @@ protected bool ValidateUpdateInput(object[] input) } } - if (nullCount == Dependencies.Count()) - { - return false; - } - - return true; + return nullCount != Dependencies.Count(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/WidgetGroup.cs b/BudgetAnalyser.Engine/Widgets/WidgetGroup.cs index f4524761..8b8a96a3 100644 --- a/BudgetAnalyser.Engine/Widgets/WidgetGroup.cs +++ b/BudgetAnalyser.Engine/Widgets/WidgetGroup.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; namespace BudgetAnalyser.Engine.Widgets @@ -45,4 +45,4 @@ public class WidgetGroup Justification = "Required for UI Binding.")] public ObservableCollection Widgets { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/WidgetPersistentState.cs b/BudgetAnalyser.Engine/Widgets/WidgetPersistentState.cs index 95959d9a..78fea4a6 100644 --- a/BudgetAnalyser.Engine/Widgets/WidgetPersistentState.cs +++ b/BudgetAnalyser.Engine/Widgets/WidgetPersistentState.cs @@ -18,4 +18,4 @@ public class WidgetPersistentState // TODO This state persistence is being misused currently. Custom monitor widgets should be saved with model data not state persistence. } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/WidgetSize.cs b/BudgetAnalyser.Engine/Widgets/WidgetSize.cs index ed907f7e..2b95d7df 100644 --- a/BudgetAnalyser.Engine/Widgets/WidgetSize.cs +++ b/BudgetAnalyser.Engine/Widgets/WidgetSize.cs @@ -15,4 +15,4 @@ public enum WidgetSize /// Medium } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Engine/Widgets/WidgetsApplicationState.cs b/BudgetAnalyser.Engine/Widgets/WidgetsApplicationState.cs index 1ccd5649..7d0a9702 100644 --- a/BudgetAnalyser.Engine/Widgets/WidgetsApplicationState.cs +++ b/BudgetAnalyser.Engine/Widgets/WidgetsApplicationState.cs @@ -24,4 +24,4 @@ public class WidgetsApplicationState : IPersistentApplicationStateObject Justification = "Required for serialisation")] public List WidgetStates { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Wpf.UnitTest/FakeLogger.cs b/BudgetAnalyser.Wpf.UnitTest/FakeLogger.cs index f2b26330..bf3c0e8b 100644 --- a/BudgetAnalyser.Wpf.UnitTest/FakeLogger.cs +++ b/BudgetAnalyser.Wpf.UnitTest/FakeLogger.cs @@ -4,7 +4,7 @@ namespace BudgetAnalyser.Wpf.UnitTest { - [AutoRegisterWithIoC(Named = "Named Logger", SingleInstance = true)] + [AutoRegisterWithIoC(Named = "Named Logger", SingleInstance = true)] public class FakeLogger : ILogger { public LogLevel LogLevelFilter { get; set; } @@ -45,4 +45,4 @@ public void LogWarning(Func logEntryBuilder) Debug.WriteLine(logEntryBuilder(this)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Wpf.UnitTest/MetaTest.cs b/BudgetAnalyser.Wpf.UnitTest/MetaTest.cs index 0884a268..fe7cccaa 100644 --- a/BudgetAnalyser.Wpf.UnitTest/MetaTest.cs +++ b/BudgetAnalyser.Wpf.UnitTest/MetaTest.cs @@ -5,19 +5,19 @@ namespace BudgetAnalyser.Wpf.UnitTest [TestClass] public class MetaTest { - private const int MinimumTestCount = 7; + private const int MinimumTestCount = 9; [TestMethod] public void ListAllTests() { - Assembly assembly = GetType().Assembly; + var assembly = GetType().Assembly; var count = 0; - foreach (Type type in assembly.ExportedTypes) + foreach (var type in assembly.ExportedTypes) { var testClassAttrib = type.GetCustomAttribute(); if (testClassAttrib is not null) { - foreach (MethodInfo method in type.GetMethods()) + foreach (var method in type.GetMethods()) { if (method.GetCustomAttribute() is not null) { @@ -31,13 +31,13 @@ public void ListAllTests() [TestMethod] public void NoDecreaseInTests() { - Assembly assembly = GetType().Assembly; - int count = (from type in assembly.ExportedTypes - let testClassAttrib = type.GetCustomAttribute() - where testClassAttrib is not null - select type.GetMethods().Count(method => method.GetCustomAttribute() is not null)).Sum(); + var assembly = GetType().Assembly; + var count = (from type in assembly.ExportedTypes + let testClassAttrib = type.GetCustomAttribute() + where testClassAttrib is not null + select type.GetMethods().Count(method => method.GetCustomAttribute() is not null)).Sum(); Console.WriteLine(count); Assert.IsTrue(count >= MinimumTestCount); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Wpf.UnitTest/Statement/StatementViewModelTest.cs b/BudgetAnalyser.Wpf.UnitTest/Statement/StatementViewModelTest.cs index 77908b37..6a085eb6 100644 --- a/BudgetAnalyser.Wpf.UnitTest/Statement/StatementViewModelTest.cs +++ b/BudgetAnalyser.Wpf.UnitTest/Statement/StatementViewModelTest.cs @@ -16,35 +16,35 @@ public class StatementViewModelTest [TestMethod] public void GivenNoDataHasTransactionsShouldBeFalse() { - StatementViewModel subject = CreateSubject(); + var subject = CreateSubject(); Assert.IsFalse(subject.HasTransactions); } [TestMethod] public void GivenNoDataStatementNameShouldBeNoTransactionsLoaded() { - StatementViewModel subject = CreateSubject(); + var subject = CreateSubject(); Assert.AreEqual("[No Transactions Loaded]", subject.StatementName); } [TestMethod] public void GivenTestData1HasTransactionsShouldBeTrue() { - StatementViewModel subject = Arrange(); + var subject = Arrange(); Assert.IsTrue(subject.HasTransactions); } [TestMethod] public void GivenTestData1StatementNameShouldBeFooStatement() { - StatementViewModel subject = Arrange(); + var subject = Arrange(); Assert.AreEqual("FooStatement", subject.StatementName); } [TestMethod] public void GivenTestData1TotalCreditsShouldBe0() { - StatementViewModel subject = Arrange(); + var subject = Arrange(); Assert.AreEqual(0, subject.TotalCredits); } @@ -52,7 +52,7 @@ public void GivenTestData1TotalCreditsShouldBe0() [ExpectedException(typeof(InvalidOperationException))] public void SetStatement_ShouldThrow_GivenInitialiseHasNotBeenCalled() { - StatementViewModel subject = CreateSubject(); + var subject = CreateSubject(); subject.Statement = StatementModelTestData.TestData1(); Assert.Fail(); } @@ -68,7 +68,7 @@ public void TestInitialise() [TestMethod] public void TriggerRefreshTotalsRowShouldRaise10Events() { - StatementViewModel subject = Arrange(); + var subject = Arrange(); var eventCount = 0; subject.PropertyChanged += (s, e) => eventCount++; subject.TriggerRefreshTotalsRow(); @@ -78,7 +78,7 @@ public void TriggerRefreshTotalsRowShouldRaise10Events() private static Transaction GetPhoneTxnFromFullList(StatementViewModel subject) { - Transaction transactionFromFullList = subject.Statement.Transactions + var transactionFromFullList = subject.Statement.Transactions .Single(t => t.BudgetBucket == StatementModelTestData.PhoneBucket && t.Date == new DateTime(2013, 07, 16)); return transactionFromFullList; } @@ -90,7 +90,7 @@ private static IWaitCursor WaitCursorFactory() private StatementViewModel Arrange() { - StatementViewModel subject = CreateSubject().Initialise(this.mockTransactionService.Object); + var subject = CreateSubject().Initialise(this.mockTransactionService.Object); subject.Statement = StatementModelTestData.TestData1(); return subject; } @@ -100,4 +100,4 @@ private StatementViewModel CreateSubject() return new StatementViewModel(this.mockUiContext.Object, new Mock().Object); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Wpf.UnitTest/TestData/StatementModelTestData.cs b/BudgetAnalyser.Wpf.UnitTest/TestData/StatementModelTestData.cs index 005fad2d..88e05987 100644 --- a/BudgetAnalyser.Wpf.UnitTest/TestData/StatementModelTestData.cs +++ b/BudgetAnalyser.Wpf.UnitTest/TestData/StatementModelTestData.cs @@ -33,7 +33,7 @@ public static StatementModel TestData1() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions1(); + var transactions = CreateTransactions1(); statement.LoadTransactions(transactions); return statement; } @@ -50,7 +50,7 @@ public static StatementModel TestData2() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions2(); + var transactions = CreateTransactions2(); statement.LoadTransactions(transactions); return statement; } @@ -88,7 +88,7 @@ public static StatementModel TestData3() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions3(); + var transactions = CreateTransactions3(); statement.LoadTransactions(transactions); return statement; } @@ -107,7 +107,7 @@ public static StatementModel TestData4() LastImport = new DateTime(2013, 08, 15) }; - List transactions = CreateTransactions3().ToList(); + var transactions = CreateTransactions3().ToList(); transactions.AddRange(CreateTransactions1()); statement.LoadTransactions(transactions); return statement; @@ -128,7 +128,7 @@ public static StatementModel TestData5() LastImport = new DateTime(2013, 08, 15) }; - IEnumerable transactions = CreateTransactions5(); + var transactions = CreateTransactions5(); statement.LoadTransactions(transactions); return statement; } @@ -577,4 +577,4 @@ private static IEnumerable CreateTransactions5() }; return transactions; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.Wpf.UnitTest/TestData/TestDataConstants.cs b/BudgetAnalyser.Wpf.UnitTest/TestData/TestDataConstants.cs index fdc29a9f..877e89ce 100644 --- a/BudgetAnalyser.Wpf.UnitTest/TestData/TestDataConstants.cs +++ b/BudgetAnalyser.Wpf.UnitTest/TestData/TestDataConstants.cs @@ -30,4 +30,4 @@ public static class TestDataConstants public const string VisaAccountName = "VISA"; public const string WaterBucketCode = "WATER"; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser.sln.DotSettings b/BudgetAnalyser.sln.DotSettings index fa88727c..5cc9d685 100644 --- a/BudgetAnalyser.sln.DotSettings +++ b/BudgetAnalyser.sln.DotSettings @@ -1,6 +1,11 @@  <?xml version="1.0" encoding="utf-16"?><Profile name="Ben: Full Cleanup"><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><CSReorderTypeMembers>True</CSReorderTypeMembers><CSCodeStyleAttributes ArrangeVarStyle="True" ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" ArrangeArgumentsStyle="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeAttributes="True" ArrangeCodeBodyStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" ArrangeNamespaces="True" ArrangeNullCheckingPattern="True" /><RemoveCodeRedundanciesVB>True</RemoveCodeRedundanciesVB><Xaml.RedundantFreezeAttribute>True</Xaml.RedundantFreezeAttribute><Xaml.RemoveRedundantModifiersAttribute>True</Xaml.RemoveRedundantModifiersAttribute><Xaml.RemoveRedundantNameAttribute>True</Xaml.RemoveRedundantNameAttribute><Xaml.RemoveRedundantResource>True</Xaml.RemoveRedundantResource><Xaml.RemoveRedundantCollectionProperty>True</Xaml.RemoveRedundantCollectionProperty><Xaml.RemoveRedundantAttachedPropertySetter>True</Xaml.RemoveRedundantAttachedPropertySetter><Xaml.RemoveRedundantStyledValue>True</Xaml.RemoveRedundantStyledValue><Xaml.RemoveRedundantNamespaceAlias>True</Xaml.RemoveRedundantNamespaceAlias><Xaml.RemoveForbiddenResourceName>True</Xaml.RemoveForbiddenResourceName><Xaml.RemoveRedundantGridDefinitionsAttribute>True</Xaml.RemoveRedundantGridDefinitionsAttribute><Xaml.RemoveRedundantUpdateSourceTriggerAttribute>True</Xaml.RemoveRedundantUpdateSourceTriggerAttribute><Xaml.RemoveRedundantBindingModeAttribute>True</Xaml.RemoveRedundantBindingModeAttribute><Xaml.RemoveRedundantGridSpanAttribut>True</Xaml.RemoveRedundantGridSpanAttribut><XMLReformatCode>True</XMLReformatCode><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><HtmlReformatCode>True</HtmlReformatCode><VBOptimizeImports>True</VBOptimizeImports><VBShortenReferences>True</VBShortenReferences><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><VBReformatCode>True</VBReformatCode><VBFormatDocComments>True</VBFormatDocComments><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor></Profile> Ben: Full Cleanup + 1 + NEVER + NEVER + NEVER + NEVER 200 <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"> <TypePattern DisplayName="Non-reorderable types" Priority="99999999"> diff --git a/BudgetAnalyser/App.xaml.cs b/BudgetAnalyser/App.xaml.cs index 89b70e28..750ab88c 100644 --- a/BudgetAnalyser/App.xaml.cs +++ b/BudgetAnalyser/App.xaml.cs @@ -88,4 +88,4 @@ private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledEx LogUnhandledException("App.OnDispatcherUnhandledException", e.Exception); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ApplicationDatabaseFacade.cs b/BudgetAnalyser/ApplicationDatabaseFacade.cs index 9c161e4a..18dd9ab3 100644 --- a/BudgetAnalyser/ApplicationDatabaseFacade.cs +++ b/BudgetAnalyser/ApplicationDatabaseFacade.cs @@ -9,7 +9,7 @@ namespace BudgetAnalyser; /// An interface to represent a clientside facade to marshall all access to the . This is to allow clientside code to be notified of changing data and send /// messages between controllers. /// -public interface IApplicationDatabaseFacade +public interface IApplicationDatabaseFacade { // NOTE This interface could inherit from IApplicationDatabaseService, but for simplicity of IOC registration, it does not. Also, not necessarily a bad thing because it forces local code to use // this facade and not accidentally use the service directly. @@ -179,4 +179,4 @@ public bool ValidateAll(StringBuilder messages) { return engineService.ValidateAll(messages); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ApplicationState/ApplicationStateLoadFinishedMessage.cs b/BudgetAnalyser/ApplicationState/ApplicationStateLoadFinishedMessage.cs index e960fed0..0a207f9f 100644 --- a/BudgetAnalyser/ApplicationState/ApplicationStateLoadFinishedMessage.cs +++ b/BudgetAnalyser/ApplicationState/ApplicationStateLoadFinishedMessage.cs @@ -9,4 +9,4 @@ namespace BudgetAnalyser.ApplicationState public class ApplicationStateLoadFinishedMessage : MessageBase { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ApplicationState/ApplicationStateLoadedMessage.cs b/BudgetAnalyser/ApplicationState/ApplicationStateLoadedMessage.cs index ea247ab9..1de83f49 100644 --- a/BudgetAnalyser/ApplicationState/ApplicationStateLoadedMessage.cs +++ b/BudgetAnalyser/ApplicationState/ApplicationStateLoadedMessage.cs @@ -44,12 +44,7 @@ public ApplicationStateLoadedMessage(IEnumerable() where T : class, IPersistentApplicationStateObject { var type = typeof(T); - if (RehydratedModels.TryGetValue(type, out var model)) - { - return model as T; - } - - return null; + return RehydratedModels.TryGetValue(type, out var model) ? model as T : null; } } } diff --git a/BudgetAnalyser/ApplicationState/ApplicationStateRequestedMessage.cs b/BudgetAnalyser/ApplicationState/ApplicationStateRequestedMessage.cs index 5663e816..ba05b609 100644 --- a/BudgetAnalyser/ApplicationState/ApplicationStateRequestedMessage.cs +++ b/BudgetAnalyser/ApplicationState/ApplicationStateRequestedMessage.cs @@ -36,4 +36,4 @@ public void PersistThisModel(IPersistentApplicationStateObject model) this.modelsToPersist.Add(model); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ApplicationState/PersistBaxAppStateAsXaml.cs b/BudgetAnalyser/ApplicationState/PersistBaxAppStateAsXaml.cs index 8a19b48f..14fb4e28 100644 --- a/BudgetAnalyser/ApplicationState/PersistBaxAppStateAsXaml.cs +++ b/BudgetAnalyser/ApplicationState/PersistBaxAppStateAsXaml.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Xaml; @@ -74,18 +74,14 @@ public IEnumerable Load() try { - object serialised = XamlServices.Load(FullFileName); + var serialised = XamlServices.Load(FullFileName); // Will throw Xaml Exception if the xml is corrupt, or the xaml types cannot be found and created. - var correctFormat = serialised as List; - if (correctFormat is null) - { - throw new BadApplicationStateFileFormatException( + return serialised is not List correctFormat + ? throw new BadApplicationStateFileFormatException( string.Format(CultureInfo.InvariantCulture, "The file used to store application state ({0}) is not in the correct format. It may have been tampered with.", - FullFileName)); - } - - return correctFormat; + FullFileName)) + : (IEnumerable)correctFormat; } catch (IOException ex) { @@ -124,4 +120,4 @@ private IEnumerable HandleCorruptFileGraceful return new List(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetBucketBindingSource.cs b/BudgetAnalyser/Budget/BudgetBucketBindingSource.cs index 3ffde397..6eec4909 100644 --- a/BudgetAnalyser/Budget/BudgetBucketBindingSource.cs +++ b/BudgetAnalyser/Budget/BudgetBucketBindingSource.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.Budget; +using BudgetAnalyser.Engine.Budget; namespace BudgetAnalyser.Budget { @@ -10,4 +10,4 @@ public static class BudgetBucketBindingSource /// public static IBudgetBucketRepository BucketRepository { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetBucketChosenEventArgs.cs b/BudgetAnalyser/Budget/BudgetBucketChosenEventArgs.cs index 2ddc9b3a..cf09de96 100644 --- a/BudgetAnalyser/Budget/BudgetBucketChosenEventArgs.cs +++ b/BudgetAnalyser/Budget/BudgetBucketChosenEventArgs.cs @@ -23,4 +23,4 @@ public BudgetBucketChosenEventArgs(Guid correlationId, BudgetBucket? bucket, Acc public BudgetBucket? SelectedBucket { get; private set; } public Account StoreInThisAccount { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetBucketUserControl.xaml.cs b/BudgetAnalyser/Budget/BudgetBucketUserControl.xaml.cs index cf3fa8df..03cb04cb 100644 --- a/BudgetAnalyser/Budget/BudgetBucketUserControl.xaml.cs +++ b/BudgetAnalyser/Budget/BudgetBucketUserControl.xaml.cs @@ -12,4 +12,4 @@ public BudgetBucketUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetController.cs b/BudgetAnalyser/Budget/BudgetController.cs index 85c316ad..5e58ded0 100644 --- a/BudgetAnalyser/Budget/BudgetController.cs +++ b/BudgetAnalyser/Budget/BudgetController.cs @@ -1,4 +1,4 @@ -using System.ComponentModel; +using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Windows.Input; @@ -38,7 +38,7 @@ public class BudgetController : ControllerBase, IShowableController public BudgetController( [NotNull] UiContext uiContext, [NotNull] IBudgetMaintenanceService maintenanceService, - [NotNull] IApplicationDatabaseFacade applicationDatabaseService) + [NotNull] IApplicationDatabaseFacade applicationDatabaseService) : base(uiContext.Messenger) { if (uiContext is null) @@ -72,11 +72,16 @@ public BudgetController( // ReSharper disable once MemberCanBePrivate.Global public string BudgetMenuItemName { - [UsedImplicitly] get => this.budgetMenuItemName; + [UsedImplicitly] + get => this.budgetMenuItemName; set { - if (Equals(value, this.BudgetMenuItemName)) return; + if (Equals(value, BudgetMenuItemName)) + { + return; + } + this.budgetMenuItemName = value; OnPropertyChanged(); } @@ -129,7 +134,11 @@ public bool Dirty get => this.doNotUseDirty; private set { - if (value == this.doNotUseDirty) return; + if (value == this.doNotUseDirty) + { + return; + } + this.doNotUseDirty = value; OnPropertyChanged(); if (Dirty) @@ -149,7 +158,11 @@ public decimal ExpenseTotal private set { - if (value == this.expenseTotal) return; + if (value == this.expenseTotal) + { + return; + } + this.expenseTotal = value; OnPropertyChanged(); } @@ -164,7 +177,11 @@ public decimal IncomeTotal private set { - if (value == this.incomeTotal) return; + if (value == this.incomeTotal) + { + return; + } + this.incomeTotal = value; OnPropertyChanged(); } @@ -180,10 +197,15 @@ private set // ReSharper disable once MemberCanBePrivate.Global public decimal Surplus { - [UsedImplicitly] get => this.surplus; + [UsedImplicitly] + get => this.surplus; private set { - if (value == this.surplus) return; + if (value == this.surplus) + { + return; + } + this.surplus = value; OnPropertyChanged(); } @@ -198,7 +220,11 @@ public bool Shown set { - if (value == this.doNotUseShownBudget) return; + if (value == this.doNotUseShownBudget) + { + return; + } + this.doNotUseShownBudget = value; OnPropertyChanged(); BudgetMenuItemName = this.doNotUseShownBudget ? CloseBudgetMenuName : EditBudgetMenuName; @@ -258,13 +284,11 @@ private void OnAddNewExpenseExecute(ExpenseBucket expense) { newExpense.Bucket = new SpentPerPeriodExpenseBucket(string.Empty, string.Empty); } - else if (expense is SavedUpForExpenseBucket) - { - newExpense.Bucket = new SavedUpForExpenseBucket(string.Empty, string.Empty); - } else { - throw new InvalidCastException("Invalid type passed to Add New Expense: " + expense); + newExpense.Bucket = expense is SavedUpForExpenseBucket + ? (BudgetBucket)new SavedUpForExpenseBucket(string.Empty, string.Empty) + : throw new InvalidCastException("Invalid type passed to Add New Expense: " + expense); } Expenses.RaiseListChangedEvents = true; @@ -465,4 +489,4 @@ private void SyncDataToBudgetService() { this.maintenanceService.UpdateIncomesAndExpenses(CurrentBudget.Model, Incomes, Expenses); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetDetailsView.xaml.cs b/BudgetAnalyser/Budget/BudgetDetailsView.xaml.cs index 37c315b7..cc63bd97 100644 --- a/BudgetAnalyser/Budget/BudgetDetailsView.xaml.cs +++ b/BudgetAnalyser/Budget/BudgetDetailsView.xaml.cs @@ -12,4 +12,4 @@ public BudgetDetailsView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetMaintenance.xaml.cs b/BudgetAnalyser/Budget/BudgetMaintenance.xaml.cs index c3ba4676..83bb1a34 100644 --- a/BudgetAnalyser/Budget/BudgetMaintenance.xaml.cs +++ b/BudgetAnalyser/Budget/BudgetMaintenance.xaml.cs @@ -46,7 +46,7 @@ private void OnExpensesListChanged(object sender, ListChangedEventArgs listChang if (listChangedEventArgs.ListChangedType == ListChangedType.ItemAdded) { this.ExpensesListScrollViewer.ScrollToBottom(); - int count = this.Expenses.Items.Count == 0 ? 0 : this.Expenses.Items.Count - 1; + var count = this.Expenses.Items.Count == 0 ? 0 : this.Expenses.Items.Count - 1; this.Expenses.SelectedIndex = count; } } @@ -56,9 +56,9 @@ private void OnIncomesListChanged(object sender, ListChangedEventArgs listChange if (listChangedEventArgs.ListChangedType == ListChangedType.ItemAdded) { this.IncomesListScrollViewer.ScrollToBottom(); - int count = this.Incomes.Items.Count == 0 ? 0 : this.Incomes.Items.Count - 1; + var count = this.Incomes.Items.Count == 0 ? 0 : this.Incomes.Items.Count - 1; this.Incomes.SelectedIndex = count; } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetModelNameUserControl.xaml.cs b/BudgetAnalyser/Budget/BudgetModelNameUserControl.xaml.cs index 03bf5141..0ff4fe17 100644 --- a/BudgetAnalyser/Budget/BudgetModelNameUserControl.xaml.cs +++ b/BudgetAnalyser/Budget/BudgetModelNameUserControl.xaml.cs @@ -46,4 +46,4 @@ private void OnMouseDoubleClick(object sender, MouseButtonEventArgs e) this.budgetNameTextBlock.Visibility = Visibility.Hidden; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetReadyMessage.cs b/BudgetAnalyser/Budget/BudgetReadyMessage.cs index 9efd3017..d744c815 100644 --- a/BudgetAnalyser/Budget/BudgetReadyMessage.cs +++ b/BudgetAnalyser/Budget/BudgetReadyMessage.cs @@ -14,4 +14,4 @@ public BudgetReadyMessage(IBudgetCurrencyContext activeBudget, BudgetCollection public IBudgetCurrencyContext ActiveBudget { get; private set; } public BudgetCollection Budgets { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetSelectionView.xaml.cs b/BudgetAnalyser/Budget/BudgetSelectionView.xaml.cs index e3186b80..9b3ac338 100644 --- a/BudgetAnalyser/Budget/BudgetSelectionView.xaml.cs +++ b/BudgetAnalyser/Budget/BudgetSelectionView.xaml.cs @@ -19,9 +19,9 @@ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventA { if (e.NewValue is BudgetController budgetController) { - ICollectionView view = CollectionViewSource.GetDefaultView(budgetController.Budgets); + var view = CollectionViewSource.GetDefaultView(budgetController.Budgets); view.SortDescriptions.Add(new SortDescription("EffectiveFrom", ListSortDirection.Descending)); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/BudgetSelectionViewModel.cs b/BudgetAnalyser/Budget/BudgetSelectionViewModel.cs index 8c99f0cb..21d4d9b3 100644 --- a/BudgetAnalyser/Budget/BudgetSelectionViewModel.cs +++ b/BudgetAnalyser/Budget/BudgetSelectionViewModel.cs @@ -15,4 +15,4 @@ public BudgetSelectionViewModel(BudgetCollection budgets) [UsedImplicitly] public BudgetModel Selected { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/ChooseBudgetBucketController.cs b/BudgetAnalyser/Budget/ChooseBudgetBucketController.cs index b660f703..067d2cb1 100644 --- a/BudgetAnalyser/Budget/ChooseBudgetBucketController.cs +++ b/BudgetAnalyser/Budget/ChooseBudgetBucketController.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.BankAccount; using BudgetAnalyser.Engine.Budget; @@ -44,7 +44,8 @@ public ChooseBudgetBucketController([NotNull] IUiContext uiContext, [NotNull] IB public IEnumerable BudgetBuckets { - [UsedImplicitly] get => this.doNotUseBudgetBuckets; + [UsedImplicitly] + get => this.doNotUseBudgetBuckets; private set { @@ -60,10 +61,15 @@ private set public string FilterDescription { - [UsedImplicitly] get => this.doNotUseFilterDescription; + [UsedImplicitly] + get => this.doNotUseFilterDescription; set { - if (value == this.doNotUseFilterDescription) return; + if (value == this.doNotUseFilterDescription) + { + return; + } + this.doNotUseFilterDescription = value; OnPropertyChanged(); } @@ -74,7 +80,11 @@ public BudgetBucket? Selected get => this.doNotUseSelected; set { - if (Equals(value, this.doNotUseSelected)) return; + if (Equals(value, this.doNotUseSelected)) + { + return; + } + this.doNotUseSelected = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteOkButton)); @@ -114,7 +124,7 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) return; } - EventHandler handler = Chosen; + var handler = Chosen; if (handler is not null) { if (message.Response == ShellDialogButton.Cancel) @@ -141,4 +151,4 @@ private void Reset() StoreInThisAccount = null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/ChooseBudgetBucketUserControl.xaml.cs b/BudgetAnalyser/Budget/ChooseBudgetBucketUserControl.xaml.cs index b436a3b8..872f1990 100644 --- a/BudgetAnalyser/Budget/ChooseBudgetBucketUserControl.xaml.cs +++ b/BudgetAnalyser/Budget/ChooseBudgetBucketUserControl.xaml.cs @@ -12,4 +12,4 @@ public ChooseBudgetBucketUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/CreateNewBudgetModelUserControl.xaml.cs b/BudgetAnalyser/Budget/CreateNewBudgetModelUserControl.xaml.cs index 299be4c4..eeb64c9e 100644 --- a/BudgetAnalyser/Budget/CreateNewBudgetModelUserControl.xaml.cs +++ b/BudgetAnalyser/Budget/CreateNewBudgetModelUserControl.xaml.cs @@ -12,4 +12,4 @@ public CreateNewBudgetModelUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/CreateNewFixedBudgetController.cs b/BudgetAnalyser/Budget/CreateNewFixedBudgetController.cs index 280c3b58..a9e2701b 100644 --- a/BudgetAnalyser/Budget/CreateNewFixedBudgetController.cs +++ b/BudgetAnalyser/Budget/CreateNewFixedBudgetController.cs @@ -1,10 +1,10 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Budget { @@ -39,7 +39,11 @@ public decimal Amount [UsedImplicitly] set { - if (value == this.doNotUseAmount) return; + if (value == this.doNotUseAmount) + { + return; + } + this.doNotUseAmount = value; OnPropertyChanged(); Messenger.Send(); @@ -70,7 +74,11 @@ public string Code [UsedImplicitly] set { - if (value == this.doNotUseCode) return; + if (value == this.doNotUseCode) + { + return; + } + this.doNotUseCode = value; OnPropertyChanged(); Messenger.Send(); @@ -83,7 +91,11 @@ public string Description [UsedImplicitly] set { - if (value == this.doNotUseDescription) return; + if (value == this.doNotUseDescription) + { + return; + } + this.doNotUseDescription = value; OnPropertyChanged(); Messenger.Send(); @@ -117,8 +129,8 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) return; } - EventHandler handler = Complete; + var handler = Complete; handler?.Invoke(this, new DialogResponseEventArgs(this.dialogCorrelationId, message.Response == ShellDialogButton.Cancel)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/CreateNewFixedBudgetProjectUserControl.xaml.cs b/BudgetAnalyser/Budget/CreateNewFixedBudgetProjectUserControl.xaml.cs index 2808469a..9c678cc6 100644 --- a/BudgetAnalyser/Budget/CreateNewFixedBudgetProjectUserControl.xaml.cs +++ b/BudgetAnalyser/Budget/CreateNewFixedBudgetProjectUserControl.xaml.cs @@ -12,4 +12,4 @@ public CreateNewFixedBudgetProjectUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/DialogResponseEventArgs.cs b/BudgetAnalyser/Budget/DialogResponseEventArgs.cs index 303216c3..a858e805 100644 --- a/BudgetAnalyser/Budget/DialogResponseEventArgs.cs +++ b/BudgetAnalyser/Budget/DialogResponseEventArgs.cs @@ -13,4 +13,4 @@ public DialogResponseEventArgs(Guid correlationId, bool canceled) public bool Canceled { get; private set; } public Guid CorrelationId { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Budget/NewBudgetModelController.cs b/BudgetAnalyser/Budget/NewBudgetModelController.cs index 4f2d0010..84056211 100644 --- a/BudgetAnalyser/Budget/NewBudgetModelController.cs +++ b/BudgetAnalyser/Budget/NewBudgetModelController.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine; +using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; @@ -40,7 +40,11 @@ public BudgetCycle BudgetCycle get => this.doNotUseBudgetCycle; set { - if (value == this.doNotUseBudgetCycle) return; + if (value == this.doNotUseBudgetCycle) + { + return; + } + this.doNotUseBudgetCycle = value; OnPropertyChanged(); OnPropertyChanged(nameof(FortnightlyChecked)); @@ -69,7 +73,11 @@ public DateTime EffectiveFrom get => this.doNotUseEffectiveFrom; set { - if (value == this.doNotUseEffectiveFrom) return; + if (value == this.doNotUseEffectiveFrom) + { + return; + } + this.doNotUseEffectiveFrom = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -123,4 +131,4 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) Ready?.Invoke(this, EventArgs.Empty); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/BudgetAnalyserFeature.cs b/BudgetAnalyser/BudgetAnalyserFeature.cs index 3916079b..c112a4d1 100644 --- a/BudgetAnalyser/BudgetAnalyserFeature.cs +++ b/BudgetAnalyser/BudgetAnalyserFeature.cs @@ -11,4 +11,4 @@ public enum BudgetAnalyserFeature LedgerBook, Reports, } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/CompositionRoot.cs b/BudgetAnalyser/CompositionRoot.cs index da59d2ba..4be7d3a9 100644 --- a/BudgetAnalyser/CompositionRoot.cs +++ b/BudgetAnalyser/CompositionRoot.cs @@ -20,8 +20,8 @@ using BudgetAnalyser.ReportsCatalog.OverallPerformance; using BudgetAnalyser.Statement; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; using Rees.Wpf.RecentFiles; using Rees.Wpf.UserInteraction; using IPersistApplicationState = BudgetAnalyser.ApplicationState.IPersistApplicationState; @@ -137,13 +137,12 @@ private void BuildApplicationObjectGraph(ContainerBuilder builder, params Assemb foreach (var assembly in assemblies) { - IEnumerable requiredPropertyInjections = DefaultIoCRegistrations.ProcessPropertyInjection(assembly); + var requiredPropertyInjections = DefaultIoCRegistrations.ProcessPropertyInjection(assembly); foreach (var requirement in requiredPropertyInjections) { // Some reasonably awkward Autofac usage here to allow testability. (Extension methods aren't easy to test) - ServiceRegistration registration; var typedService = new TypedService(requirement.DependencyRequired); - var success = container.ComponentRegistry.TryGetServiceRegistration(typedService, out registration); + var success = container.ComponentRegistry.TryGetServiceRegistration(typedService, out var registration); if (success) { var requestToResolve = new ResolveRequest(typedService, registration, Enumerable.Empty()); @@ -163,7 +162,7 @@ private void BuildApplicationObjectGraph(ContainerBuilder builder, params Assemb private static void ComposeTypesWithDefaultImplementations(Assembly assembly, ContainerBuilder builder) { - IEnumerable dependencies = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(assembly); + var dependencies = DefaultIoCRegistrations.RegisterAutoMappingsFromAssembly(assembly); foreach (var dependency in dependencies) { IRegistrationBuilder registration; @@ -258,15 +257,15 @@ private bool IsMainThread() { return Application.Current.Dispatcher.CheckAccess(); } - + /// - /// Finalizes an instance of the class. - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// + /// Finalizes an instance of the class. + /// Use C# destructor syntax for finalization code. + /// This destructor will run only if the Dispose method + /// does not get called. + /// It gives your base class the opportunity to finalize. + /// Do not provide destructors in types derived from this class. + /// ~CompositionRoot() { // Do not re-create Dispose clean-up code here. @@ -275,4 +274,4 @@ private bool IsMainThread() Dispose(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ConcurrentMessenger.cs b/BudgetAnalyser/ConcurrentMessenger.cs index dabed7d1..10d57f55 100644 --- a/BudgetAnalyser/ConcurrentMessenger.cs +++ b/BudgetAnalyser/ConcurrentMessenger.cs @@ -41,12 +41,16 @@ public void Register(TRecipient recipient, TToken { lock (SyncRoot) { - if (this.defaultMessenger.IsRegistered(recipient, token)) return; + if (this.defaultMessenger.IsRegistered(recipient, token)) + { + return; + } + this.defaultMessenger.Register(recipient, token, handler); } this.logger.LogInfo(l => l.Format("IMessenger.Register Token:{0} recipient:{1} Message:{2}", token, recipient, typeof(TMessage).Name)); - } + } public void UnregisterAll(object recipient) { @@ -54,7 +58,7 @@ public void UnregisterAll(object recipient) { this.defaultMessenger.UnregisterAll(recipient); } - + this.logger.LogInfo(l => l.Format("IMessenger.UnregisterAll recipient:{0}", recipient)); } @@ -72,7 +76,11 @@ public void Unregister(object recipient, TToken token) where T { lock (SyncRoot) { - if (!this.defaultMessenger.IsRegistered(recipient, token)) return; + if (!this.defaultMessenger.IsRegistered(recipient, token)) + { + return; + } + this.defaultMessenger.Unregister(recipient, token); } } @@ -108,4 +116,4 @@ public void Reset() this.logger.LogInfo(l => "IMessenger.Reset"); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/BoolToAndConverter.cs b/BudgetAnalyser/Converters/BoolToAndConverter.cs index 21d3b3f3..4b3fb82e 100644 --- a/BudgetAnalyser/Converters/BoolToAndConverter.cs +++ b/BudgetAnalyser/Converters/BoolToAndConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows.Data; namespace BudgetAnalyser.Converters @@ -9,19 +8,19 @@ namespace BudgetAnalyser.Converters /// public class BoolToAndConverter : IValueConverter { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { - if (value is bool) + if (value is bool b) { - return (bool)value ? "And" : "Or"; + return b ? "And" : "Or"; } return null; } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/BucketToColourConverter.cs b/BudgetAnalyser/Converters/BucketToColourConverter.cs index 00af93f0..353b71d2 100644 --- a/BudgetAnalyser/Converters/BucketToColourConverter.cs +++ b/BudgetAnalyser/Converters/BucketToColourConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Windows.Data; using BudgetAnalyser.Engine.Budget; @@ -9,8 +9,7 @@ public class BucketToColourConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - var bucketValue = value as BudgetBucket; - if (bucketValue is null) + if (value is not BudgetBucket bucketValue) { return null; } @@ -30,12 +29,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn return ConverterHelper.AccumulatedBucketBrush; } - if (value is IncomeBudgetBucket) - { - return ConverterHelper.IncomeBucketBrush; - } - - return ConverterHelper.NeutralNumberBackgroundBrush; + return value is IncomeBudgetBucket ? ConverterHelper.IncomeBucketBrush : (object)ConverterHelper.NeutralNumberBackgroundBrush; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) @@ -43,4 +37,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/BucketToVisibilityConverter.cs b/BudgetAnalyser/Converters/BucketToVisibilityConverter.cs index a78b9a2f..af803cdc 100644 --- a/BudgetAnalyser/Converters/BucketToVisibilityConverter.cs +++ b/BudgetAnalyser/Converters/BucketToVisibilityConverter.cs @@ -10,8 +10,7 @@ public class BucketToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - var bucket = value as BudgetBucket; - if (bucket is null) + if (value is not BudgetBucket bucket) { return Visibility.Visible; } @@ -20,12 +19,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn { if (parameter.ToString() == "Expense") { - if (bucket is SurplusBucket) - { - return Visibility.Visible; - } - - return bucket is ExpenseBucket ? Visibility.Visible : Visibility.Collapsed; + return bucket is SurplusBucket ? Visibility.Visible : (object)(bucket is ExpenseBucket ? Visibility.Visible : Visibility.Collapsed); } if (parameter.ToString() == "Income") @@ -42,4 +36,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/BudgetBucketToStringConverter.cs b/BudgetAnalyser/Converters/BudgetBucketToStringConverter.cs index 22e39ad2..21f8d862 100644 --- a/BudgetAnalyser/Converters/BudgetBucketToStringConverter.cs +++ b/BudgetAnalyser/Converters/BudgetBucketToStringConverter.cs @@ -18,12 +18,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var stringValue = value as string; - if (string.IsNullOrWhiteSpace(stringValue)) - { - return null; - } - - return BudgetBucketBindingSource.BucketRepository.GetByCode(stringValue); + return string.IsNullOrWhiteSpace(stringValue) ? null : (object)BudgetBucketBindingSource.BucketRepository.GetByCode(stringValue); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/BudgetNameViewModelConverter.cs b/BudgetAnalyser/Converters/BudgetNameViewModelConverter.cs index 275e9dd5..16b90bd1 100644 --- a/BudgetAnalyser/Converters/BudgetNameViewModelConverter.cs +++ b/BudgetAnalyser/Converters/BudgetNameViewModelConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Windows.Data; using BudgetAnalyser.Engine.Budget; @@ -14,15 +14,7 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur return null; } - var budget = values[0] as BudgetModel; - var budgets = values[1] as BudgetCollection; - - if (budget is null || budgets is null) - { - return null; - } - - return new BudgetCurrencyContext(budgets, budget); + return values[0] is not BudgetModel budget || values[1] is not BudgetCollection budgets ? null : (object)new BudgetCurrencyContext(budgets, budget); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) @@ -30,4 +22,4 @@ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/ConverterHelper.cs b/BudgetAnalyser/Converters/ConverterHelper.cs index 3eba397b..134b3c72 100644 --- a/BudgetAnalyser/Converters/ConverterHelper.cs +++ b/BudgetAnalyser/Converters/ConverterHelper.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Media; @@ -21,42 +20,54 @@ public static class ConverterHelper private const string TileBackground = "Brush.TileBackground"; private const string TileBackgroundAlternate = "Brush.TileBackgroundAlternate"; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush AccumulatedBucketBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush AccumulatedBucketBrush = Application.Current.Resources[AccumulatedBucket] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush CreditBackground1Brush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush CreditBackground1Brush = Application.Current.Resources[CreditBackground1] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush CreditBackground2Brush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush CreditBackground2Brush = Application.Current.Resources[CreditBackground2] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush DebitBackground1Brush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush DebitBackground1Brush = Application.Current.Resources[DebitBackground1] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush DebitBackground2Brush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush DebitBackground2Brush = Application.Current.Resources[DebitBackground2] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush IncomeBucketBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush IncomeBucketBrush = Application.Current.Resources[IncomeBucket] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush NeutralNumberBackgroundBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush NeutralNumberBackgroundBrush = Application.Current.Resources[NeutralNumberBackground] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush NotSoBadDebitBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush NotSoBadDebitBrush = Application.Current.Resources[NotSoBadDebit] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush SecondaryBackgroundBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush SecondaryBackgroundBrush = Application.Current.Resources[SecondaryBackground] as Brush; [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush SlightDebitBrush = Application.Current.Resources[SlightDebit] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush SpentPeriodicallyBucketBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush SpentPeriodicallyBucketBrush = Application.Current.Resources[SpentMonthlyBucket] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush TileBackgroundBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush TileBackgroundBrush = Application.Current.Resources[TileBackground] as Brush; - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Brush TileBackgroundAlternateBrush = + [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly Brush TileBackgroundAlternateBrush = Application.Current.Resources[TileBackgroundAlternate] as Brush; @@ -64,31 +75,27 @@ public static class ConverterHelper public static decimal? ParseNumber(object value) { - if (value is decimal) + if (value is decimal decimalValue) { - return (decimal)value; + return decimalValue; } - if (value is double) + if (value is double doubleNumber) { - var doublenumber = (double)value; - return Convert.ToDecimal(doublenumber); + return Convert.ToDecimal(doubleNumber); } - if (value is int) + if (value is int intNumber) { - var intNumber = (int)value; return Convert.ToDecimal(intNumber); } - if (value is long) + if (value is long longNumber) { - var longNumber = (long)value; return Convert.ToDecimal(longNumber); } var stringValue = value as string; if (stringValue is not null) { - decimal number; - if (decimal.TryParse(stringValue, out number)) + if (decimal.TryParse(stringValue, out var number)) { return number; } @@ -97,4 +104,4 @@ public static class ConverterHelper return null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/ImagePathConverter.cs b/BudgetAnalyser/Converters/ImagePathConverter.cs index 4e8585c5..b8dd545d 100644 --- a/BudgetAnalyser/Converters/ImagePathConverter.cs +++ b/BudgetAnalyser/Converters/ImagePathConverter.cs @@ -18,13 +18,10 @@ public object Convert(object value, Type targetType, object parameter, CultureIn return value; } - string path = value.ToString(); - if (path.StartsWith("../", StringComparison.OrdinalIgnoreCase)) - { - return string.Format(CultureInfo.CurrentCulture, "../{0}/{1}", parameter, path.Substring(3)); - } - - return string.Format(CultureInfo.CurrentCulture, "../{0}/{1}", parameter, path); + var path = value.ToString(); + return path.StartsWith("../", StringComparison.OrdinalIgnoreCase) + ? string.Format(CultureInfo.CurrentCulture, "../{0}/{1}", parameter, path.Substring(3)) + : (object)string.Format(CultureInfo.CurrentCulture, "../{0}/{1}", parameter, path); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) @@ -32,4 +29,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/NumberSignToBrushConverter.cs b/BudgetAnalyser/Converters/NumberSignToBrushConverter.cs index 1ea8c79e..3e44d87e 100644 --- a/BudgetAnalyser/Converters/NumberSignToBrushConverter.cs +++ b/BudgetAnalyser/Converters/NumberSignToBrushConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; @@ -10,14 +10,9 @@ public class NumberSignToBrushConverter : IValueConverter public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var stringParameter = parameter as string; - bool light = stringParameter is not null && stringParameter == "Light"; - decimal? number = ConverterHelper.ParseNumber(value); - if (number is null) - { - return ConverterHelper.TransparentBrush; - } - - return ConvertToBrush(number.Value, light); + var light = stringParameter is not null && stringParameter == "Light"; + var number = ConverterHelper.ParseNumber(value); + return number is null ? ConverterHelper.TransparentBrush : (object)ConvertToBrush(number.Value, light); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) @@ -29,17 +24,9 @@ private static Brush ConvertToBrush(decimal number, bool light) { if (light) { - if (number < 0) - { - return ConverterHelper.DebitBackground2Brush; - } - return ConverterHelper.CreditBackground2Brush; - } - if (number < 0) - { - return ConverterHelper.DebitBackground1Brush; + return number < 0 ? ConverterHelper.DebitBackground2Brush : ConverterHelper.CreditBackground2Brush; } - return ConverterHelper.CreditBackground1Brush; + return number < 0 ? ConverterHelper.DebitBackground1Brush : ConverterHelper.CreditBackground1Brush; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/NumberToBoldConverter.cs b/BudgetAnalyser/Converters/NumberToBoldConverter.cs index 8674ab6d..6ad99da7 100644 --- a/BudgetAnalyser/Converters/NumberToBoldConverter.cs +++ b/BudgetAnalyser/Converters/NumberToBoldConverter.cs @@ -9,13 +9,8 @@ public class NumberToBoldConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - decimal? number = ConverterHelper.ParseNumber(value); - if (number is null) - { - return FontWeights.Normal; - } - - return number < 0 ? FontWeights.Bold : FontWeights.Normal; + var number = ConverterHelper.ParseNumber(value); + return number is null ? FontWeights.Normal : (object)(number < 0 ? FontWeights.Bold : FontWeights.Normal); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) @@ -23,4 +18,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Converters/PercentToColourConverter.cs b/BudgetAnalyser/Converters/PercentToColourConverter.cs index e1d7b383..9deda6a5 100644 --- a/BudgetAnalyser/Converters/PercentToColourConverter.cs +++ b/BudgetAnalyser/Converters/PercentToColourConverter.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Windows.Data; namespace BudgetAnalyser.Converters @@ -25,12 +25,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn return ConvertToIncomeColors(percent); } - if (parameter.ToString() == "Performance") - { - return ConvertToPerformanceColors(percent); - } - - return ConverterHelper.NeutralNumberBackgroundBrush; + return parameter.ToString() == "Performance" ? ConvertToPerformanceColors(percent) : ConverterHelper.NeutralNumberBackgroundBrush; } catch (InvalidCastException) { @@ -55,12 +50,7 @@ private static object ConvertToExpenseColors(double percent) return ConverterHelper.SlightDebitBrush; } - if (percent < 1.1) - { - return ConverterHelper.NotSoBadDebitBrush; - } - - return ConverterHelper.DebitBackground1Brush; + return percent < 1.1 ? ConverterHelper.NotSoBadDebitBrush : (object)ConverterHelper.DebitBackground1Brush; } private static object ConvertToIncomeColors(double percent) @@ -75,12 +65,7 @@ private static object ConvertToIncomeColors(double percent) return ConverterHelper.NotSoBadDebitBrush; } - if (percent < 1.00) - { - return ConverterHelper.SlightDebitBrush; - } - - return ConverterHelper.CreditBackground1Brush; + return percent < 1.00 ? ConverterHelper.SlightDebitBrush : (object)ConverterHelper.CreditBackground1Brush; } private static object ConvertToPerformanceColors(double percent) @@ -95,12 +80,7 @@ private static object ConvertToPerformanceColors(double percent) return ConverterHelper.NotSoBadDebitBrush; } - if (percent < 100.00) - { - return ConverterHelper.NeutralNumberBackgroundBrush; - } - - return ConverterHelper.CreditBackground1Brush; + return percent < 100.00 ? ConverterHelper.NeutralNumberBackgroundBrush : (object)ConverterHelper.CreditBackground1Brush; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorController.cs b/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorController.cs index 94f37a35..7f115c30 100644 --- a/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorController.cs +++ b/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorController.cs @@ -1,12 +1,12 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using BudgetAnalyser.Budget; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Dashboard { @@ -58,7 +58,7 @@ public CreateNewSurprisePaymentMonitorController([NotNull] IUiContext uiContext, public WeeklyOrFortnightly Frequency { - get { return this.doNotUseFrequency; } + get => this.doNotUseFrequency; set { this.doNotUseFrequency = value; @@ -71,7 +71,11 @@ public DateTime PaymentStartDate get => this.doNotUsePaymentStartDate; set { - if (Equals(value, this.doNotUsePaymentStartDate)) return; + if (Equals(value, this.doNotUsePaymentStartDate)) + { + return; + } + this.doNotUsePaymentStartDate = value; OnPropertyChanged(); Messenger.Send(); @@ -84,7 +88,11 @@ public BudgetBucket? Selected [UsedImplicitly] set { - if (Equals(value, this.doNotUseSelected)) return; + if (Equals(value, this.doNotUseSelected)) + { + return; + } + this.doNotUseSelected = value; OnPropertyChanged(); Messenger.Send(); @@ -118,8 +126,8 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) return; } - EventHandler handler = Complete; + var handler = Complete; handler?.Invoke(this, new DialogResponseEventArgs(this.dialogCorrelationId, message.Response == ShellDialogButton.Cancel)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorUserControl.xaml.cs b/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorUserControl.xaml.cs index a7c29a06..cfde9ac1 100644 --- a/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorUserControl.xaml.cs +++ b/BudgetAnalyser/Dashboard/CreateNewSurprisePaymentMonitorUserControl.xaml.cs @@ -12,4 +12,4 @@ public CreateNewSurprisePaymentMonitorUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/DashboardController.cs b/BudgetAnalyser/Dashboard/DashboardController.cs index a89867cd..5a75df3f 100644 --- a/BudgetAnalyser/Dashboard/DashboardController.cs +++ b/BudgetAnalyser/Dashboard/DashboardController.cs @@ -52,7 +52,7 @@ public DashboardController( public Guid CorrelationId { - get { return this.doNotUseCorrelationId; } + get => this.doNotUseCorrelationId; private set { this.doNotUseCorrelationId = value; @@ -64,7 +64,7 @@ private set public bool Shown { - get { return this.doNotUseShown; } + get => this.doNotUseShown; set { if (value == this.doNotUseShown) @@ -181,4 +181,4 @@ private void RegisterForMessengerNotifications() Messenger.Register(this, static (r, m) => r.OnApplicationStateRequested(m)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/DashboardUserControl.xaml.cs b/BudgetAnalyser/Dashboard/DashboardUserControl.xaml.cs index cc7d73aa..0d56b4f5 100644 --- a/BudgetAnalyser/Dashboard/DashboardUserControl.xaml.cs +++ b/BudgetAnalyser/Dashboard/DashboardUserControl.xaml.cs @@ -12,4 +12,4 @@ public DashboardUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/EncryptFileController.cs b/BudgetAnalyser/Dashboard/EncryptFileController.cs index 7d281546..21dfb5f1 100644 --- a/BudgetAnalyser/Dashboard/EncryptFileController.cs +++ b/BudgetAnalyser/Dashboard/EncryptFileController.cs @@ -4,8 +4,8 @@ using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Dashboard { @@ -26,8 +26,16 @@ public class EncryptFileController : ControllerBase, IShellDialogInteractivity public EncryptFileController([NotNull] IUiContext uiContext, [NotNull] IApplicationDatabaseFacade appDbService) : base(uiContext.Messenger) { this.appDbService = appDbService; - if (uiContext is null) throw new ArgumentNullException(nameof(uiContext)); - if (appDbService is null) throw new ArgumentNullException(nameof(appDbService)); + if (uiContext is null) + { + throw new ArgumentNullException(nameof(uiContext)); + } + + if (appDbService is null) + { + throw new ArgumentNullException(nameof(appDbService)); + } + this.questionService = uiContext.UserPrompts.YesNoBox; this.messageService = uiContext.UserPrompts.MessageBox; @@ -43,18 +51,9 @@ public EncryptFileController([NotNull] IUiContext uiContext, [NotNull] IApplicat /// /// Will be called to ascertain the availability of the button. /// - public bool CanExecuteOkButton - { - get - { - if (EncryptFileMode) - { - return this.password is not null && this.password.Length > 4 && this.passwordConfirmed; - } - - return this.password is not null && this.password.Length > 4; - } - } + public bool CanExecuteOkButton => EncryptFileMode + ? this.password is not null && this.password.Length > 4 && this.passwordConfirmed + : this.password is not null && this.password.Length > 4; /// /// Will be called to ascertain the availability of the button. @@ -66,7 +65,11 @@ public bool DecryptFileMode get => this.doNotUseDecryptFileMode; private set { - if (value == this.doNotUseDecryptFileMode) return; + if (value == this.doNotUseDecryptFileMode) + { + return; + } + this.doNotUseDecryptFileMode = value; this.doNotUseEncryptFileMode = !value; this.doNotUseEnterPasswordMode = value; @@ -81,7 +84,11 @@ public bool EncryptFileMode get => this.doNotUseEncryptFileMode; private set { - if (value == this.doNotUseEncryptFileMode) return; + if (value == this.doNotUseEncryptFileMode) + { + return; + } + this.doNotUseEncryptFileMode = value; this.doNotUseEnterPasswordMode = !value; this.doNotUseDecryptFileMode = !value; @@ -96,7 +103,11 @@ public bool EnterPasswordMode get => this.doNotUseEnterPasswordMode; private set { - if (value == this.doNotUseEnterPasswordMode) return; + if (value == this.doNotUseEnterPasswordMode) + { + return; + } + this.doNotUseEnterPasswordMode = value; this.doNotUseEncryptFileMode = !value; this.doNotUseDecryptFileMode = !value; @@ -115,7 +126,11 @@ public bool IsEncrypted get => this.doNotUseIsEncrypted; private set { - if(value == this.doNotUseIsEncrypted) return; + if (value == this.doNotUseIsEncrypted) + { + return; + } + this.doNotUseIsEncrypted = value; OnPropertyChanged(); } @@ -126,7 +141,11 @@ public string ValidationMessage get => this.doNotUseValidationMessage; private set { - if (value == this.doNotUseValidationMessage) return; + if (value == this.doNotUseValidationMessage) + { + return; + } + this.doNotUseValidationMessage = value; OnPropertyChanged(); } @@ -166,7 +185,7 @@ internal void SetConfirmedPassword(bool confirmed) { this.passwordConfirmed = confirmed; CommandManager.InvalidateRequerySuggested(); // This stopped working here after the conversion to .NET8. The RelayCommand on ShellDialogController is not refreshed. - Messenger.Send(); + Messenger.Send(); } internal void SetPassword(SecureString newPassword) @@ -181,10 +200,14 @@ private async Task DecryptFiles() { try { - bool? confirmation = this.questionService.Show( + var confirmation = this.questionService.Show( "Are you sure you want to decrypt and store the data files in plain text? After this is complete the files can be read by any other program without a password.", "Decrypt Data Files?"); - if (confirmation is null || !confirmation.Value) return; + if (confirmation is null || !confirmation.Value) + { + return; + } + await Task.Run(async () => await this.appDbService.DecryptFilesAsync(this.password)); this.messageService.Show("Files are decrypted and are saved as plain CSV and XML files. They are no longer protected. Encrypted files have been deleted.", "Decrypt Data Files - Completed"); @@ -197,10 +220,14 @@ private async Task DecryptFiles() private async Task EncryptFiles() { - bool? confirmation = this.questionService.Show( + var confirmation = this.questionService.Show( "Are you sure you want to encrypt and protect the data files? After this is complete the files cannot be read by any other program aside from Budget Analyser. You will be required to enter the password each time you load your Budget Analyser file.", "Encrypt Data Files?"); - if (confirmation is null || !confirmation.Value) return; + if (confirmation is null || !confirmation.Value) + { + return; + } + this.appDbService.SetCredential(this.password); await Task.Run(async () => await this.appDbService.EncryptFilesAsync()); this.messageService.Show( @@ -210,7 +237,10 @@ private async Task EncryptFiles() private async void OnShellDiaglogResponseMessageReceived(ShellDialogResponseMessage message) { - if (!message.IsItForMe(this.dialogCorrelationId)) return; + if (!message.IsItForMe(this.dialogCorrelationId)) + { + return; + } if (message.Response == ShellDialogButton.Cancel) { @@ -247,7 +277,10 @@ private async void OnShellDiaglogResponseMessageReceived(ShellDialogResponseMess private void OnWidgetActivatedMessageReceived(WidgetActivatedMessage message) { - if (message.Handled || !(message.Widget is EncryptWidget)) return; + if (message.Handled || !(message.Widget is EncryptWidget)) + { + return; + } if (this.appDbService.IsEncrypted) { @@ -277,4 +310,4 @@ private void ShowEncryptDecryptDialogCommon() }); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/LoadDemoWidget.cs b/BudgetAnalyser/Dashboard/LoadDemoWidget.cs index 3ac906ce..957d8677 100644 --- a/BudgetAnalyser/Dashboard/LoadDemoWidget.cs +++ b/BudgetAnalyser/Dashboard/LoadDemoWidget.cs @@ -25,4 +25,4 @@ public override void Update([NotNull] params object[] input) ToolTip = "Load a demo to show the basic features of Budget Analyser."; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/PasswordSetMessage.cs b/BudgetAnalyser/Dashboard/PasswordSetMessage.cs index ff09e789..a089d031 100644 --- a/BudgetAnalyser/Dashboard/PasswordSetMessage.cs +++ b/BudgetAnalyser/Dashboard/PasswordSetMessage.cs @@ -6,4 +6,4 @@ public class PasswordSetMessage : MessageBase { public string DatabaseStorageKey { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/ProtectFilesUserControl.xaml.cs b/BudgetAnalyser/Dashboard/ProtectFilesUserControl.xaml.cs index e5fc8a42..fbacfcdc 100644 --- a/BudgetAnalyser/Dashboard/ProtectFilesUserControl.xaml.cs +++ b/BudgetAnalyser/Dashboard/ProtectFilesUserControl.xaml.cs @@ -50,4 +50,4 @@ private void SendPasswordToController() this.controller.SetPassword(this.passwordBox.SecurePassword); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/WidgetActivatedMessage.cs b/BudgetAnalyser/Dashboard/WidgetActivatedMessage.cs index 4342633c..ab37ca35 100644 --- a/BudgetAnalyser/Dashboard/WidgetActivatedMessage.cs +++ b/BudgetAnalyser/Dashboard/WidgetActivatedMessage.cs @@ -13,4 +13,4 @@ public WidgetActivatedMessage(Widget widget) public bool Handled { get; set; } public Widget Widget { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Dashboard/WidgetCommands.cs b/BudgetAnalyser/Dashboard/WidgetCommands.cs index 5d6d943a..62ec4043 100644 --- a/BudgetAnalyser/Dashboard/WidgetCommands.cs +++ b/BudgetAnalyser/Dashboard/WidgetCommands.cs @@ -15,7 +15,7 @@ namespace BudgetAnalyser.Dashboard [AutoRegisterWithIoC] public static class WidgetCommands { - private static RelayCommand WidgetClickedRelayCommand = new(OnWidgetCommandExecuted, WidgetCommandCanExecute); + private static readonly RelayCommand WidgetClickedRelayCommand = new(OnWidgetCommandExecuted, WidgetCommandCanExecute); public static ICommand AddNewBucketMonitorWidgetCommand => new RelayCommand(OnAddNewBucketMonitorWidgetCommandExecute); public static ICommand AddNewFixedBudgetMonitorWidgetCommand => new RelayCommand(OnAddNewFixedBudgetMonitorWidgetCommandExecute); @@ -48,7 +48,11 @@ public static class WidgetCommands public static void DeregisterForWidgetChanges(IEnumerable widgetGroups) { - if (widgetGroups is null) return; + if (widgetGroups is null) + { + return; + } + widgetGroups.SelectMany(w => w.Widgets) .ToList() .ForEach(w => w.PropertyChanged -= OnWidgetDataUpdated); @@ -59,7 +63,11 @@ public static void DeregisterForWidgetChanges(IEnumerable widgetGro /// public static void ListenForWidgetChanges(IEnumerable widgetGroups) { - if (widgetGroups is null) return; + if (widgetGroups is null) + { + return; + } + widgetGroups.SelectMany(w => w.Widgets) .ToList() .ForEach(w => w.PropertyChanged += OnWidgetDataUpdated); @@ -86,7 +94,7 @@ private static void OnRemoveWidgetCommandExecute(Widget widget) var fixedProject = widget as FixedBudgetMonitorWidget; if (fixedProject is not null) { - bool? result = QuestionBoxService.Show( + var result = QuestionBoxService.Show( "Remove Widget", "Are you sure you want to remove the Fixed Budget Project Widget '{0}'?\n\nOnce removed, it cannot be undone. All assigned transactions will be remain in the project bucket. Any unsaved edits will also be committed.", fixedProject.Id); @@ -117,12 +125,15 @@ private static bool WidgetCommandCanExecute(Widget widget) private static void OnWidgetDataUpdated(object? sender, PropertyChangedEventArgs e) { - var widget = sender as Widget; - if (widget is null) return; + if (sender is not Widget widget) + { + return; + } + if (e.PropertyName is nameof(widget.Clickable) or nameof(widget.Enabled)) { Dispatcher.CurrentDispatcher.BeginInvoke(WidgetClickedRelayCommand.NotifyCanExecuteChanged, DispatcherPriority.ApplicationIdle); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/DemoFileHelper.cs b/BudgetAnalyser/DemoFileHelper.cs index cfdbfce3..e10a8920 100644 --- a/BudgetAnalyser/DemoFileHelper.cs +++ b/BudgetAnalyser/DemoFileHelper.cs @@ -12,11 +12,11 @@ public class DemoFileHelper public string FindDemoFile() { - string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + var folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Debug.Assert(folder is not null); for (var failsafe = 0; failsafe < 10; failsafe++) { - string path = Path.Combine(folder, DemoFileName); + var path = Path.Combine(folder, DemoFileName); if (FileExists(path)) { return path; @@ -39,4 +39,4 @@ protected virtual bool FileExists(string path) return File.Exists(path); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/DisuedRulesUserControl.xaml.cs b/BudgetAnalyser/Filtering/DisuedRulesUserControl.xaml.cs index 716f705c..c969cfbf 100644 --- a/BudgetAnalyser/Filtering/DisuedRulesUserControl.xaml.cs +++ b/BudgetAnalyser/Filtering/DisuedRulesUserControl.xaml.cs @@ -10,4 +10,4 @@ public DisusedRulesUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/FilterAppliedMessage.cs b/BudgetAnalyser/Filtering/FilterAppliedMessage.cs index 85eb0fb4..dbe9e50b 100644 --- a/BudgetAnalyser/Filtering/FilterAppliedMessage.cs +++ b/BudgetAnalyser/Filtering/FilterAppliedMessage.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine; +using BudgetAnalyser.Engine; using Rees.Wpf; namespace BudgetAnalyser.Filtering @@ -13,4 +13,4 @@ public FilterAppliedMessage(object sender, GlobalFilterCriteria criteria) public GlobalFilterCriteria Criteria { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/GlobalDateFilterView.xaml.cs b/BudgetAnalyser/Filtering/GlobalDateFilterView.xaml.cs index d1088825..95bc6d4b 100644 --- a/BudgetAnalyser/Filtering/GlobalDateFilterView.xaml.cs +++ b/BudgetAnalyser/Filtering/GlobalDateFilterView.xaml.cs @@ -12,4 +12,4 @@ public GlobalDateFilterView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/GlobalFilterController.cs b/BudgetAnalyser/Filtering/GlobalFilterController.cs index da29fcd6..fdcf6f46 100644 --- a/BudgetAnalyser/Filtering/GlobalFilterController.cs +++ b/BudgetAnalyser/Filtering/GlobalFilterController.cs @@ -54,7 +54,8 @@ public GlobalFilterController([NotNull] UiContext uiContext) : base(uiContext.Me public string AccountTypeSummary { - [UsedImplicitly] get => this.doNotUseAccountTypeSummary; + [UsedImplicitly] + get => this.doNotUseAccountTypeSummary; private set { this.doNotUseAccountTypeSummary = value; @@ -88,7 +89,8 @@ public GlobalFilterCriteria Criteria public string DateSummaryLine1 { - [UsedImplicitly] get => this.doNotUseDateSummaryLine1; + [UsedImplicitly] + get => this.doNotUseDateSummaryLine1; private set { this.doNotUseDateSummaryLine1 = value; @@ -98,7 +100,8 @@ private set public string DateSummaryLine2 { - [UsedImplicitly] get => this.doNotUseDateSummaryLine2; + [UsedImplicitly] + get => this.doNotUseDateSummaryLine2; private set { this.doNotUseDateSummaryLine2 = value; @@ -283,4 +286,4 @@ private void UpdateSummaries() DateSummaryLine2 = string.Format(CultureInfo.CurrentCulture, "up until: {0:d}", Criteria.EndDate.Value); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/RequestFilterChangeMessage.cs b/BudgetAnalyser/Filtering/RequestFilterChangeMessage.cs index a96fb9b1..ec1ccea8 100644 --- a/BudgetAnalyser/Filtering/RequestFilterChangeMessage.cs +++ b/BudgetAnalyser/Filtering/RequestFilterChangeMessage.cs @@ -12,4 +12,4 @@ public RequestFilterChangeMessage(object sender) public GlobalFilterCriteria Criteria { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Filtering/RequestFilterMessage.cs b/BudgetAnalyser/Filtering/RequestFilterMessage.cs index f0e827d9..13303901 100644 --- a/BudgetAnalyser/Filtering/RequestFilterMessage.cs +++ b/BudgetAnalyser/Filtering/RequestFilterMessage.cs @@ -12,4 +12,4 @@ public RequestFilterMessage(object sender) public GlobalFilterCriteria Criteria { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/GlobalSuppressions.cs b/BudgetAnalyser/GlobalSuppressions.cs index 4104fc2f..7d4a47a5 100644 Binary files a/BudgetAnalyser/GlobalSuppressions.cs and b/BudgetAnalyser/GlobalSuppressions.cs differ diff --git a/BudgetAnalyser/GlobalUsing.cs b/BudgetAnalyser/GlobalUsing.cs index ea1fe989..2d85688a 100644 --- a/BudgetAnalyser/GlobalUsing.cs +++ b/BudgetAnalyser/GlobalUsing.cs @@ -1 +1 @@ -global using NotNullAttribute = JetBrains.Annotations.NotNullAttribute; \ No newline at end of file +global using NotNullAttribute = JetBrains.Annotations.NotNullAttribute; diff --git a/BudgetAnalyser/IShowableController.cs b/BudgetAnalyser/IShowableController.cs index bff818d1..a3d0a714 100644 --- a/BudgetAnalyser/IShowableController.cs +++ b/BudgetAnalyser/IShowableController.cs @@ -1,4 +1,4 @@ -namespace BudgetAnalyser +namespace BudgetAnalyser { /// /// An interface that uses a data bound Shown property to show or hide the controller @@ -8,4 +8,4 @@ public interface IShowableController { bool Shown { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/IUiContext.cs b/BudgetAnalyser/IUiContext.cs index be08b403..04dbf8c7 100644 --- a/BudgetAnalyser/IUiContext.cs +++ b/BudgetAnalyser/IUiContext.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Budget; +using BudgetAnalyser.Budget; using BudgetAnalyser.Dashboard; using BudgetAnalyser.Engine; using BudgetAnalyser.Filtering; @@ -42,4 +42,4 @@ public interface IUiContext StatementController StatementController { get; } UserPrompts UserPrompts { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/InputBox.xaml.cs b/BudgetAnalyser/InputBox.xaml.cs index 06e03333..d2725e41 100644 --- a/BudgetAnalyser/InputBox.xaml.cs +++ b/BudgetAnalyser/InputBox.xaml.cs @@ -29,4 +29,4 @@ private void OnOkButtonClick(object sender, RoutedEventArgs e) Close(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/AddLedgerReconciliationController.cs b/BudgetAnalyser/LedgerBook/AddLedgerReconciliationController.cs index ae570aba..f0753144 100644 --- a/BudgetAnalyser/LedgerBook/AddLedgerReconciliationController.cs +++ b/BudgetAnalyser/LedgerBook/AddLedgerReconciliationController.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Windows.Input; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.BankAccount; @@ -28,7 +28,7 @@ public class AddLedgerReconciliationController : ControllerBase, IShellDialogToo public AddLedgerReconciliationController( UiContext uiContext, - IAccountTypeRepository accountTypeRepository) + IAccountTypeRepository accountTypeRepository) : base(uiContext.Messenger) { this.accountTypeRepository = accountTypeRepository ?? throw new ArgumentNullException(nameof(accountTypeRepository)); @@ -56,7 +56,11 @@ public bool AddBalanceVisibility get => this.doNotUseAddBalanceVisibility; private set { - if (value == this.doNotUseAddBalanceVisibility) return; + if (value == this.doNotUseAddBalanceVisibility) + { + return; + } + this.doNotUseAddBalanceVisibility = value; OnPropertyChanged(); } @@ -64,17 +68,18 @@ private set public ICommand AddBankBalanceCommand => new RelayCommand(OnAddBankBalanceCommandExecuted, CanExecuteAddBankBalanceCommand); - public decimal? AdjustedBankBalanceTotal - { - get { return AddBalanceVisibility ? default(decimal?) : BankBalances.Sum(b => b.AdjustedBalance); } - } + public decimal? AdjustedBankBalanceTotal => AddBalanceVisibility ? default(decimal?) : BankBalances.Sum(b => b.AdjustedBalance); public IEnumerable BankAccounts { get => this.doNotUseBankAccounts; private set { - if (Object.ReferenceEquals(value, this.doNotUseBankAccounts)) return; + if (object.ReferenceEquals(value, this.doNotUseBankAccounts)) + { + return; + } + this.doNotUseBankAccounts = value; OnPropertyChanged(); } @@ -85,7 +90,11 @@ public decimal BankBalance get => this.doNotUseBankBalance; set { - if (value == this.doNotUseBankBalance) return; + if (value == this.doNotUseBankBalance) + { + return; + } + this.doNotUseBankBalance = value; OnPropertyChanged(); OnPropertyChanged(nameof(BankBalanceTotal)); @@ -99,18 +108,7 @@ public decimal BankBalance public bool Canceled { get; private set; } public bool CanExecuteCancelButton => true; - public bool CanExecuteOkButton - { - get - { - if (CreateMode) - { - return Date != DateTime.MinValue && HasRequiredBalances; - } - - return Editable && Date != DateTime.MinValue && HasRequiredBalances; - } - } + public bool CanExecuteOkButton => CreateMode ? Date != DateTime.MinValue && HasRequiredBalances : Editable && Date != DateTime.MinValue && HasRequiredBalances; public bool CanExecuteSaveButton => false; public string CloseButtonToolTip => "Cancel"; @@ -121,7 +119,11 @@ public DateTime Date get => this.doNotUseDate; set { - if (Equals(value, this.doNotUseDate)) return; + if (Equals(value, this.doNotUseDate)) + { + return; + } + this.doNotUseDate = value; OnPropertyChanged(); Messenger.Send(); @@ -133,7 +135,11 @@ public bool Editable get => this.doNotUseEditable; private set { - if (Equals(value, this.doNotUseEditable)) return; + if (Equals(value, this.doNotUseEditable)) + { + return; + } + this.doNotUseEditable = value; OnPropertyChanged(); Messenger.Send(); @@ -220,12 +226,7 @@ private bool CanExecuteAddBankBalanceCommand() return false; } - if (!AddBalanceVisibility) - { - return true; - } - - return SelectedBankAccount is not null; + return !AddBalanceVisibility ? true : SelectedBankAccount is not null; } private void OnAddBankBalanceCommandExecuted() @@ -294,7 +295,7 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) } } - EventHandler handler = Complete; + var handler = Complete; handler?.Invoke(this, new EditBankBalancesEventArgs { Canceled = Canceled }); } finally @@ -315,7 +316,7 @@ private void Reset() private void ShowDialogCommon(string title) { Canceled = false; - List accountsToShow = this.accountTypeRepository.ListCurrentlyUsedAccountTypes().ToList(); + var accountsToShow = this.accountTypeRepository.ListCurrentlyUsedAccountTypes().ToList(); BankAccounts = accountsToShow.OrderBy(a => a.Name); SelectedBankAccount = null; if (CreateMode) @@ -336,4 +337,4 @@ private void ShowDialogCommon(string title) Messenger.Send(dialogRequest); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/AddLedgerReconciliationUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/AddLedgerReconciliationUserControl.xaml.cs index 42bccb2c..3b7e3722 100644 --- a/BudgetAnalyser/LedgerBook/AddLedgerReconciliationUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/AddLedgerReconciliationUserControl.xaml.cs @@ -36,9 +36,8 @@ private void OnBankBalanceMouseUp(object sender, MouseButtonEventArgs e) private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { - if (e.NewValue is bool) + if (e.NewValue is bool visible) { - var visible = (bool)e.NewValue; if (visible) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => this.BankBalance.Focus()); @@ -48,8 +47,11 @@ private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArg private void OnBankBalanceKeyDown(object sender, KeyEventArgs e) { - var balanceBox = sender as TextBox; - if (balanceBox is null) return; + if (sender is not TextBox balanceBox) + { + return; + } + switch (e.Key) { case Key.Decimal: @@ -68,8 +70,11 @@ private void OnBankBalanceKeyDown(object sender, KeyEventArgs e) private void OnBankBalanceKeyUp(object sender, KeyEventArgs e) { - var balanceBox = sender as TextBox; - if (balanceBox is null) return; + if (sender is not TextBox balanceBox) + { + return; + } + switch (e.Key) { case Key.Back: @@ -85,4 +90,4 @@ private void OnBankBalanceKeyUp(object sender, KeyEventArgs e) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/BankBalanceUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/BankBalanceUserControl.xaml.cs index 87a911ee..80b4c4f7 100644 --- a/BudgetAnalyser/LedgerBook/BankBalanceUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/BankBalanceUserControl.xaml.cs @@ -12,4 +12,4 @@ public BankBalanceUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/BankBalanceViewModel.cs b/BudgetAnalyser/LedgerBook/BankBalanceViewModel.cs index 90fcd0c4..8a62f967 100644 --- a/BudgetAnalyser/LedgerBook/BankBalanceViewModel.cs +++ b/BudgetAnalyser/LedgerBook/BankBalanceViewModel.cs @@ -42,4 +42,4 @@ public decimal AdjustedBalance [UsedImplicitly] public bool ShowAdjustedBalance => this.line is not null; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/EditBankBalancesEventArgs.cs b/BudgetAnalyser/LedgerBook/EditBankBalancesEventArgs.cs index 4b6678df..21621322 100644 --- a/BudgetAnalyser/LedgerBook/EditBankBalancesEventArgs.cs +++ b/BudgetAnalyser/LedgerBook/EditBankBalancesEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.LedgerBook { @@ -6,4 +6,4 @@ public class EditBankBalancesEventArgs : EventArgs { public bool Canceled { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/ILedgerBookGridBuilder.cs b/BudgetAnalyser/LedgerBook/ILedgerBookGridBuilder.cs index 00711a1a..9988d2f5 100644 --- a/BudgetAnalyser/LedgerBook/ILedgerBookGridBuilder.cs +++ b/BudgetAnalyser/LedgerBook/ILedgerBookGridBuilder.cs @@ -1,4 +1,4 @@ -using System.Windows; +using System.Windows; using System.Windows.Controls; namespace BudgetAnalyser.LedgerBook @@ -14,4 +14,4 @@ void BuildGrid( [NotNull] ContentPresenter contentPanel, int numberOfPeriodsToShow); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookController.cs b/BudgetAnalyser/LedgerBook/LedgerBookController.cs index 6124d978..81903f40 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookController.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookController.cs @@ -1,4 +1,4 @@ -using System.Windows.Input; +using System.Windows.Input; using BudgetAnalyser.Budget; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; @@ -70,7 +70,11 @@ public int NumberOfPeriodsToShow get => this.doNotUseNumberOfPeriodsToShow; set { - if (value == this.doNotUseNumberOfPeriodsToShow) return; + if (value == this.doNotUseNumberOfPeriodsToShow) + { + return; + } + this.doNotUseNumberOfPeriodsToShow = value; OnPropertyChanged(); } @@ -238,8 +242,7 @@ private void OnAddNewLedgerComplete(object sender, BudgetBucketChosenEventArgs e return; } - var expenseBucket = e.SelectedBucket as ExpenseBucket; - if (expenseBucket is null) + if (e.SelectedBucket is not ExpenseBucket expenseBucket) { this.messageBox.Show("You must select an expense budget bucket to track when adding a new Ledger Column."); return; @@ -398,4 +401,4 @@ private void RaiseLedgerBookUpdated() var handler = LedgerBookUpdated; handler?.Invoke(this, EventArgs.Empty); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookControllerFileOperations.cs b/BudgetAnalyser/LedgerBook/LedgerBookControllerFileOperations.cs index f229a37b..dcdd366d 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookControllerFileOperations.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookControllerFileOperations.cs @@ -33,7 +33,10 @@ internal bool Dirty { this.doNotUseDirty = value; OnPropertyChanged(); - if (value) this.applicationDatabaseService.NotifyOfChange(ApplicationDataType.Ledger); + if (value) + { + this.applicationDatabaseService.NotifyOfChange(ApplicationDataType.Ledger); + } } } @@ -69,4 +72,4 @@ internal void SyncDataFromLedgerService() ViewModel.LedgerBook = LedgerService.LedgerBook; MessengerInstance.Send(new LedgerBookReadyMessage(ViewModel.LedgerBook) { ForceUiRefresh = true }); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderFactory.cs b/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderFactory.cs index 4c18836a..7bc05d66 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderFactory.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderFactory.cs @@ -7,12 +7,9 @@ public class LedgerBookGridBuilderFactory { public virtual ILedgerBookGridBuilder GridBuilderV2([NotNull] LedgerBookController ledgerBookController) { - if (ledgerBookController is null) - { - throw new ArgumentNullException(nameof(ledgerBookController)); - } - - return new LedgerBookGridBuilderV2( + return ledgerBookController is null + ? throw new ArgumentNullException(nameof(ledgerBookController)) + : (ILedgerBookGridBuilder)new LedgerBookGridBuilderV2( ledgerBookController.ShowTransactionsCommand, ledgerBookController.ShowBankBalancesCommand, ledgerBookController.ShowRemarksCommand, @@ -21,4 +18,4 @@ public virtual ILedgerBookGridBuilder GridBuilderV2([NotNull] LedgerBookControll ledgerBookController.ShowLedgerBucketDetailsCommand); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderV2.cs b/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderV2.cs index 27df52ef..72495055 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderV2.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookGridBuilderV2.cs @@ -117,13 +117,11 @@ private TextBlock AddContentToGrid(FrameworkElement parent, string content, ref { panel.Children.Add(textBlock); } - else if (decorator is not null) - { - decorator.Child = textBlock; - } else { - throw new ArgumentException($"{nameof(parent)} is not a Panel nor a Decorator", nameof(parent)); + decorator.Child = decorator is not null + ? (UIElement)textBlock + : throw new ArgumentException($"{nameof(parent)} is not a Panel nor a Decorator", nameof(parent)); } return textBlock; @@ -534,12 +532,7 @@ private void DynamicallyCreateLedgerBookGrid(int numberOfPeriodsToShow) private object FindResource(string resourceName) { var localResource = this.localResources[resourceName]; - if (localResource is not null) - { - return localResource; - } - - return Application.Current.FindResource(resourceName); + return localResource is not null ? localResource : Application.Current.FindResource(resourceName); } private static Brush StripColour(LedgerBucket ledger) @@ -549,11 +542,6 @@ private static Brush StripColour(LedgerBucket ledger) return ConverterHelper.SpentPeriodicallyBucketBrush; } - if (ledger.BudgetBucket is SavedUpForExpenseBucket) - { - return ConverterHelper.AccumulatedBucketBrush; - } - - return ConverterHelper.TileBackgroundBrush; + return ledger.BudgetBucket is SavedUpForExpenseBucket ? ConverterHelper.AccumulatedBucketBrush : ConverterHelper.TileBackgroundBrush; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookReadyMessage.cs b/BudgetAnalyser/LedgerBook/LedgerBookReadyMessage.cs index e62fd9c2..db7a8aeb 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookReadyMessage.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookReadyMessage.cs @@ -12,4 +12,4 @@ public LedgerBookReadyMessage(Engine.Ledger.LedgerBook ledgerBook) public bool ForceUiRefresh { get; set; } public Engine.Ledger.LedgerBook LedgerBook { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerBookUserControl.xaml.cs index bcc12bca..f5bd0736 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookUserControl.xaml.cs @@ -90,4 +90,4 @@ private void ResetLedgerBookContent() { this.LedgerBookPanel.Content = null; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBookViewModel.cs b/BudgetAnalyser/LedgerBook/LedgerBookViewModel.cs index 4a77a44a..cbcf4d2a 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBookViewModel.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBookViewModel.cs @@ -22,7 +22,11 @@ public Engine.Ledger.LedgerBook? LedgerBook set { - if (Equals(value, this.doNotUseLedgerBook)) return; + if (Equals(value, this.doNotUseLedgerBook)) + { + return; + } + this.doNotUseLedgerBook = value; OnPropertyChanged(); OnPropertyChanged(nameof(NoLedgerBookLoaded)); @@ -43,7 +47,7 @@ public Engine.Ledger.LedgerBook? LedgerBook /// internal IBudgetCurrencyContext? CurrentBudget { - get { return this.doNotUseCurrentBudget; } + get => this.doNotUseCurrentBudget; set { this.doNotUseCurrentBudget = value; @@ -57,7 +61,11 @@ internal StatementModel? CurrentStatement set { - if (Equals(value, this.doNotUseCurrentStatement)) return; + if (Equals(value, this.doNotUseCurrentStatement)) + { + return; + } + this.doNotUseCurrentStatement = value; OnPropertyChanged(); OnPropertyChanged(nameof(NoStatementLoaded)); @@ -73,10 +81,14 @@ public LedgerEntryLine? NewLedgerLine get => this.doNotUseNewLedgerLine; set { - if (Equals(value, this.doNotUseNewLedgerLine)) return; + if (Equals(value, this.doNotUseNewLedgerLine)) + { + return; + } + this.doNotUseNewLedgerLine = value; OnPropertyChanged(); } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBucketHistoryUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerBucketHistoryUserControl.xaml.cs index f702b91c..82a1e748 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBucketHistoryUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBucketHistoryUserControl.xaml.cs @@ -12,4 +12,4 @@ public LedgerBucketHistoryUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBucketView.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerBucketView.xaml.cs index 42c37d9b..0a9aa7e8 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBucketView.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBucketView.xaml.cs @@ -12,4 +12,4 @@ public LedgerBucketView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerBucketViewController.cs b/BudgetAnalyser/LedgerBook/LedgerBucketViewController.cs index 1953461f..3d27e7d7 100644 --- a/BudgetAnalyser/LedgerBook/LedgerBucketViewController.cs +++ b/BudgetAnalyser/LedgerBook/LedgerBucketViewController.cs @@ -7,8 +7,8 @@ using BudgetAnalyser.Engine.Services; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.LedgerBook { @@ -54,7 +54,7 @@ public LedgerBucketViewController([NotNull] IAccountTypeRepository accountRepo, [UsedImplicitly] public decimal BudgetAmount { get; private set; } - + [UsedImplicitly] public BudgetCycle BudgetCycle { get; private set; } @@ -132,7 +132,7 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) } this.ledgerService.MoveLedgerToAccount(this.ledger, StoredInAccount); - EventHandler handler = Updated; + var handler = Updated; handler?.Invoke(this, EventArgs.Empty); } finally @@ -149,4 +149,4 @@ private void Reset() StoredInAccount = null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerRemarksController.cs b/BudgetAnalyser/LedgerBook/LedgerRemarksController.cs index 546f55fc..248e7d3a 100644 --- a/BudgetAnalyser/LedgerBook/LedgerRemarksController.cs +++ b/BudgetAnalyser/LedgerBook/LedgerRemarksController.cs @@ -36,7 +36,7 @@ public LedgerRemarksController([NotNull] UiContext uiContext, [NotNull] IReconci public bool IsReadOnly { - get { return this.doNotUseIsReadOnly; } + get => this.doNotUseIsReadOnly; private set { this.doNotUseIsReadOnly = value; @@ -46,7 +46,7 @@ private set public LedgerEntryLine LedgerEntryLine { - get { return this.doNotUseLedgerEntryLine; } + get => this.doNotUseLedgerEntryLine; private set { this.doNotUseLedgerEntryLine = value; @@ -56,7 +56,7 @@ private set public string Remarks { - get { return this.doNotUseRemarks; } + get => this.doNotUseRemarks; set { this.doNotUseRemarks = value; @@ -93,8 +93,8 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) LedgerEntryLine = null; Remarks = null; - EventHandler handler = Completed; + var handler = Completed; handler?.Invoke(this, EventArgs.Empty); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerRemarksUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerRemarksUserControl.xaml.cs index d38d3f2c..024aa659 100644 --- a/BudgetAnalyser/LedgerBook/LedgerRemarksUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerRemarksUserControl.xaml.cs @@ -23,4 +23,4 @@ private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArg } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerTransactionCommands.cs b/BudgetAnalyser/LedgerBook/LedgerTransactionCommands.cs index 04750807..b5240c98 100644 --- a/BudgetAnalyser/LedgerBook/LedgerTransactionCommands.cs +++ b/BudgetAnalyser/LedgerBook/LedgerTransactionCommands.cs @@ -32,4 +32,4 @@ private static void OnNavigateToTransactionCommandExecute([NotNull] Guid? transa } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerTransactionEventArgs.cs b/BudgetAnalyser/LedgerBook/LedgerTransactionEventArgs.cs index 7ca3009b..a1d31225 100644 --- a/BudgetAnalyser/LedgerBook/LedgerTransactionEventArgs.cs +++ b/BudgetAnalyser/LedgerBook/LedgerTransactionEventArgs.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace BudgetAnalyser.LedgerBook { @@ -11,4 +11,4 @@ public LedgerTransactionEventArgs(bool wasChanged) public bool WasModified { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerTransactionUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerTransactionUserControl.xaml.cs index 09736667..1559e8a5 100644 --- a/BudgetAnalyser/LedgerBook/LedgerTransactionUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerTransactionUserControl.xaml.cs @@ -16,29 +16,9 @@ public LedgerTransactionUserControl() DataContextChanged += OnDataContextChanged; } - public decimal? Credit - { - get - { - if (LedgerTransaction is null) - { - return null; - } - return LedgerTransaction.Amount >= 0 ? LedgerTransaction.Amount : 0M; - } - } + public decimal? Credit => LedgerTransaction is null ? null : LedgerTransaction.Amount >= 0 ? LedgerTransaction.Amount : 0M; - public decimal? Debit - { - get - { - if (LedgerTransaction is null) - { - return null; - } - return LedgerTransaction.Amount < 0 ? -LedgerTransaction.Amount : 0M; - } - } + public decimal? Debit => LedgerTransaction is null ? null : LedgerTransaction.Amount < 0 ? -LedgerTransaction.Amount : 0M; private LedgerTransaction LedgerTransaction => (LedgerTransaction)DataContext; @@ -63,4 +43,4 @@ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventA } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerTransactionsController.cs b/BudgetAnalyser/LedgerBook/LedgerTransactionsController.cs index 7adee263..90f4f581 100644 --- a/BudgetAnalyser/LedgerBook/LedgerTransactionsController.cs +++ b/BudgetAnalyser/LedgerBook/LedgerTransactionsController.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -74,7 +74,7 @@ public LedgerTransactionsController([NotNull] UiContext uiContext, [NotNull] ILe public bool IsReadOnly { - get { return this.doNotUseIsReadOnly; } + get => this.doNotUseIsReadOnly; set { this.doNotUseIsReadOnly = value; @@ -85,7 +85,7 @@ public bool IsReadOnly public LedgerEntry LedgerEntry { - get { return this.doNotUseLedgerEntry; } + get => this.doNotUseLedgerEntry; private set { this.doNotUseLedgerEntry = value; @@ -97,7 +97,7 @@ private set public Account NewTransactionAccount { - get { return this.doNotUseNewTransactionAccount; } + get => this.doNotUseNewTransactionAccount; set { this.doNotUseNewTransactionAccount = value; @@ -107,7 +107,7 @@ public Account NewTransactionAccount public decimal NewTransactionAmount { - get { return this.doNotUseNewTransactionAmount; } + get => this.doNotUseNewTransactionAmount; set { this.doNotUseNewTransactionAmount = value; @@ -117,7 +117,7 @@ public decimal NewTransactionAmount public string NewTransactionNarrative { - get { return this.doNotUseNewTransactionNarrative; } + get => this.doNotUseNewTransactionNarrative; set { this.doNotUseNewTransactionNarrative = value; @@ -129,7 +129,7 @@ public string NewTransactionNarrative public bool ShowAddingNewTransactionPanel { - get { return this.doNotUseShowAddingNewTransactionPanel; } + get => this.doNotUseShowAddingNewTransactionPanel; private set { this.doNotUseShowAddingNewTransactionPanel = value; @@ -141,7 +141,7 @@ private set public string Title { - get { return this.doNotUseTitle; } + get => this.doNotUseTitle; private set { this.doNotUseTitle = value; @@ -270,7 +270,7 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) LedgerEntry = null; } - EventHandler handler = Complete; + var handler = Complete; handler?.Invoke(this, new LedgerTransactionEventArgs(this.wasChanged)); Reset(); @@ -315,17 +315,25 @@ private void Reset() private decimal RetrieveOpeningBalance() { var book = this.ledgerService.LedgerBook; - bool found = false; - IEnumerable remainingRecons = book.Reconciliations.SkipWhile(r => + var found = false; + var remainingRecons = book.Reconciliations.SkipWhile(r => { // Find the recon that directly precedes this current one. - if (found) return false; // Found recon line on previous pass, now return. + if (found) + { + return false; // Found recon line on previous pass, now return. + } + found = r.Entries.Contains(LedgerEntry); return true; // Keep skipping... }).Take(1); - LedgerEntryLine previousLine = remainingRecons.FirstOrDefault(); - if (previousLine is null) return 0M; + var previousLine = remainingRecons.FirstOrDefault(); + if (previousLine is null) + { + return 0M; + } + var previousEntry = previousLine.Entries.FirstOrDefault(l => l.LedgerBucket == LedgerEntry.LedgerBucket); return previousEntry?.Balance ?? 0M; } @@ -352,7 +360,7 @@ private void Save() private void SaveBalanceAdjustment() { - LedgerTransaction newTransaction = this.reconService.CreateBalanceAdjustment(this.entryLine, NewTransactionAmount, NewTransactionNarrative, NewTransactionAccount); + var newTransaction = this.reconService.CreateBalanceAdjustment(this.entryLine, NewTransactionAmount, NewTransactionNarrative, NewTransactionAccount); ShownTransactions.Add(newTransaction); this.wasChanged = true; OnPropertyChanged(nameof(TransactionsTotal)); @@ -388,4 +396,4 @@ private void ShowDialogCommon(bool isNew) Messenger.Send(dialogRequest); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/LedgerTransactionsUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/LedgerTransactionsUserControl.xaml.cs index fd3724e2..ab9c0a74 100644 --- a/BudgetAnalyser/LedgerBook/LedgerTransactionsUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/LedgerTransactionsUserControl.xaml.cs @@ -23,4 +23,4 @@ private void OnNewTransactionVisibilityChanged(object sender, DependencyProperty } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/ReconciliationToDoListController.cs b/BudgetAnalyser/LedgerBook/ReconciliationToDoListController.cs index 2e0756a0..f85813aa 100644 --- a/BudgetAnalyser/LedgerBook/ReconciliationToDoListController.cs +++ b/BudgetAnalyser/LedgerBook/ReconciliationToDoListController.cs @@ -24,7 +24,8 @@ public ReconciliationToDoListController([NotNull] IMessenger messenger, [NotNull public bool AddingNewTask { - [UsedImplicitly] get => this.doNotUseAddingNewTask; + [UsedImplicitly] + get => this.doNotUseAddingNewTask; private set { this.doNotUseAddingNewTask = value; @@ -107,4 +108,4 @@ private void OnRemoveTaskCommandExecuted(ToDoTask task) Tasks.Remove(task); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/ReconciliationToDoListUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/ReconciliationToDoListUserControl.xaml.cs index 1174f6e3..bc4eaa3d 100644 --- a/BudgetAnalyser/LedgerBook/ReconciliationToDoListUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/ReconciliationToDoListUserControl.xaml.cs @@ -19,14 +19,13 @@ public ReconciliationToDoListUserControl() private void OnListDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { - ICollectionView view = CollectionViewSource.GetDefaultView(Controller.Tasks); + var view = CollectionViewSource.GetDefaultView(Controller.Tasks); view.SortDescriptions.Add(new SortDescription("SystemGenerated", ListSortDirection.Descending)); } private void OnUnloaded(object sender, RoutedEventArgs e) { - var controller = DataContext as ReconciliationToDoListController; - if (controller is null) + if (DataContext is not ReconciliationToDoListController controller) { return; } @@ -34,4 +33,4 @@ private void OnUnloaded(object sender, RoutedEventArgs e) controller.Close(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/ShowSurplusBalancesController.cs b/BudgetAnalyser/LedgerBook/ShowSurplusBalancesController.cs index 56236cbb..a7784a04 100644 --- a/BudgetAnalyser/LedgerBook/ShowSurplusBalancesController.cs +++ b/BudgetAnalyser/LedgerBook/ShowSurplusBalancesController.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Windows.Input; using BudgetAnalyser.Engine; @@ -24,14 +24,9 @@ public ShowSurplusBalancesController(IMessenger messenger) : base(messenger) [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Instance method required for data binding")] [UsedImplicitly] - public ICommand RemoveBankBalanceCommand - { - get - { + public ICommand RemoveBankBalanceCommand => // This is here solely to disable the Remove Bank Balance button on the default DataTemplate that displays the BankBalance type. - return new RelayCommand(b => { }, b => false); - } - } + new RelayCommand(b => { }, b => false); public ObservableCollection SurplusBalances { get; private set; } @@ -57,4 +52,4 @@ public void ShowDialog([NotNull] LedgerEntryLine ledgerLine) Messenger.Send(dialogRequest); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/ShowSurplusBalancesUserControl.xaml.cs b/BudgetAnalyser/LedgerBook/ShowSurplusBalancesUserControl.xaml.cs index 07cd3f19..36f1b7f1 100644 --- a/BudgetAnalyser/LedgerBook/ShowSurplusBalancesUserControl.xaml.cs +++ b/BudgetAnalyser/LedgerBook/ShowSurplusBalancesUserControl.xaml.cs @@ -12,4 +12,4 @@ public ShowSurplusBalancesUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/TransferFundsController.cs b/BudgetAnalyser/LedgerBook/TransferFundsController.cs index 583912bc..b2ef1808 100644 --- a/BudgetAnalyser/LedgerBook/TransferFundsController.cs +++ b/BudgetAnalyser/LedgerBook/TransferFundsController.cs @@ -64,11 +64,12 @@ public void ShowDialog(IEnumerable ledgerBuckets) private bool IsOkToSave() { - if (!TransferFundsDto.IsValid) return false; - if (TransferFundsDto.BankTransferRequired) - return BankTransferConfirmed; + if (!TransferFundsDto.IsValid) + { + return false; + } - return true; + return TransferFundsDto.BankTransferRequired ? BankTransferConfirmed : true; } private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) @@ -95,4 +96,4 @@ private void Reset() LedgerBuckets = null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/LedgerBook/TransferFundsView.xaml.cs b/BudgetAnalyser/LedgerBook/TransferFundsView.xaml.cs index 8d35c6be..1bb6a9f7 100644 --- a/BudgetAnalyser/LedgerBook/TransferFundsView.xaml.cs +++ b/BudgetAnalyser/LedgerBook/TransferFundsView.xaml.cs @@ -12,4 +12,4 @@ public TransferFundsView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/MainMenuController.cs b/BudgetAnalyser/MainMenuController.cs index e595575c..d8cd3610 100644 --- a/BudgetAnalyser/MainMenuController.cs +++ b/BudgetAnalyser/MainMenuController.cs @@ -52,7 +52,7 @@ public MainMenuController( public bool BudgetToggle { - get { return this.doNotUseBudgetToggle; } + get => this.doNotUseBudgetToggle; set { this.doNotUseBudgetToggle = value; @@ -64,7 +64,7 @@ public bool BudgetToggle public bool DashboardToggle { - get { return this.doNotUseDashboardToggle; } + get => this.doNotUseDashboardToggle; set { this.doNotUseDashboardToggle = value; @@ -77,7 +77,7 @@ public bool DashboardToggle public bool LedgerBookToggle { - get { return this.doNotUseLedgerBookToggle; } + get => this.doNotUseLedgerBookToggle; set { this.doNotUseLedgerBookToggle = value; @@ -90,7 +90,7 @@ public bool LedgerBookToggle public bool ReportsToggle { - get { return this.doNotUseReportsToggle; } + get => this.doNotUseReportsToggle; set { this.doNotUseReportsToggle = value; @@ -103,7 +103,7 @@ public bool ReportsToggle public bool TransactionsToggle { - get { return this.doNotUseTransactionsToggle; } + get => this.doNotUseTransactionsToggle; set { this.doNotUseTransactionsToggle = value; @@ -123,7 +123,7 @@ private static bool CanExecuteDashboardCommand() private void AfterTabExecutedCommon() { - foreach (IShowableController controller in this.uiContext.ShowableControllers) + foreach (var controller in this.uiContext.ShowableControllers) { controller.Shown = false; } @@ -205,7 +205,11 @@ private void OnWidgetActivatedMessageReceived([NotNull] WidgetActivatedMessage m if (message.Widget is SaveWidget) { - if (PersistenceOperationCommands.SaveDatabaseCommand.CanExecute(null)) PersistenceOperationCommands.SaveDatabaseCommand.Execute(null); + if (PersistenceOperationCommands.SaveDatabaseCommand.CanExecute(null)) + { + PersistenceOperationCommands.SaveDatabaseCommand.Execute(null); + } + return; } @@ -235,8 +239,7 @@ private void OnWidgetActivatedMessageReceived([NotNull] WidgetActivatedMessage m private void ProcessCreateNewFileWidgetActivated(WidgetActivatedMessage message) { - var widget = message.Widget as NewFileWidget; - if (widget is null) + if (message.Widget is not NewFileWidget widget) { return; } @@ -248,8 +251,7 @@ private void ProcessCreateNewFileWidgetActivated(WidgetActivatedMessage message) private void ProcessCurrentFileWidgetActivated(WidgetActivatedMessage message) { - var widget = message.Widget as CurrentFileWidget; - if (widget is null) + if (message.Widget is not CurrentFileWidget widget) { return; } @@ -261,8 +263,7 @@ private void ProcessCurrentFileWidgetActivated(WidgetActivatedMessage message) private void ProcessLoadDemoWidgetActivated(WidgetActivatedMessage message) { - var widget = message.Widget as LoadDemoWidget; - if (widget is null) + if (message.Widget is not LoadDemoWidget widget) { return; } @@ -273,4 +274,4 @@ private void ProcessLoadDemoWidgetActivated(WidgetActivatedMessage message) PersistenceOperationCommands.LoadDemoDatabaseCommand.Execute(this); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/MainMenuUserControl.xaml.cs b/BudgetAnalyser/MainMenuUserControl.xaml.cs index 99c8420f..a9af33f2 100644 --- a/BudgetAnalyser/MainMenuUserControl.xaml.cs +++ b/BudgetAnalyser/MainMenuUserControl.xaml.cs @@ -12,4 +12,4 @@ public MainMenuUserControl() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/AppliedRulesController.cs b/BudgetAnalyser/Matching/AppliedRulesController.cs index 063b2f3f..1183027c 100644 --- a/BudgetAnalyser/Matching/AppliedRulesController.cs +++ b/BudgetAnalyser/Matching/AppliedRulesController.cs @@ -1,10 +1,10 @@ -using System.Windows.Input; +using System.Windows.Input; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Services; using BudgetAnalyser.Statement; using CommunityToolkit.Mvvm.Input; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Matching { @@ -99,4 +99,4 @@ private void OnShowRulesCommandExecute() RulesController.Shown = true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/DisusedRuleViewModel.cs b/BudgetAnalyser/Matching/DisusedRuleViewModel.cs index 2e44a2b2..043f88ee 100644 --- a/BudgetAnalyser/Matching/DisusedRuleViewModel.cs +++ b/BudgetAnalyser/Matching/DisusedRuleViewModel.cs @@ -9,4 +9,4 @@ public class DisusedRuleViewModel public ICommand RemoveCommand { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/DisusedRulesController.cs b/BudgetAnalyser/Matching/DisusedRulesController.cs index 4513a901..314bd6af 100644 --- a/BudgetAnalyser/Matching/DisusedRulesController.cs +++ b/BudgetAnalyser/Matching/DisusedRulesController.cs @@ -23,9 +23,20 @@ public DisusedRulesController([NotNull] IMessenger messenger, [NotNull] ITransac { this.ruleService = ruleService; this.dbService = dbService; - if (messenger is null) throw new ArgumentNullException(nameof(messenger)); - if (ruleService is null) throw new ArgumentNullException(nameof(ruleService)); - if (dbService is null) throw new ArgumentNullException(nameof(dbService)); + if (messenger is null) + { + throw new ArgumentNullException(nameof(messenger)); + } + + if (ruleService is null) + { + throw new ArgumentNullException(nameof(ruleService)); + } + + if (dbService is null) + { + throw new ArgumentNullException(nameof(dbService)); + } Messenger.Register(this, static (r, m) => r.OnShellDialogResponseReceived(m)); Messenger.Register(this, static (r, m) => r.OnWidgetActivatedMessageReceived(m)); @@ -33,13 +44,7 @@ public DisusedRulesController([NotNull] IMessenger messenger, [NotNull] ITransac public ObservableCollection DisusedRules { get; private set; } - public ICommand RemoveRuleCommand - { - get - { - return new RelayCommand(OnRemoveRuleExecuted, r => r is not null); - } - } + public ICommand RemoveRuleCommand => new RelayCommand(OnRemoveRuleExecuted, r => r is not null); private void OnRemoveRuleExecuted(DisusedRuleViewModel rule) { @@ -49,10 +54,14 @@ private void OnRemoveRuleExecuted(DisusedRuleViewModel rule) private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) { - if (!message.IsItForMe(this.dialogCorrelationId)) return; + if (!message.IsItForMe(this.dialogCorrelationId)) + { + return; + } + if (this.removedRules.Any()) { - foreach (MatchingRule rule in this.removedRules) + foreach (var rule in this.removedRules) { this.ruleService.RemoveRule(rule); } @@ -64,7 +73,10 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) private void OnWidgetActivatedMessageReceived(WidgetActivatedMessage message) { - if (message.Handled || !(message.Widget is DisusedMatchingRuleWidget)) return; + if (message.Handled || !(message.Widget is DisusedMatchingRuleWidget)) + { + return; + } var rules = DisusedMatchingRuleWidget.QueryRules(this.ruleService.MatchingRules); DisusedRules = new ObservableCollection(rules.Select(r => new DisusedRuleViewModel { MatchingRule = r, RemoveCommand = RemoveRuleCommand })); @@ -83,4 +95,4 @@ private void Reset() this.dialogCorrelationId = Guid.NewGuid(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/EditRulesUserControl.xaml.cs b/BudgetAnalyser/Matching/EditRulesUserControl.xaml.cs index e98b19ef..64444916 100644 --- a/BudgetAnalyser/Matching/EditRulesUserControl.xaml.cs +++ b/BudgetAnalyser/Matching/EditRulesUserControl.xaml.cs @@ -27,8 +27,7 @@ public EditRulesUserControl() private void OnCheckedAndSelectedRule(object sender, RoutedEventArgs e) { - var radioButton = sender as RadioButton; - if (radioButton is null) + if (sender is not RadioButton radioButton) { return; } @@ -62,8 +61,7 @@ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventA private void OnGroupListBoxLoaded(object sender, RoutedEventArgs e) { - var listBox = e.OriginalSource as ListBox; - if (listBox is null) + if (e.OriginalSource is not ListBox listBox) { return; } @@ -114,7 +112,7 @@ private void OnGroupListBoxRuleSelectionChanged(object sender, SelectionChangedE private void OnRuleAdded(object sender, MatchingRuleEventArgs e) { - MatchingRule rule = e.Rule; + var rule = e.Rule; var flatList = (ObservableCollection)this.FlatListBox.ItemsSource; if (flatList.All(r => r.RuleId != rule.RuleId)) { @@ -122,7 +120,7 @@ private void OnRuleAdded(object sender, MatchingRuleEventArgs e) } var groupedList = (ObservableCollection)this.GroupedByListBox.ItemsSource; - RulesGroupedByBucket group = groupedList.SingleOrDefault(g => g.Bucket == rule.Bucket); + var group = groupedList.SingleOrDefault(g => g.Bucket == rule.Bucket); if (group is null) { group = new RulesGroupedByBucket(rule.Bucket, new[] { rule }); @@ -142,11 +140,8 @@ private void OnRuleRemoved(object sender, EventArgs e) flatList.Remove(rule); var groupedList = (ObservableCollection)this.GroupedByListBox.ItemsSource; - RulesGroupedByBucket group = groupedList.FirstOrDefault(g => g.Bucket == rule.Bucket); - if (group is not null) - { - group.Rules.Remove(rule); - } + var group = groupedList.FirstOrDefault(g => g.Bucket == rule.Bucket); + group?.Rules.Remove(rule); } private void OnSortChanged(object sender, EventArgs e) @@ -159,14 +154,14 @@ private void OnSortChanged(object sender, EventArgs e) switch (this.currentSort) { case RulesController.DescriptionSortKey: - ICollectionView view1 = CollectionViewSource.GetDefaultView(this.FlatListBox.ItemsSource); + var view1 = CollectionViewSource.GetDefaultView(this.FlatListBox.ItemsSource); view1.SortDescriptions.Clear(); view1.SortDescriptions.Add(new SortDescription("Description", ListSortDirection.Ascending)); view1.Refresh(); break; case RulesController.MatchesSortKey: - ICollectionView view2 = CollectionViewSource.GetDefaultView(this.FlatListBox.ItemsSource); + var view2 = CollectionViewSource.GetDefaultView(this.FlatListBox.ItemsSource); view2.SortDescriptions.Clear(); view2.SortDescriptions.Add(new SortDescription("MatchCount", ListSortDirection.Descending)); view2.Refresh(); @@ -179,7 +174,7 @@ private void OnSortChanged(object sender, EventArgs e) if (Controller.GroupByListBoxVisibility) { - ICollectionView view = CollectionViewSource.GetDefaultView(this.GroupedByListBox.ItemsSource); + var view = CollectionViewSource.GetDefaultView(this.GroupedByListBox.ItemsSource); view.Refresh(); } } @@ -190,4 +185,4 @@ private void OnVisibilityChangedAndButton(object sender, DependencyPropertyChang OnCheckedAndSelectedRule(sender, new RoutedEventArgs()); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/MatchingRuleEventArgs.cs b/BudgetAnalyser/Matching/MatchingRuleEventArgs.cs index d78c6448..032f3e8a 100644 --- a/BudgetAnalyser/Matching/MatchingRuleEventArgs.cs +++ b/BudgetAnalyser/Matching/MatchingRuleEventArgs.cs @@ -7,4 +7,4 @@ public class MatchingRuleEventArgs : EventArgs { public MatchingRule Rule { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/NewRuleController.cs b/BudgetAnalyser/Matching/NewRuleController.cs index 363433a3..20f95981 100644 --- a/BudgetAnalyser/Matching/NewRuleController.cs +++ b/BudgetAnalyser/Matching/NewRuleController.cs @@ -1,4 +1,4 @@ -using System.ComponentModel; +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Windows.Data; using BudgetAnalyser.Engine; @@ -7,8 +7,8 @@ using BudgetAnalyser.Engine.Services; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Matching { @@ -56,7 +56,11 @@ public DecimalCriteria Amount get => this.doNotUseAmount; set { - if (Equals(value, this.doNotUseAmount)) return; + if (Equals(value, this.doNotUseAmount)) + { + return; + } + this.doNotUseAmount = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -69,7 +73,11 @@ public bool AndChecked get => this.doNotUseAndChecked; set { - if (value == this.doNotUseAndChecked) return; + if (value == this.doNotUseAndChecked) + { + return; + } + this.doNotUseAndChecked = value; OnPropertyChanged(); this.doNotUseOrChecked = !AndChecked; @@ -88,7 +96,11 @@ public StringCriteria Description get => this.doNotUseDescription; set { - if (Equals(value, this.doNotUseDescription)) return; + if (Equals(value, this.doNotUseDescription)) + { + return; + } + this.doNotUseDescription = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -104,7 +116,11 @@ public bool OrChecked [UsedImplicitly] set { - if (value == this.doNotUseOrChecked) return; + if (value == this.doNotUseOrChecked) + { + return; + } + this.doNotUseOrChecked = value; OnPropertyChanged(); this.doNotUseAndChecked = !OrChecked; @@ -117,7 +133,11 @@ public StringCriteria Reference1 get => this.doNotUseReference1; set { - if (Equals(value, this.doNotUseReference1)) return; + if (Equals(value, this.doNotUseReference1)) + { + return; + } + this.doNotUseReference1 = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -130,7 +150,11 @@ public StringCriteria Reference2 get => this.doNotUseReference2; set { - if (Equals(value, this.doNotUseReference2)) return; + if (Equals(value, this.doNotUseReference2)) + { + return; + } + this.doNotUseReference2 = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -143,7 +167,11 @@ public StringCriteria Reference3 get => this.doNotUseReference3; set { - if (Equals(value, this.doNotUseReference3)) return; + if (Equals(value, this.doNotUseReference3)) + { + return; + } + this.doNotUseReference3 = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -160,7 +188,11 @@ public StringCriteria TransactionType get => this.doNotUseTransactionType; set { - if (Equals(value, this.doNotUseTransactionType)) return; + if (Equals(value, this.doNotUseTransactionType)) + { + return; + } + this.doNotUseTransactionType = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanExecuteSaveButton)); @@ -267,7 +299,7 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) private void RefreshSimilarRules() { - ICollectionView view = CollectionViewSource.GetDefaultView(SimilarRules); + var view = CollectionViewSource.GetDefaultView(SimilarRules); view?.Refresh(); } @@ -280,7 +312,7 @@ private void UpdateSimilarRules() } this.logger.LogInfo(l => l.Format("UpdateSimilarRules1: Rules.Count() = {0}", SimilarRules.Count())); - ICollectionView view = CollectionViewSource.GetDefaultView(SimilarRules); + var view = CollectionViewSource.GetDefaultView(SimilarRules); view.Filter = item => this.rulesService.IsRuleSimilar((SimilarMatchedRule)item, Amount, Description, new[] { Reference1, Reference2, Reference3 }, TransactionType); view.SortDescriptions.Add(new SortDescription(nameof(SimilarMatchedRule.SortOrder), ListSortDirection.Descending)); @@ -290,4 +322,4 @@ private void UpdateSimilarRules() this.logger.LogInfo(l => l.Format("UpdateSimilarRules2: Rules.Count() = {0}", SimilarRules.Count())); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/NewRuleView.xaml.cs b/BudgetAnalyser/Matching/NewRuleView.xaml.cs index d81f0adf..a64793fa 100644 --- a/BudgetAnalyser/Matching/NewRuleView.xaml.cs +++ b/BudgetAnalyser/Matching/NewRuleView.xaml.cs @@ -12,4 +12,4 @@ public NewRuleView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Matching/RulesController.cs b/BudgetAnalyser/Matching/RulesController.cs index 1636114d..1a89f734 100644 --- a/BudgetAnalyser/Matching/RulesController.cs +++ b/BudgetAnalyser/Matching/RulesController.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Windows; using System.Windows.Input; using BudgetAnalyser.Engine; @@ -6,8 +6,8 @@ using BudgetAnalyser.Engine.Services; using BudgetAnalyser.Engine.Statement; using CommunityToolkit.Mvvm.Input; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Matching { @@ -137,7 +137,7 @@ public bool ShowReadOnlyRuleDetails { get { - bool result = SelectedRule is not null && !EditingRule; + var result = SelectedRule is not null && !EditingRule; return result; } } @@ -147,7 +147,7 @@ public string SortBy get => this.doNotUseSortBy; set { - string oldValue = this.doNotUseSortBy; + var oldValue = this.doNotUseSortBy; this.doNotUseSortBy = value; OnPropertyChanged(); GroupByListBoxVisibility = false; @@ -168,7 +168,7 @@ public string SortBy throw new ArgumentException(value + " is not a valid sort by argument."); } - EventHandler handler = SortChanged; + var handler = SortChanged; handler?.Invoke(this, EventArgs.Empty); } } @@ -220,7 +220,7 @@ private void AddToList(MatchingRule rule) { Rules.Add(rule); RulesGroupedByBucket.Single(g => g.Bucket == rule.Bucket).Rules.Add(rule); - EventHandler handler = RuleAdded; + var handler = RuleAdded; handler?.Invoke(this, new MatchingRuleEventArgs { Rule = rule }); } @@ -246,7 +246,7 @@ private void OnDeleteRuleCommandExecute() return; } - bool? certainty = this.questionBox.Show("Delete this rule?", "Are you sure?"); + var certainty = this.questionBox.Show("Delete this rule?", "Are you sure?"); if (certainty is not null && certainty.Value) { RemoveRule(); @@ -304,7 +304,7 @@ private void RemoveRule() EditingRule = false; } - MatchingRule selectedRule = SelectedRule; + var selectedRule = SelectedRule; if (!this.ruleService.RemoveRule(SelectedRule)) { return; @@ -312,10 +312,10 @@ private void RemoveRule() this.applicationDatabaseService.NotifyOfChange(ApplicationDataType.MatchingRules); - EventHandler handler = RuleRemoved; + var handler = RuleRemoved; handler?.Invoke(selectedRule, new MatchingRuleEventArgs { Rule = selectedRule }); SelectedRule = null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Mobile/UploadMobileDataController.cs b/BudgetAnalyser/Mobile/UploadMobileDataController.cs index 9fa260a5..a7a45d21 100644 --- a/BudgetAnalyser/Mobile/UploadMobileDataController.cs +++ b/BudgetAnalyser/Mobile/UploadMobileDataController.cs @@ -5,8 +5,8 @@ using BudgetAnalyser.Engine.Widgets; using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Mobile { @@ -46,7 +46,11 @@ public UploadMobileDataController( [NotNull] IApplicationDatabaseFacade appDbService) : base(uiContext.Messenger) { - if (uiContext is null) throw new ArgumentNullException(nameof(uiContext)); + if (uiContext is null) + { + throw new ArgumentNullException(nameof(uiContext)); + } + this.dataExporter = dataExporter ?? throw new ArgumentNullException(nameof(dataExporter)); this.uploader = uploader ?? throw new ArgumentNullException(nameof(uploader)); this.appDbService = appDbService ?? throw new ArgumentNullException(nameof(appDbService)); @@ -62,7 +66,11 @@ public string AccessKeyId get => this.doNotUseAccessKeyId; set { - if (value == this.doNotUseAccessKeyId) return; + if (value == this.doNotUseAccessKeyId) + { + return; + } + this.doNotUseAccessKeyId = value; OnPropertyChanged(); Messenger.Send(); @@ -74,7 +82,11 @@ public string AccessKeySecret get => this.doNotUseAccessKeySecret; set { - if (value == this.doNotUseAccessKeySecret) return; + if (value == this.doNotUseAccessKeySecret) + { + return; + } + this.doNotUseAccessKeySecret = value; OnPropertyChanged(); Messenger.Send(); @@ -86,7 +98,11 @@ public string AmazonRegion get => this.doNotUseAmazonRegion; set { - if (value == this.doNotUseAmazonRegion) return; + if (value == this.doNotUseAmazonRegion) + { + return; + } + this.doNotUseAmazonRegion = value; OnPropertyChanged(); } @@ -145,11 +161,18 @@ private async Task AttemptUploadAsync() private async void OnShellDialogMessageReceived(ShellDialogResponseMessage message) { - if (!message.IsItForMe(this.correlationId)) return; + if (!message.IsItForMe(this.correlationId)) + { + return; + } try { - if (message.Response == ShellDialogButton.Cancel) return; + if (message.Response == ShellDialogButton.Cancel) + { + return; + } + var changed = AccessKeyId != this.widget.LedgerBook.MobileSettings.AccessKeyId; changed |= AccessKeySecret != this.widget.LedgerBook.MobileSettings.AccessKeySecret; changed |= AmazonRegion != this.widget.LedgerBook.MobileSettings.AmazonS3Region; @@ -184,4 +207,4 @@ private void OnWidgetActivatedMessageReceived(WidgetActivatedMessage message) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/NewWindowContainer.xaml.cs b/BudgetAnalyser/NewWindowContainer.xaml.cs index 63162ade..67bf90cf 100644 --- a/BudgetAnalyser/NewWindowContainer.xaml.cs +++ b/BudgetAnalyser/NewWindowContainer.xaml.cs @@ -52,4 +52,4 @@ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventA this.showableController = e.NewValue as IShowableController; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/NewWindowViewLoader.cs b/BudgetAnalyser/NewWindowViewLoader.cs index 8b4feac2..de5ac71a 100644 --- a/BudgetAnalyser/NewWindowViewLoader.cs +++ b/BudgetAnalyser/NewWindowViewLoader.cs @@ -18,4 +18,4 @@ protected override void ConfigureWindow(object context) TargetWindow.MainContent.Content = context; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/PersistenceOperationCommands.cs b/BudgetAnalyser/PersistenceOperationCommands.cs index a244add6..b197b504 100644 --- a/BudgetAnalyser/PersistenceOperationCommands.cs +++ b/BudgetAnalyser/PersistenceOperationCommands.cs @@ -20,4 +20,4 @@ public static class PersistenceOperationCommands [UsedImplicitly] public static ICommand ValidateModelCommand { get; } = new RelayCommand(() => PersistenceOperations.OnValidateModelsCommandExecute()); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/PersistenceOperations.cs b/BudgetAnalyser/PersistenceOperations.cs index 415d4d8c..1caca088 100644 --- a/BudgetAnalyser/PersistenceOperations.cs +++ b/BudgetAnalyser/PersistenceOperations.cs @@ -16,7 +16,7 @@ public class PersistenceOperations private readonly DemoFileHelper demoFileHelper; private readonly IUiContext uiContext; private DateTime lastSave = DateTime.Now; - + public PersistenceOperations( [NotNull] IApplicationDatabaseFacade applicationDatabaseService, [NotNull] DemoFileHelper demoFileHelper, @@ -50,7 +50,7 @@ public async void OnCreateNewDatabaseCommandExecute() fileDialog.AddExtension = true; fileDialog.Filter = "Budget Analyser files (*.bax)|*.bax"; fileDialog.Title = "Select a folder and filename"; - bool? response = fileDialog.ShowDialog(); + var response = fileDialog.ShowDialog(); if (response is null || response == false || fileDialog.FileName.IsNothing()) { return; @@ -78,8 +78,16 @@ public async void OnSaveDatabaseCommandExecute() await OneSaveAtATime.WaitAsync(); try { - if (!this.applicationDatabaseService.HasUnsavedChanges) return; - if (DateTime.Now.Subtract(this.lastSave).TotalSeconds < 2) return; // No need to save repeatedly. + if (!this.applicationDatabaseService.HasUnsavedChanges) + { + return; + } + + if (DateTime.Now.Subtract(this.lastSave).TotalSeconds < 2) + { + return; // No need to save repeatedly. + } + await SaveDatabase(); this.lastSave = DateTime.Now; } @@ -156,7 +164,7 @@ private async Task PromptToSaveIfNecessary() if (this.applicationDatabaseService.HasUnsavedChanges) { const string messageBoxHeading = "Open Budget Analyser File"; - bool? response = this.uiContext.UserPrompts.YesNoBox.Show("Save changes before loading a different file?", messageBoxHeading); + var response = this.uiContext.UserPrompts.YesNoBox.Show("Save changes before loading a different file?", messageBoxHeading); if (response is not null && response.Value) { return await SaveDatabase(messageBoxHeading); @@ -177,13 +185,8 @@ private string PromptUserForFileName() openDialog.DefaultExt = "*.bax"; openDialog.Filter = "Budget Analyser files (*.bax)|*.bax|Xml files (*.xml, *.xaml)|*.xml;*.xaml"; openDialog.Title = "Select Budget Analyser file to open"; - bool? response = openDialog.ShowDialog(); - if (response is null || response.Value == false) - { - return null; - } - - return openDialog.FileName; + var response = openDialog.ShowDialog(); + return response is null || response.Value == false ? null : openDialog.FileName; } private async Task SaveDatabase(string title) @@ -209,4 +212,4 @@ private bool ValidateModel(string title) return false; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceController.cs b/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceController.cs index e05b84dc..88e6c1a8 100644 --- a/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceController.cs +++ b/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceController.cs @@ -32,7 +32,8 @@ public OverallPerformanceController([NotNull] IMessenger messenger, [NotNull] IO public bool ExpenseFilter { - [UsedImplicitly] get { return this.doNotUseExpenseFilter; } + [UsedImplicitly] + get => this.doNotUseExpenseFilter; set { @@ -44,7 +45,7 @@ public bool ExpenseFilter public bool IncomeFilter { - get { return this.doNotUseIncomeFilter; } + get => this.doNotUseIncomeFilter; set { @@ -68,11 +69,10 @@ public void Load(StatementModel statementModel, BudgetCollection budgets, Global IncomeFilter = false; OnPropertyChanged(nameof(Analysis)); - ICollectionView view = CollectionViewSource.GetDefaultView(Analysis.Analyses); + var view = CollectionViewSource.GetDefaultView(Analysis.Analyses); view.Filter = x => { - var bucketAnalysis = x as BucketPerformanceResult; - if (bucketAnalysis is null) + if (x is not BucketPerformanceResult bucketAnalysis) { return true; } @@ -82,7 +82,7 @@ public void Load(StatementModel statementModel, BudgetCollection budgets, Global return bucketAnalysis.Bucket is IncomeBudgetBucket; } - bool result = !(bucketAnalysis.Bucket is IncomeBudgetBucket); + var result = !(bucketAnalysis.Bucket is IncomeBudgetBucket); return result; }; } @@ -97,4 +97,4 @@ private void RefreshCollection() CollectionViewSource.GetDefaultView(Analysis.Analyses).Refresh(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceView.xaml.cs b/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceView.xaml.cs index a88f17cb..cd0e9b91 100644 --- a/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceView.xaml.cs +++ b/BudgetAnalyser/ReportsCatalog/OverallPerformance/OverallPerformanceView.xaml.cs @@ -12,4 +12,4 @@ public OverallPerformanceView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ReportsCatalog/ReportsCatalogController.cs b/BudgetAnalyser/ReportsCatalog/ReportsCatalogController.cs index f0e5f45b..5778e110 100644 --- a/BudgetAnalyser/ReportsCatalog/ReportsCatalogController.cs +++ b/BudgetAnalyser/ReportsCatalog/ReportsCatalogController.cs @@ -50,7 +50,11 @@ public bool Shown get => this.doNotUseShown; set { - if (value == this.doNotUseShown) return; + if (value == this.doNotUseShown) + { + return; + } + this.doNotUseShown = value; OnPropertyChanged(); } @@ -58,7 +62,11 @@ public bool Shown public void ShowOverallPerformanceReport() { - if (this.currentStatementModel is null) return; + if (this.currentStatementModel is null) + { + return; + } + OverallPerformanceController.Load(this.currentStatementModel, this.budgets, RequestCurrentFilter()); this.newWindowViewLoader.MinHeight = this.newWindowViewLoader.Height = 650; @@ -85,4 +93,4 @@ private GlobalFilterCriteria RequestCurrentFilter() Messenger.Send(currentFilterMessage); return currentFilterMessage.Criteria; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ReportsCatalog/ReportsCatalogUserControl.xaml.cs b/BudgetAnalyser/ReportsCatalog/ReportsCatalogUserControl.xaml.cs index d426efc6..424958ba 100644 --- a/BudgetAnalyser/ReportsCatalog/ReportsCatalogUserControl.xaml.cs +++ b/BudgetAnalyser/ReportsCatalog/ReportsCatalogUserControl.xaml.cs @@ -18,4 +18,4 @@ private void OverallPerformanceClicked(object sender, RoutedEventArgs e) ((ReportsCatalogController)DataContext).ShowOverallPerformanceReport(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ScratchPad.xaml.cs b/BudgetAnalyser/ScratchPad.xaml.cs index 1043d4fb..a9cc3a01 100644 --- a/BudgetAnalyser/ScratchPad.xaml.cs +++ b/BudgetAnalyser/ScratchPad.xaml.cs @@ -12,4 +12,4 @@ public Scratchpad() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Shell.xaml.cs b/BudgetAnalyser/Shell.xaml.cs index b248a586..fd2acc61 100644 --- a/BudgetAnalyser/Shell.xaml.cs +++ b/BudgetAnalyser/Shell.xaml.cs @@ -71,4 +71,4 @@ private async void ShellWindow_OnClosing(object sender, CancelEventArgs e) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellController.cs b/BudgetAnalyser/ShellController.cs index 5cecdd6f..79ddacd0 100644 --- a/BudgetAnalyser/ShellController.cs +++ b/BudgetAnalyser/ShellController.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Windows; using BudgetAnalyser.ApplicationState; using BudgetAnalyser.Budget; @@ -114,7 +114,7 @@ public void Initialize() } // Create a distinct list of sequences. - IEnumerable sequences = rehydratedModels.Select(persistentModel => persistentModel.LoadSequence).OrderBy(s => s).Distinct(); + var sequences = rehydratedModels.Select(persistentModel => persistentModel.LoadSequence).OrderBy(s => s).Distinct(); this.uiContext.Controllers.OfType().ToList().ForEach(i => i.Initialize()); @@ -122,7 +122,7 @@ public void Initialize() foreach (var sequence in sequences) { var sequenceCopy = sequence; - IEnumerable models = rehydratedModels.Where(persistentModel => persistentModel.LoadSequence == sequenceCopy); + var models = rehydratedModels.Where(persistentModel => persistentModel.LoadSequence == sequenceCopy); Messenger.Send(new ApplicationStateLoadedMessage(models)); } @@ -173,7 +173,7 @@ public async Task ShellClosing() { if (this.persistenceOperations.HasUnsavedChanges) { - bool? result = this.uiContext.UserPrompts.YesNoBox.Show("There are unsaved changes, save before exiting?", "Budget Analyser"); + var result = this.uiContext.UserPrompts.YesNoBox.Show("There are unsaved changes, save before exiting?", "Budget Analyser"); if (result is not null && result.Value) { // Save must be run carefully because the application is exiting. If run using the task factory with defaults the task will stall, as background tasks are waiting to be marshalled back to main context @@ -209,14 +209,7 @@ private async void OnApplicationStateLoaded([NotNull] ApplicationStateLoadedMess if (shellState is not null) { // Setting Window Size at this point has no effect, must happen after window is loaded. See OnViewReady() - if (shellState.Size.X > 0 || shellState.Size.Y > 0) - { - this.originalWindowSize = shellState.Size; - } - else - { - this.originalWindowSize = new Point(1250, 600); - } + this.originalWindowSize = shellState.Size.X > 0 || shellState.Size.Y > 0 ? shellState.Size : new Point(1250, 600); if (shellState.TopLeft.X > 0 || shellState.TopLeft.Y > 0) { @@ -275,4 +268,4 @@ private void OnDialogRequested(ShellDialogRequestMessage message) } } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/IShellDialogInteractivity.cs b/BudgetAnalyser/ShellDialog/IShellDialogInteractivity.cs index 9c94dcef..cb54e6de 100644 --- a/BudgetAnalyser/ShellDialog/IShellDialogInteractivity.cs +++ b/BudgetAnalyser/ShellDialog/IShellDialogInteractivity.cs @@ -22,4 +22,4 @@ public interface IShellDialogInteractivity /// bool CanExecuteSaveButton { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/IShellDialogToolTips.cs b/BudgetAnalyser/ShellDialog/IShellDialogToolTips.cs index ac7eb722..ba4421f4 100644 --- a/BudgetAnalyser/ShellDialog/IShellDialogToolTips.cs +++ b/BudgetAnalyser/ShellDialog/IShellDialogToolTips.cs @@ -5,4 +5,4 @@ public interface IShellDialogToolTips string ActionButtonToolTip { get; } string CloseButtonToolTip { get; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogButton.cs b/BudgetAnalyser/ShellDialog/ShellDialogButton.cs index 1dea07de..e0d7db18 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogButton.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogButton.cs @@ -7,4 +7,4 @@ public enum ShellDialogButton Save, Help } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogController.cs b/BudgetAnalyser/ShellDialog/ShellDialogController.cs index 687fa6b1..2cffc97c 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogController.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogController.cs @@ -16,7 +16,7 @@ public class ShellDialogController : ControllerBase private bool doNotUseOkButtonVisible; private bool doNotUseSaveButtonVisible; private string doNotUseTitle; - + public ShellDialogController([NotNull] IMessenger messenger) : base(messenger) { DialogType = ShellDialogType.OkCancel; @@ -25,19 +25,7 @@ public ShellDialogController([NotNull] IMessenger messenger) : base(messenger) messenger.Register(this, (l, m) => this.dialogRelayCommand.NotifyCanExecuteChanged()); } - public string ActionToolTip - { - get - { - var customTooltips = Content as IShellDialogToolTips; - if (customTooltips is null) - { - return DialogType == ShellDialogType.SaveCancel ? "Save" : "Ok"; - } - - return customTooltips.ActionButtonToolTip; - } - } + public string ActionToolTip => Content is not IShellDialogToolTips customTooltips ? DialogType == ShellDialogType.SaveCancel ? "Save" : "Ok" : customTooltips.ActionButtonToolTip; public bool CancelButtonVisible { @@ -49,26 +37,18 @@ public bool CancelButtonVisible } } - public string CloseToolTip - { - get - { - var customTooltips = Content as IShellDialogToolTips; - if (customTooltips is null) - { - return "Close"; - } - - return customTooltips.CloseButtonToolTip; - } - } + public string CloseToolTip => Content is not IShellDialogToolTips customTooltips ? "Close" : customTooltips.CloseButtonToolTip; public object? Content { get => this.doNotUseContent; set { - if (Equals(value, this.doNotUseContent)) return; + if (Equals(value, this.doNotUseContent)) + { + return; + } + this.doNotUseContent = value; OnPropertyChanged(); this.dialogRelayCommand.NotifyCanExecuteChanged(); @@ -84,7 +64,11 @@ public ShellDialogType DialogType get => this.doNotUseDialogType; set { - if (value == this.doNotUseDialogType) return; + if (value == this.doNotUseDialogType) + { + return; + } + this.doNotUseDialogType = value; OkButtonVisible = DialogType == ShellDialogType.Ok || DialogType == ShellDialogType.OkCancel; SaveButtonVisible = DialogType == ShellDialogType.SaveCancel; @@ -97,10 +81,15 @@ public ShellDialogType DialogType public bool HelpButtonVisible { - [UsedImplicitly] get => this.doNotUseHelpButtonVisible; + [UsedImplicitly] + get => this.doNotUseHelpButtonVisible; set { - if (value == this.doNotUseHelpButtonVisible) return; + if (value == this.doNotUseHelpButtonVisible) + { + return; + } + this.doNotUseHelpButtonVisible = value; OnPropertyChanged(); } @@ -111,7 +100,11 @@ public bool OkButtonVisible get => this.doNotUseOkButtonVisible; set { - if (value == this.doNotUseOkButtonVisible) return; + if (value == this.doNotUseOkButtonVisible) + { + return; + } + this.doNotUseOkButtonVisible = value; OnPropertyChanged(); OnPropertyChanged(nameof(OkIsCancel)); @@ -125,7 +118,11 @@ public bool SaveButtonVisible get => this.doNotUseSaveButtonVisible; set { - if (value == this.doNotUseSaveButtonVisible) return; + if (value == this.doNotUseSaveButtonVisible) + { + return; + } + this.doNotUseSaveButtonVisible = value; OnPropertyChanged(); } @@ -133,10 +130,15 @@ public bool SaveButtonVisible public string Title { - [UsedImplicitly] get => this.doNotUseTitle; + [UsedImplicitly] + get => this.doNotUseTitle; set { - if (value == this.doNotUseTitle) return; + if (value == this.doNotUseTitle) + { + return; + } + this.doNotUseTitle = value; OnPropertyChanged(); } @@ -155,7 +157,7 @@ public void ShowFromShell(ShellDialogRequestMessage message) CorrelationId = message.CorrelationId; HelpButtonVisible = message.HelpAvailable; } - + private bool CanExecuteDialogCommand(ShellDialogButton arg) { if (Content is null) @@ -188,7 +190,10 @@ private void OnDialogCommandExecute(ShellDialogButton commandType) DispatcherPriority.ApplicationIdle, () => { - if (Content is null) return; + if (Content is null) + { + return; + } // No correlation id given so no response is expected. if (CorrelationId != Guid.Empty) @@ -197,7 +202,10 @@ private void OnDialogCommandExecute(ShellDialogButton commandType) { case ShellDialogButton.Ok: case ShellDialogButton.Save: - if (!OkButtonVisible && commandType == ShellDialogButton.Ok) commandType = ShellDialogButton.Save; + if (!OkButtonVisible && commandType == ShellDialogButton.Ok) + { + commandType = ShellDialogButton.Save; + } // Ok will be the default response if Enter is pressed, even when the Ok button is invisible. Messenger.Send(new ShellDialogResponseMessage(Content, commandType) { CorrelationId = CorrelationId }); break; @@ -221,4 +229,4 @@ private void OnDialogCommandExecute(ShellDialogButton commandType) }); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogRequestMessage.cs b/BudgetAnalyser/ShellDialog/ShellDialogRequestMessage.cs index 2d88b9a7..422368e2 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogRequestMessage.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogRequestMessage.cs @@ -27,4 +27,4 @@ public ShellDialogRequestMessage(BudgetAnalyserFeature location, object content, public BudgetAnalyserFeature Location { get; private set; } public string Title { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogResponseMessage.cs b/BudgetAnalyser/ShellDialog/ShellDialogResponseMessage.cs index 9ad1382a..b1e19d5e 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogResponseMessage.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogResponseMessage.cs @@ -19,4 +19,4 @@ public bool IsItForMe(Guid correlationId) return correlationId != Guid.Empty && correlationId == CorrelationId; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogType.cs b/BudgetAnalyser/ShellDialog/ShellDialogType.cs index 352b37ec..2eaee3d1 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogType.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogType.cs @@ -6,4 +6,4 @@ public enum ShellDialogType OkCancel, SaveCancel } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellDialog/ShellDialogView.xaml.cs b/BudgetAnalyser/ShellDialog/ShellDialogView.xaml.cs index 6fc46910..a2a5384d 100644 --- a/BudgetAnalyser/ShellDialog/ShellDialogView.xaml.cs +++ b/BudgetAnalyser/ShellDialog/ShellDialogView.xaml.cs @@ -34,4 +34,4 @@ private void OnShellDialogKeyUp(object sender, KeyEventArgs e) e.Handled = true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/ShellPersistentState.cs b/BudgetAnalyser/ShellPersistentState.cs index 6a2f2453..5992e5d7 100644 --- a/BudgetAnalyser/ShellPersistentState.cs +++ b/BudgetAnalyser/ShellPersistentState.cs @@ -1,4 +1,4 @@ -using System.Windows; +using System.Windows; using BudgetAnalyser.Engine.Persistence; namespace BudgetAnalyser @@ -9,4 +9,4 @@ public class ShellPersistentState : IPersistentApplicationStateObject public Point Size { get; set; } public Point TopLeft { get; set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/AccountUserControl.xaml.cs b/BudgetAnalyser/Statement/AccountUserControl.xaml.cs index 4d0b8709..f79430b9 100644 --- a/BudgetAnalyser/Statement/AccountUserControl.xaml.cs +++ b/BudgetAnalyser/Statement/AccountUserControl.xaml.cs @@ -16,4 +16,4 @@ public AccountUserControl() public Account Account => (Account)DataContext; public string FriendlyAccountName => Account?.ToString(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/EditingTransactionController.cs b/BudgetAnalyser/Statement/EditingTransactionController.cs index 4f99bdf9..43e91839 100644 --- a/BudgetAnalyser/Statement/EditingTransactionController.cs +++ b/BudgetAnalyser/Statement/EditingTransactionController.cs @@ -32,7 +32,8 @@ public EditingTransactionController([NotNull] UiContext uiContext, [NotNull] IBu public IEnumerable Buckets { - [UsedImplicitly] get { return this.doNotUseBuckets; } + [UsedImplicitly] + get => this.doNotUseBuckets; private set { this.doNotUseBuckets = value; @@ -47,7 +48,7 @@ private set public Transaction Transaction { - get { return this.doNotUseTransaction; } + get => this.doNotUseTransaction; set { OriginalHash = value?.GetEqualityHashCode() ?? 0; @@ -73,4 +74,4 @@ public void ShowDialog(Transaction transaction, Guid correlationId) }); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/LoadFileController.cs b/BudgetAnalyser/Statement/LoadFileController.cs index 12944136..02774f44 100644 --- a/BudgetAnalyser/Statement/LoadFileController.cs +++ b/BudgetAnalyser/Statement/LoadFileController.cs @@ -7,8 +7,8 @@ using BudgetAnalyser.ShellDialog; using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; -using Rees.Wpf.Contracts; using Rees.Wpf; +using Rees.Wpf.Contracts; namespace BudgetAnalyser.Statement { @@ -58,7 +58,11 @@ public bool CanExecuteOkButton get => this.doNotUseCanExecuteOkButton; private set { - if (value == this.doNotUseCanExecuteOkButton) return; + if (value == this.doNotUseCanExecuteOkButton) + { + return; + } + this.doNotUseCanExecuteOkButton = value; OnPropertyChanged(); Messenger.Send(); @@ -75,7 +79,11 @@ public string FileName set { - if (value == this.doNotUseFileName) return; + if (value == this.doNotUseFileName) + { + return; + } + this.doNotUseFileName = value; OnPropertyChanged(); if (!string.IsNullOrWhiteSpace(FileName)) @@ -95,7 +103,11 @@ public bool FileTypeSelectionReady get => this.doNotUseFileTypeSelectionReady; private set { - if (value == this.doNotUseFileTypeSelectionReady) return; + if (value == this.doNotUseFileTypeSelectionReady) + { + return; + } + this.doNotUseFileTypeSelectionReady = value; OnPropertyChanged(); } @@ -109,7 +121,11 @@ public Account SelectedExistingAccountName set { - if (Equals(value, this.doNotUseSelectedExistingAccountName)) return; + if (Equals(value, this.doNotUseSelectedExistingAccountName)) + { + return; + } + this.doNotUseSelectedExistingAccountName = value; OnPropertyChanged(); CheckAccountName(); @@ -124,7 +140,11 @@ public string Title get => this.doNotUseTitle; private set { - if (value == this.doNotUseTitle) return; + if (value == this.doNotUseTitle) + { + return; + } + this.doNotUseTitle = value; OnPropertyChanged(); } @@ -291,7 +311,7 @@ private void OnBrowseForFileCommandExecute() dialog.DefaultExt = "*.CSV"; dialog.Title = "Select a CSV file of transactions to load."; dialog.Filter = "Comma Separated Values (*.CSV)|*.CSV"; - bool? result = dialog.ShowDialog(); + var result = dialog.ShowDialog(); if (result is null || result == false) { FileName = null; @@ -369,4 +389,4 @@ private Task RequestUserInputCommomPreparation() Dispose(false); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/LoadFileView.xaml.cs b/BudgetAnalyser/Statement/LoadFileView.xaml.cs index a0726ab8..893120af 100644 --- a/BudgetAnalyser/Statement/LoadFileView.xaml.cs +++ b/BudgetAnalyser/Statement/LoadFileView.xaml.cs @@ -20,4 +20,4 @@ private void OnFileNameMouseUp(object sender, MouseEventArgs e) Controller.BrowseForFileCommand.Execute(null); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/NavigateToTransactionMessage.cs b/BudgetAnalyser/Statement/NavigateToTransactionMessage.cs index 9c19555d..d2ede07a 100644 --- a/BudgetAnalyser/Statement/NavigateToTransactionMessage.cs +++ b/BudgetAnalyser/Statement/NavigateToTransactionMessage.cs @@ -11,7 +11,7 @@ public NavigateToTransactionMessage(Guid transactionId) { TransactionId = transactionId; this.cancellationSource = new CancellationTokenSource(); - CancellationToken cancellationToken = this.cancellationSource.Token; + var cancellationToken = this.cancellationSource.Token; WhenReadyToNavigate = new Task(() => { }, cancellationToken); } @@ -104,4 +104,4 @@ private void Dispose(bool disposing) this.disposed = true; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/SplitTransactionController.cs b/BudgetAnalyser/Statement/SplitTransactionController.cs index ee0ed9f0..16366a22 100644 --- a/BudgetAnalyser/Statement/SplitTransactionController.cs +++ b/BudgetAnalyser/Statement/SplitTransactionController.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using BudgetAnalyser.Engine; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Statement; @@ -38,10 +38,15 @@ public SplitTransactionController([NotNull] UiContext uiContext, [NotNull] IBudg public string InvalidMessage { - [UsedImplicitly] get => this.doNotUseInvalidMessage; + [UsedImplicitly] + get => this.doNotUseInvalidMessage; private set { - if (value == this.doNotUseInvalidMessage) return; + if (value == this.doNotUseInvalidMessage) + { + return; + } + this.doNotUseInvalidMessage = value; OnPropertyChanged(); } @@ -52,7 +57,11 @@ public Transaction? OriginalTransaction get => this.doNotUseOriginalTransaction; private set { - if (Equals(value, this.doNotUseOriginalTransaction)) return; + if (Equals(value, this.doNotUseOriginalTransaction)) + { + return; + } + this.doNotUseOriginalTransaction = value; OnPropertyChanged(); OnPropertyChanged(nameof(Valid)); @@ -65,7 +74,11 @@ public decimal SplinterAmount1 get => this.doNotUseSplinterAmount1; set { - if (value == this.doNotUseSplinterAmount1) return; + if (value == this.doNotUseSplinterAmount1) + { + return; + } + this.doNotUseSplinterAmount1 = value; this.doNotUseSplinterAmount2 = OriginalTransaction.Amount - value; OnPropertyChanged(); @@ -81,7 +94,11 @@ public decimal SplinterAmount2 get => this.doNotUseSplinterAmount2; set { - if (value == this.doNotUseSplinterAmount2) return; + if (value == this.doNotUseSplinterAmount2) + { + return; + } + this.doNotUseSplinterAmount2 = value; this.doNotUseSplinterAmount1 = OriginalTransaction.Amount - value; OnPropertyChanged(nameof(SplinterAmount1)); @@ -100,7 +117,10 @@ public bool Valid { get { - if (OriginalTransaction is null) return false; + if (OriginalTransaction is null) + { + return false; + } if (SplinterAmount1 == 0) { @@ -153,4 +173,4 @@ private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) OriginalTransaction = null; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/SplitTransactionView.xaml.cs b/BudgetAnalyser/Statement/SplitTransactionView.xaml.cs index 9af98a01..b26f7c90 100644 --- a/BudgetAnalyser/Statement/SplitTransactionView.xaml.cs +++ b/BudgetAnalyser/Statement/SplitTransactionView.xaml.cs @@ -12,4 +12,4 @@ public SplitTransactionView() InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementController.cs b/BudgetAnalyser/Statement/StatementController.cs index 794085ab..ab9eb7c7 100644 --- a/BudgetAnalyser/Statement/StatementController.cs +++ b/BudgetAnalyser/Statement/StatementController.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Windows.Input; using BudgetAnalyser.Budget; using BudgetAnalyser.Engine; @@ -63,7 +63,11 @@ public string BucketFilter set { - if (Equals(value, this.doNotUseBucketFilter)) return; + if (Equals(value, this.doNotUseBucketFilter)) + { + return; + } + this.doNotUseBucketFilter = value; OnPropertyChanged(); ViewModel.Transactions = this.transactionService.FilterByBucket(BucketFilter); @@ -84,7 +88,11 @@ public string? TextFilter get => this.doNotUseTextFilter; set { - if (Equals(value, this.doNotUseTextFilter)) return; + if (Equals(value, this.doNotUseTextFilter)) + { + return; + } + this.doNotUseTextFilter = string.IsNullOrEmpty(value) ? null : value; OnPropertyChanged(); ViewModel.Transactions = this.transactionService.FilterBySearchText(TextFilter); @@ -208,7 +216,10 @@ private void OnClosedNotificationReceived(object sender, EventArgs e) private async void OnDeleteTransactionCommandExecute() { - if (ViewModel.SelectedRow is null) return; + if (ViewModel.SelectedRow is null) + { + return; + } var confirm = this.uiContext.UserPrompts.YesNoBox.Show( "Are you sure you want to delete this transaction?", @@ -292,4 +303,4 @@ private void OnSplitTransactionCommandExecute() this.shellDialogCorrelationId = Guid.NewGuid(); SplitTransactionController.ShowDialog(ViewModel.SelectedRow, this.shellDialogCorrelationId); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementControllerFileOperations.cs b/BudgetAnalyser/Statement/StatementControllerFileOperations.cs index b77f84e6..3f9dd531 100644 --- a/BudgetAnalyser/Statement/StatementControllerFileOperations.cs +++ b/BudgetAnalyser/Statement/StatementControllerFileOperations.cs @@ -38,7 +38,8 @@ public StatementControllerFileOperations( public bool LoadingData { - [UsedImplicitly] get => this.doNotUseLoadingData; + [UsedImplicitly] + get => this.doNotUseLoadingData; private set { this.doNotUseLoadingData = value; @@ -161,4 +162,4 @@ private void NotifyOfReset() Messenger.Send(new StatementHasBeenModifiedMessage(false, ViewModel.Statement)); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementControllerNavigation.cs b/BudgetAnalyser/Statement/StatementControllerNavigation.cs index f2e8c904..94acd87f 100644 --- a/BudgetAnalyser/Statement/StatementControllerNavigation.cs +++ b/BudgetAnalyser/Statement/StatementControllerNavigation.cs @@ -44,10 +44,10 @@ public StatementControllerNavigation( private bool NavigateToTransactionOutsideOfFilter(Guid transactionId) { - Transaction foundTransaction = ViewModel.Statement.AllTransactions.FirstOrDefault(t => t.Id == transactionId); + var foundTransaction = ViewModel.Statement.AllTransactions.FirstOrDefault(t => t.Id == transactionId); if (foundTransaction is not null) { - bool? result = this.questionBox.Show("The transaction falls outside the current filter. Do you wish to adjust the filter to show the transaction?", "Navigate to Transaction"); + var result = this.questionBox.Show("The transaction falls outside the current filter. Do you wish to adjust the filter to show the transaction?", "Navigate to Transaction"); if (result is null || !result.Value) { return false; @@ -57,14 +57,9 @@ private bool NavigateToTransactionOutsideOfFilter(Guid transactionId) var requestCurrentFilter = new RequestFilterMessage(this); MessengerInstance.Send(requestCurrentFilter); - if (foundTransaction.Date < requestCurrentFilter.Criteria.BeginDate) - { - newCriteria = new GlobalFilterCriteria { BeginDate = foundTransaction.Date, EndDate = requestCurrentFilter.Criteria.EndDate }; - } - else - { - newCriteria = new GlobalFilterCriteria { BeginDate = requestCurrentFilter.Criteria.BeginDate, EndDate = foundTransaction.Date }; - } + newCriteria = foundTransaction.Date < requestCurrentFilter.Criteria.BeginDate + ? new GlobalFilterCriteria { BeginDate = foundTransaction.Date, EndDate = requestCurrentFilter.Criteria.EndDate } + : new GlobalFilterCriteria { BeginDate = requestCurrentFilter.Criteria.BeginDate, EndDate = foundTransaction.Date }; MessengerInstance.Send(new RequestFilterChangeMessage(this) { Criteria = newCriteria }); @@ -76,7 +71,7 @@ private bool NavigateToTransactionOutsideOfFilter(Guid transactionId) private bool NavigateToVisibleTransaction(Guid transactionId) { - Transaction foundTransaction = ViewModel.Statement.Transactions.FirstOrDefault(t => t.Id == transactionId); + var foundTransaction = ViewModel.Statement.Transactions.FirstOrDefault(t => t.Id == transactionId); if (foundTransaction is not null) { ViewModel.SelectedRow = foundTransaction; @@ -104,4 +99,4 @@ private void OnNavigateToTransactionRequestReceived(NavigateToTransactionMessage // No such transaction id found. } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementHasBeenModifiedMessage.cs b/BudgetAnalyser/Statement/StatementHasBeenModifiedMessage.cs index 6cd879bc..05480df8 100644 --- a/BudgetAnalyser/Statement/StatementHasBeenModifiedMessage.cs +++ b/BudgetAnalyser/Statement/StatementHasBeenModifiedMessage.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine.Statement; +using BudgetAnalyser.Engine.Statement; using Rees.Wpf; namespace BudgetAnalyser.Statement @@ -22,4 +22,4 @@ public StatementHasBeenModifiedMessage(bool dirty, StatementModel statementModel public bool Dirty { get; private set; } public StatementModel StatementModel { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementReadyMessage.cs b/BudgetAnalyser/Statement/StatementReadyMessage.cs index 39225563..860ba420 100644 --- a/BudgetAnalyser/Statement/StatementReadyMessage.cs +++ b/BudgetAnalyser/Statement/StatementReadyMessage.cs @@ -16,4 +16,4 @@ public StatementReadyMessage(StatementModel statement) public StatementModel StatementModel { get; private set; } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementUserControl.xaml.cs b/BudgetAnalyser/Statement/StatementUserControl.xaml.cs index f24532e8..8faf9971 100644 --- a/BudgetAnalyser/Statement/StatementUserControl.xaml.cs +++ b/BudgetAnalyser/Statement/StatementUserControl.xaml.cs @@ -52,17 +52,15 @@ private void ApplyBucketFilter() { defaultView.Filter = null; } - else if (Controller.BucketFilter == TransactionConstants.UncategorisedFilter) - { - defaultView.Filter = t => - { - var txn = (Transaction)t; - return txn.BudgetBucket is null || string.IsNullOrWhiteSpace(txn.BudgetBucket.Code); - }; - } else { - defaultView.Filter = t => + defaultView.Filter = Controller.BucketFilter == TransactionConstants.UncategorisedFilter + ? t => + { + var txn = (Transaction)t; + return txn.BudgetBucket is null || string.IsNullOrWhiteSpace(txn.BudgetBucket.Code); + } + : t => { var txn = (Transaction)t; return txn.BudgetBucket is not null && txn.BudgetBucket.Code == Controller.BucketFilter; @@ -155,10 +153,7 @@ private void OnShellDialogResponseMessageReceived(ShellDialogResponseMessage mes if (message.Content is EditingTransactionController) { var listBoxItem = GetSelectedListBoxItem(); - if (listBoxItem is not null) - { - listBoxItem.Focus(); - } + listBoxItem?.Focus(); } } @@ -217,4 +212,4 @@ private void SearchTextBox_OnKeyUp(object sender, KeyEventArgs e) { this.ClearSearchButton.IsEnabled = this.SearchTextBox.Text.Length > 0; } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/StatementViewModel.cs b/BudgetAnalyser/Statement/StatementViewModel.cs index 67bfb5ba..c2081e68 100644 --- a/BudgetAnalyser/Statement/StatementViewModel.cs +++ b/BudgetAnalyser/Statement/StatementViewModel.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using BudgetAnalyser.Engine; @@ -15,7 +15,7 @@ public class StatementViewModel : ObservableRecipient private bool doNotUseDirty; private string doNotUseDuplicateSummary; private Transaction doNotUseSelectedRow; - private bool doNotUseSortByDate; + private readonly bool doNotUseSortByDate; private StatementModel doNotUseStatement; private ObservableCollection doNotUseTransactions; private ITransactionManagerService transactionService; @@ -46,7 +46,8 @@ public bool Dirty public string DuplicateSummary { - [UsedImplicitly] get => this.doNotUseDuplicateSummary; + [UsedImplicitly] + get => this.doNotUseDuplicateSummary; private set { @@ -87,18 +88,7 @@ public StatementModel Statement } } - public string StatementName - { - get - { - if (Statement is not null) - { - return Path.GetFileNameWithoutExtension(Statement.StorageKey); - } - - return "[No Transactions Loaded]"; - } - } + public string StatementName => Statement is not null ? Path.GetFileNameWithoutExtension(Statement.StorageKey) : "[No Transactions Loaded]"; public decimal TotalCount => this.transactionService.TotalCount; public decimal TotalCredits => this.transactionService.TotalCredits; @@ -143,4 +133,4 @@ public void TriggerRefreshTotalsRow() DuplicateSummary = Statement is null ? null : this.transactionService.DetectDuplicateTransactions(); } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/Statement/TransactionsChangedMessage.cs b/BudgetAnalyser/Statement/TransactionsChangedMessage.cs index b61069d1..bb4d8faf 100644 --- a/BudgetAnalyser/Statement/TransactionsChangedMessage.cs +++ b/BudgetAnalyser/Statement/TransactionsChangedMessage.cs @@ -1,4 +1,4 @@ -using Rees.Wpf; +using Rees.Wpf; namespace BudgetAnalyser.Statement { @@ -9,4 +9,4 @@ namespace BudgetAnalyser.Statement public class TransactionsChangedMessage : MessageBase { } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/UiContext.cs b/BudgetAnalyser/UiContext.cs index 1a4d1d6c..814a6789 100644 --- a/BudgetAnalyser/UiContext.cs +++ b/BudgetAnalyser/UiContext.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using BudgetAnalyser.Budget; using BudgetAnalyser.Dashboard; using BudgetAnalyser.Engine; @@ -87,4 +87,4 @@ private List DiscoverAllControllers() .ToList(); } } -} \ No newline at end of file +} diff --git a/BudgetAnalyser/UserPrompts.cs b/BudgetAnalyser/UserPrompts.cs index aa3909ee..b82ee825 100644 --- a/BudgetAnalyser/UserPrompts.cs +++ b/BudgetAnalyser/UserPrompts.cs @@ -1,4 +1,4 @@ -using BudgetAnalyser.Engine; +using BudgetAnalyser.Engine; using Rees.Wpf.Contracts; namespace BudgetAnalyser @@ -51,4 +51,4 @@ public UserPrompts( public Func SaveFileFactory { get; private set; } public IUserQuestionBoxYesNo YesNoBox { get; private set; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ApplicationState/ApplicationStateLoadFinishedMessage.cs b/Rees.Wpf/ApplicationState/ApplicationStateLoadFinishedMessage.cs index 3dad0ba5..49024290 100644 --- a/Rees.Wpf/ApplicationState/ApplicationStateLoadFinishedMessage.cs +++ b/Rees.Wpf/ApplicationState/ApplicationStateLoadFinishedMessage.cs @@ -8,4 +8,4 @@ public class ApplicationStateLoadFinishedMessage : MessageBase { } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ApplicationState/ApplicationStateLoadedMessage.cs b/Rees.Wpf/ApplicationState/ApplicationStateLoadedMessage.cs index a75e0592..12167c9a 100644 --- a/Rees.Wpf/ApplicationState/ApplicationStateLoadedMessage.cs +++ b/Rees.Wpf/ApplicationState/ApplicationStateLoadedMessage.cs @@ -20,7 +20,7 @@ public class ApplicationStateLoadedMessage : MessageBase /// public ApplicationStateLoadedMessage(IEnumerable rehydratedModels) { - IEnumerable removeDuplicates = rehydratedModels + var removeDuplicates = rehydratedModels .GroupBy(model => model.GetType(), model => model) .Where(group => group.Key is not null) .Select(group => group.First()); @@ -42,12 +42,7 @@ public ApplicationStateLoadedMessage(IEnumerable rehydratedModels) public T ElementOfType() where T : class, IPersistent { var type = typeof(T); - if (RehydratedModels.ContainsKey(type)) - { - return RehydratedModels[type] as T; - } - - return null; + return RehydratedModels.ContainsKey(type) ? RehydratedModels[type] as T : null; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ApplicationState/ApplicationStateRequestedMessage.cs b/Rees.Wpf/ApplicationState/ApplicationStateRequestedMessage.cs index 53b88bd8..8b7263f4 100644 --- a/Rees.Wpf/ApplicationState/ApplicationStateRequestedMessage.cs +++ b/Rees.Wpf/ApplicationState/ApplicationStateRequestedMessage.cs @@ -43,4 +43,4 @@ public void PersistThisModel(IPersistent model) this.modelsToPersist.Add(model); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ApplicationState/BadApplicationStateFileFormatException.cs b/Rees.Wpf/ApplicationState/BadApplicationStateFileFormatException.cs index 3810bd0b..741e361c 100644 --- a/Rees.Wpf/ApplicationState/BadApplicationStateFileFormatException.cs +++ b/Rees.Wpf/ApplicationState/BadApplicationStateFileFormatException.cs @@ -58,4 +58,4 @@ protected BadApplicationStateFileFormatException(SerializationInfo info, Streami { } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ApplicationState/PersistApplicationStateAsXaml.cs b/Rees.Wpf/ApplicationState/PersistApplicationStateAsXaml.cs index 8b9cf336..02e6a4a7 100644 --- a/Rees.Wpf/ApplicationState/PersistApplicationStateAsXaml.cs +++ b/Rees.Wpf/ApplicationState/PersistApplicationStateAsXaml.cs @@ -73,16 +73,12 @@ public IEnumerable Load() { var serialised = XamlServices.Load(FullFileName); // Will always succeed without exceptions even if bad file format, but will return null. - var correctFormat = serialised as List; - if (correctFormat is null) - { - throw new BadApplicationStateFileFormatException( + return serialised is not List correctFormat + ? throw new BadApplicationStateFileFormatException( string.Format(CultureInfo.InvariantCulture, "The file used to store application state ({0}) is not in the correct format. It may have been tampered with.", - FullFileName)); - } - - return correctFormat; + FullFileName)) + : (IEnumerable)correctFormat; } catch (IOException ex) { @@ -112,4 +108,4 @@ public void Persist(IEnumerable modelsToPersist) } } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/BubbleScrollEventBehaviour.cs b/Rees.Wpf/BubbleScrollEventBehaviour.cs index c98b6363..4b86a5b8 100644 --- a/Rees.Wpf/BubbleScrollEventBehaviour.cs +++ b/Rees.Wpf/BubbleScrollEventBehaviour.cs @@ -22,9 +22,11 @@ protected override void OnDetaching() private void AssociatedObject_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { e.Handled = true; - var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta); - e2.RoutedEvent = UIElement.MouseWheelEvent; + var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) + { + RoutedEvent = UIElement.MouseWheelEvent + }; AssociatedObject.RaiseEvent(e2); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IPersistApplicationState.cs b/Rees.Wpf/Contracts/IPersistApplicationState.cs index bee2813c..9ff1305c 100644 --- a/Rees.Wpf/Contracts/IPersistApplicationState.cs +++ b/Rees.Wpf/Contracts/IPersistApplicationState.cs @@ -26,4 +26,4 @@ public interface IPersistApplicationState /// void Persist(IEnumerable modelsToPersist); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IPersistent.cs b/Rees.Wpf/Contracts/IPersistent.cs index c1337690..6d3832de 100644 --- a/Rees.Wpf/Contracts/IPersistent.cs +++ b/Rees.Wpf/Contracts/IPersistent.cs @@ -12,4 +12,4 @@ public interface IPersistent /// int LoadSequence { get; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IUserInputBox.cs b/Rees.Wpf/Contracts/IUserInputBox.cs index 9b1c2487..e2b1c60d 100644 --- a/Rees.Wpf/Contracts/IUserInputBox.cs +++ b/Rees.Wpf/Contracts/IUserInputBox.cs @@ -14,4 +14,4 @@ public interface IUserInputBox /// User response to the question, or null if the user cancelled. The user cannot return null if 'Ok' is clicked. string Show(string heading, string question, string defaultInput = ""); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IUserMessageBox.cs b/Rees.Wpf/Contracts/IUserMessageBox.cs index a6b8e70b..ede4773b 100644 --- a/Rees.Wpf/Contracts/IUserMessageBox.cs +++ b/Rees.Wpf/Contracts/IUserMessageBox.cs @@ -50,4 +50,4 @@ public interface IUserMessageBox /// Other arguments. void Show(Exception ex, string format, object argument1, params object[] args); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IUserPromptOpenFile.cs b/Rees.Wpf/Contracts/IUserPromptOpenFile.cs index e1264e18..420d5ed2 100644 --- a/Rees.Wpf/Contracts/IUserPromptOpenFile.cs +++ b/Rees.Wpf/Contracts/IUserPromptOpenFile.cs @@ -54,4 +54,4 @@ public interface IUserPromptOpenFile /// bool? ShowDialog(); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IUserPromptSaveFile.cs b/Rees.Wpf/Contracts/IUserPromptSaveFile.cs index a614bcf2..053d5642 100644 --- a/Rees.Wpf/Contracts/IUserPromptSaveFile.cs +++ b/Rees.Wpf/Contracts/IUserPromptSaveFile.cs @@ -49,4 +49,4 @@ public interface IUserPromptSaveFile /// bool? ShowDialog(); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IUserQuestionBoxYesNo.cs b/Rees.Wpf/Contracts/IUserQuestionBoxYesNo.cs index 0006fbc4..017bcc1d 100644 --- a/Rees.Wpf/Contracts/IUserQuestionBoxYesNo.cs +++ b/Rees.Wpf/Contracts/IUserQuestionBoxYesNo.cs @@ -23,4 +23,4 @@ public interface IUserQuestionBoxYesNo /// true for yes, false for no, and null for cancellation. bool? Show(string heading, string questionFormat, object argument1, params object[] args); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IViewLoader.cs b/Rees.Wpf/Contracts/IViewLoader.cs index b55c1839..28b2d26d 100644 --- a/Rees.Wpf/Contracts/IViewLoader.cs +++ b/Rees.Wpf/Contracts/IViewLoader.cs @@ -26,4 +26,4 @@ public interface IViewLoader /// bool? ShowDialog(object context); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Contracts/IWaitCursor.cs b/Rees.Wpf/Contracts/IWaitCursor.cs index 43b0c990..7739e81b 100644 --- a/Rees.Wpf/Contracts/IWaitCursor.cs +++ b/Rees.Wpf/Contracts/IWaitCursor.cs @@ -8,4 +8,4 @@ namespace Rees.Wpf.Contracts public interface IWaitCursor : IDisposable { } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ControllerBase.cs b/Rees.Wpf/ControllerBase.cs index 9b42a913..6523745e 100644 --- a/Rees.Wpf/ControllerBase.cs +++ b/Rees.Wpf/ControllerBase.cs @@ -26,4 +26,4 @@ public ControllerBase(IMessenger messenger) : base(messenger) /// protected Dispatcher Dispatcher { get; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/BoolToVisibility2Converter.cs b/Rees.Wpf/Converters/BoolToVisibility2Converter.cs index f551920a..b7b448c2 100644 --- a/Rees.Wpf/Converters/BoolToVisibility2Converter.cs +++ b/Rees.Wpf/Converters/BoolToVisibility2Converter.cs @@ -43,4 +43,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/ConvertToStringConverter.cs b/Rees.Wpf/Converters/ConvertToStringConverter.cs index e69a85eb..987319ee 100644 --- a/Rees.Wpf/Converters/ConvertToStringConverter.cs +++ b/Rees.Wpf/Converters/ConvertToStringConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows.Data; namespace Rees.Wpf.Converters @@ -23,7 +22,7 @@ public class ConvertToStringConverter : IValueConverter /// The type of the binding target property. /// The converter parameter to use. /// The culture to use in the converter. - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is null) { @@ -35,31 +34,28 @@ public object Convert(object value, Type targetType, object parameter, CultureIn return value.ToString(); } - if (value is DateTime) + if (value is DateTime dateTimeValue) { - return ((DateTime)value).ToString(parameter.ToString()); + return dateTimeValue.ToString(parameter.ToString()); } - if (value is int || value is long || value is ushort || value is uint || value is ulong) + if (value is int or long or ushort or uint or ulong) { return System.Convert.ToInt64(value).ToString(parameter.ToString()); } - if (value is decimal || value is double || value is float) - { - return System.Convert.ToDouble(value).ToString(parameter.ToString()); - } - - return value.ToString(); + return value is decimal or double or float + ? System.Convert.ToDouble(value).ToString(parameter.ToString()) + : (object?)value.ToString(); } /// /// Not Supported in this implementation. /// /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/DebuggerConverter.cs b/Rees.Wpf/Converters/DebuggerConverter.cs index 6825b634..3d86af4c 100644 --- a/Rees.Wpf/Converters/DebuggerConverter.cs +++ b/Rees.Wpf/Converters/DebuggerConverter.cs @@ -41,4 +41,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu return value; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/MultiBoolAndBoolConverter.cs b/Rees.Wpf/Converters/MultiBoolAndBoolConverter.cs index 39b18cc0..7dcfbe43 100644 --- a/Rees.Wpf/Converters/MultiBoolAndBoolConverter.cs +++ b/Rees.Wpf/Converters/MultiBoolAndBoolConverter.cs @@ -58,4 +58,4 @@ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, { throw new NotSupportedException(); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/MultiBoolToVisibilityConverter.cs b/Rees.Wpf/Converters/MultiBoolToVisibilityConverter.cs index 2845fc50..0925ea46 100644 --- a/Rees.Wpf/Converters/MultiBoolToVisibilityConverter.cs +++ b/Rees.Wpf/Converters/MultiBoolToVisibilityConverter.cs @@ -70,4 +70,4 @@ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/NotBoolToVisibilityConverter.cs b/Rees.Wpf/Converters/NotBoolToVisibilityConverter.cs index 9b483680..470fa956 100644 --- a/Rees.Wpf/Converters/NotBoolToVisibilityConverter.cs +++ b/Rees.Wpf/Converters/NotBoolToVisibilityConverter.cs @@ -43,4 +43,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/NotNullToBoolConverter.cs b/Rees.Wpf/Converters/NotNullToBoolConverter.cs index 068b1638..c7a58747 100644 --- a/Rees.Wpf/Converters/NotNullToBoolConverter.cs +++ b/Rees.Wpf/Converters/NotNullToBoolConverter.cs @@ -10,7 +10,7 @@ namespace Rees.Wpf.Converters public class NotNullToBoolConverter : IValueConverter { /// - /// Converts a value. + /// Converts a value. /// /// The value produced by the binding source. /// Not Used. @@ -40,4 +40,4 @@ public object ConvertBack(object? value, Type targetType, object? parameter, Cul throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/NotNullToVisibilityConverter.cs b/Rees.Wpf/Converters/NotNullToVisibilityConverter.cs index 57422091..2637ef27 100644 --- a/Rees.Wpf/Converters/NotNullToVisibilityConverter.cs +++ b/Rees.Wpf/Converters/NotNullToVisibilityConverter.cs @@ -22,11 +22,11 @@ public class NotNullToVisibilityConverter : IValueConverter /// /// A converted value. If the method returns null, the valid null value is used. /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { var stringParameter = parameter as string; var hiddenValue = Visibility.Hidden; - Func test = () => value is null; + var test = () => value is null; if (stringParameter is not null) { @@ -60,4 +60,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/NullToBoolConverter.cs b/Rees.Wpf/Converters/NullToBoolConverter.cs index 999c73a1..2adb2b31 100644 --- a/Rees.Wpf/Converters/NullToBoolConverter.cs +++ b/Rees.Wpf/Converters/NullToBoolConverter.cs @@ -10,7 +10,7 @@ namespace Rees.Wpf.Converters public class NullToBoolConverter : IValueConverter { /// - /// Converts a value. + /// Converts a value. /// /// The value produced by the binding source. /// Not Used. @@ -40,4 +40,4 @@ public object ConvertBack(object? value, Type targetType, object? parameter, Cul throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/NullToVisibilityConverter.cs b/Rees.Wpf/Converters/NullToVisibilityConverter.cs index 4f46f86e..c87acd1b 100644 --- a/Rees.Wpf/Converters/NullToVisibilityConverter.cs +++ b/Rees.Wpf/Converters/NullToVisibilityConverter.cs @@ -22,11 +22,11 @@ public class NullToVisibilityConverter : IValueConverter /// /// A converted value. If the method returns null, the valid null value is used. /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { var stringParameter = parameter as string; var hiddenValue = Visibility.Hidden; - Func test = () => value is null; + var test = () => value is null; if (stringParameter is not null) { @@ -60,4 +60,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/TextToResourceControlTemplateConverter.cs b/Rees.Wpf/Converters/TextToResourceControlTemplateConverter.cs index b3247862..85097593 100644 --- a/Rees.Wpf/Converters/TextToResourceControlTemplateConverter.cs +++ b/Rees.Wpf/Converters/TextToResourceControlTemplateConverter.cs @@ -26,12 +26,7 @@ public class TextToResourceControlTemplateConverter : IValueConverter public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var resourceName = value as string; - if (string.IsNullOrWhiteSpace(resourceName)) - { - return null; - } - - return (ControlTemplate)Application.Current.TryFindResource(resourceName); + return string.IsNullOrWhiteSpace(resourceName) ? null : (object)(ControlTemplate)Application.Current.TryFindResource(resourceName); } /// @@ -50,4 +45,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/TextToStaticResourceConverter.cs b/Rees.Wpf/Converters/TextToStaticResourceConverter.cs index 7a80aa72..4e397391 100644 --- a/Rees.Wpf/Converters/TextToStaticResourceConverter.cs +++ b/Rees.Wpf/Converters/TextToStaticResourceConverter.cs @@ -55,4 +55,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/ZeroToBlankConverter.cs b/Rees.Wpf/Converters/ZeroToBlankConverter.cs index 1e7b7a7d..b052ef8f 100644 --- a/Rees.Wpf/Converters/ZeroToBlankConverter.cs +++ b/Rees.Wpf/Converters/ZeroToBlankConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows.Data; namespace Rees.Wpf.Converters @@ -20,34 +19,29 @@ public class ZeroToBlankConverter : IValueConverter /// /// A converted value. If the method returns null, the valid null value is used. /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is null) { return null; } - if (value is decimal && (decimal)value == 0) + if (value is decimal and 0) { return null; } - if (value is double && (double)value == 0) + if (value is double and 0) { return null; } - if (value is int && (int)value == 0) + if (value is int and 0) { return null; } - if (value is long && (long)value == 0) - { - return null; - } - - return value; + return value is long and 0 ? null : value; } /// @@ -61,9 +55,9 @@ public object Convert(object value, Type targetType, object parameter, CultureIn /// A converted value. If the method returns null, the valid null value is used. /// /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/Converters/ZeroToVisibilityConverter.cs b/Rees.Wpf/Converters/ZeroToVisibilityConverter.cs index 8e37c275..c0821f06 100644 --- a/Rees.Wpf/Converters/ZeroToVisibilityConverter.cs +++ b/Rees.Wpf/Converters/ZeroToVisibilityConverter.cs @@ -1,5 +1,4 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows; using System.Windows.Data; @@ -22,34 +21,29 @@ public class ZeroToVisibilityConverter : IValueConverter /// /// A converted value. If the method returns null, the valid null value is used. /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is null) { return Visibility.Hidden; } - if (value is decimal && (decimal)value == 0) + if (value is decimal and 0) { return Visibility.Hidden; } - if (value is double && (double)value == 0) + if (value is double and 0) { return Visibility.Hidden; } - if (value is int && (int)value == 0) + if (value is int and 0) { return Visibility.Hidden; } - if (value is long && (long)value == 0) - { - return Visibility.Hidden; - } - - return Visibility.Visible; + return value is long and 0 ? Visibility.Hidden : (object)Visibility.Visible; } /// @@ -68,4 +62,4 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/DIspatcherExtension.cs b/Rees.Wpf/DIspatcherExtension.cs index 8b975b8e..8581a23d 100644 --- a/Rees.Wpf/DIspatcherExtension.cs +++ b/Rees.Wpf/DIspatcherExtension.cs @@ -17,4 +17,4 @@ public static DispatcherOperation BeginInvoke(this Dispatcher instance, Dispatch return instance.BeginInvoke(priority, new Action(lambdaToInvoke)); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/GlobalSuppressions.cs b/Rees.Wpf/GlobalSuppressions.cs index f4d1c258..7f550d76 100644 Binary files a/Rees.Wpf/GlobalSuppressions.cs and b/Rees.Wpf/GlobalSuppressions.cs differ diff --git a/Rees.Wpf/IInitializableController.cs b/Rees.Wpf/IInitializableController.cs index a4441b1e..254d60d2 100644 --- a/Rees.Wpf/IInitializableController.cs +++ b/Rees.Wpf/IInitializableController.cs @@ -12,4 +12,4 @@ public interface IInitializableController /// void Initialize(); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/IRecentFileManager.cs b/Rees.Wpf/IRecentFileManager.cs index 1da9c37a..9a92f3d5 100644 --- a/Rees.Wpf/IRecentFileManager.cs +++ b/Rees.Wpf/IRecentFileManager.cs @@ -51,4 +51,4 @@ public interface IRecentFileManager /// The full and updated list of all recently used files. IEnumerable> UpdateFile(string fullFileName); } -} \ No newline at end of file +} diff --git a/Rees.Wpf/RecentFiles/AppStateRecentFileManager.cs b/Rees.Wpf/RecentFiles/AppStateRecentFileManager.cs index 6d819fb1..2a43a3f0 100644 --- a/Rees.Wpf/RecentFiles/AppStateRecentFileManager.cs +++ b/Rees.Wpf/RecentFiles/AppStateRecentFileManager.cs @@ -132,7 +132,7 @@ protected virtual string GetName(string fullFileName) private IEnumerable> ConvertAndReturnRecentFiles() { - List> results = this.files + var results = this.files .OrderByDescending(f => f.Value.When) .Select(f => new KeyValuePair(f.Key, f.Value.Name)) .ToList(); @@ -158,4 +158,4 @@ private void OnPersistentDataRequested(ApplicationStateRequestedMessage message) message.PersistThisModel(GetPersistentData()); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/RecentFiles/RecentFileV1.cs b/Rees.Wpf/RecentFiles/RecentFileV1.cs index 57a3454e..97ade7a4 100644 --- a/Rees.Wpf/RecentFiles/RecentFileV1.cs +++ b/Rees.Wpf/RecentFiles/RecentFileV1.cs @@ -22,4 +22,4 @@ public class RecentFileV1 /// public DateTime When { get; set; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/RecentFiles/RecentFilesPersistentModelV1.cs b/Rees.Wpf/RecentFiles/RecentFilesPersistentModelV1.cs index 01c0002f..220e8a55 100644 --- a/Rees.Wpf/RecentFiles/RecentFilesPersistentModelV1.cs +++ b/Rees.Wpf/RecentFiles/RecentFilesPersistentModelV1.cs @@ -47,4 +47,4 @@ public RecentFilesPersistentModelV1(Dictionary recentlyUse /// public Dictionary RecentlyUsedFiles { get; set; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ShutdownMessage.cs b/Rees.Wpf/ShutdownMessage.cs index 371f81fe..b4ec9e46 100644 --- a/Rees.Wpf/ShutdownMessage.cs +++ b/Rees.Wpf/ShutdownMessage.cs @@ -7,4 +7,4 @@ public class ShutdownMessage : MessageBase { } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/MessageBoxBase.cs b/Rees.Wpf/UserInteraction/MessageBoxBase.cs index 4ed6a38a..295d09f2 100644 --- a/Rees.Wpf/UserInteraction/MessageBoxBase.cs +++ b/Rees.Wpf/UserInteraction/MessageBoxBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics.CodeAnalysis; using Rees.Wpf.Contracts; @@ -80,4 +80,4 @@ protected static object[] PrependElement(object newElement, object[] existingArr return stringArgs; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WindowsInputBox.cs b/Rees.Wpf/UserInteraction/WindowsInputBox.cs index 9b704e4b..ca70d413 100644 --- a/Rees.Wpf/UserInteraction/WindowsInputBox.cs +++ b/Rees.Wpf/UserInteraction/WindowsInputBox.cs @@ -69,4 +69,4 @@ public string Show(string heading, string question, string defaultInput = "") return Input ?? string.Empty; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WindowsMessageBox.cs b/Rees.Wpf/UserInteraction/WindowsMessageBox.cs index 3bcfa0ea..44a5a83e 100644 --- a/Rees.Wpf/UserInteraction/WindowsMessageBox.cs +++ b/Rees.Wpf/UserInteraction/WindowsMessageBox.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Windows; @@ -127,4 +127,4 @@ private static string RationaliseMessage(string message) return message; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WindowsOpenFileDialog.cs b/Rees.Wpf/UserInteraction/WindowsOpenFileDialog.cs index 80b94696..88dc8d3a 100644 --- a/Rees.Wpf/UserInteraction/WindowsOpenFileDialog.cs +++ b/Rees.Wpf/UserInteraction/WindowsOpenFileDialog.cs @@ -110,4 +110,4 @@ public class WindowsOpenFileDialog : IUserPromptOpenFile return result; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WindowsQuestionBoxYesNo.cs b/Rees.Wpf/UserInteraction/WindowsQuestionBoxYesNo.cs index 2f803279..28227faf 100644 --- a/Rees.Wpf/UserInteraction/WindowsQuestionBoxYesNo.cs +++ b/Rees.Wpf/UserInteraction/WindowsQuestionBoxYesNo.cs @@ -49,4 +49,4 @@ public class WindowsQuestionBoxYesNo : IUserQuestionBoxYesNo return Show(string.Format(CultureInfo.CurrentCulture, questionFormat, argument1, args), heading); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WindowsSaveFileDialog.cs b/Rees.Wpf/UserInteraction/WindowsSaveFileDialog.cs index 5925b948..a6e7a2a6 100644 --- a/Rees.Wpf/UserInteraction/WindowsSaveFileDialog.cs +++ b/Rees.Wpf/UserInteraction/WindowsSaveFileDialog.cs @@ -100,4 +100,4 @@ public class WindowsSaveFileDialog : IUserPromptSaveFile return result; } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/UserInteraction/WpfWaitCursor.cs b/Rees.Wpf/UserInteraction/WpfWaitCursor.cs index ee0c8745..2a93a89d 100644 --- a/Rees.Wpf/UserInteraction/WpfWaitCursor.cs +++ b/Rees.Wpf/UserInteraction/WpfWaitCursor.cs @@ -37,4 +37,4 @@ public void Dispose() new Action(() => Mouse.OverrideCursor = null)); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ValidationRules/GreaterThanOrEqualToZeroRule.cs b/Rees.Wpf/ValidationRules/GreaterThanOrEqualToZeroRule.cs index 7a695100..d57ea60c 100644 --- a/Rees.Wpf/ValidationRules/GreaterThanOrEqualToZeroRule.cs +++ b/Rees.Wpf/ValidationRules/GreaterThanOrEqualToZeroRule.cs @@ -20,8 +20,7 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (value is not null) { - double i; - if (double.TryParse(value.ToString(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, cultureInfo, out i)) + if (double.TryParse(value.ToString(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, cultureInfo, out var i)) { if (i >= 0) { @@ -33,4 +32,4 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo) return new ValidationResult(false, "Please enter a valid numeric value greater than zero."); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ValidationRules/NotEqualToZeroRule.cs b/Rees.Wpf/ValidationRules/NotEqualToZeroRule.cs index 2464aa34..3e21291a 100644 --- a/Rees.Wpf/ValidationRules/NotEqualToZeroRule.cs +++ b/Rees.Wpf/ValidationRules/NotEqualToZeroRule.cs @@ -21,8 +21,7 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (value is not null) { - double i; - if (double.TryParse(value.ToString(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, cultureInfo, out i)) + if (double.TryParse(value.ToString(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, cultureInfo, out var i)) { if (Math.Abs(i) > 0.0001) { @@ -34,4 +33,4 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo) return new ValidationResult(false, "Please enter a valid numeric other than zero."); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ValidationRules/StringNotNullAndNotBlankRule.cs b/Rees.Wpf/ValidationRules/StringNotNullAndNotBlankRule.cs index 2487d7e6..af935a01 100644 --- a/Rees.Wpf/ValidationRules/StringNotNullAndNotBlankRule.cs +++ b/Rees.Wpf/ValidationRules/StringNotNullAndNotBlankRule.cs @@ -20,12 +20,9 @@ public class StringNotNullAndNotBlankRule : ValidationRule public override ValidationResult Validate(object value, CultureInfo cultureInfo) { var str = value as string; - if (str is not null) - { - return string.IsNullOrWhiteSpace(str) ? new ValidationResult(false, "Please enter a text value (other than spaces).") : new ValidationResult(true, null); - } - - return new ValidationResult(false, "Please enter a text value."); + return str is not null + ? string.IsNullOrWhiteSpace(str) ? new ValidationResult(false, "Please enter a text value (other than spaces).") : new ValidationResult(true, null) + : new ValidationResult(false, "Please enter a text value."); } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/ViewModel/MainViewModel.cs b/Rees.Wpf/ViewModel/MainViewModel.cs index 6e79a8db..45eeffa3 100644 --- a/Rees.Wpf/ViewModel/MainViewModel.cs +++ b/Rees.Wpf/ViewModel/MainViewModel.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; namespace Rees.Wpf.ViewModel { @@ -20,4 +20,4 @@ public MainViewModel() //} } } -} \ No newline at end of file +} diff --git a/Rees.Wpf/WpfViewLoader.cs b/Rees.Wpf/WpfViewLoader.cs index 64ea9ee2..0d6e4aeb 100644 --- a/Rees.Wpf/WpfViewLoader.cs +++ b/Rees.Wpf/WpfViewLoader.cs @@ -42,9 +42,9 @@ public virtual void Show(object context) { TargetWindow.Close(); } -// ReSharper disable EmptyGeneralCatchClause + // ReSharper disable EmptyGeneralCatchClause catch -// ReSharper restore EmptyGeneralCatchClause + // ReSharper restore EmptyGeneralCatchClause { // Swallow any exception trying to close the orphaned window. } @@ -107,4 +107,4 @@ protected virtual T CreateWindow() return new T(); } } -} \ No newline at end of file +}