From cd44f11d9e9ec0996696c868f77655100ab099ba Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 23 Sep 2024 16:48:48 +0300 Subject: [PATCH] Adds editorconfig and refactors to the established rules --- .editorconfig | 326 +++++++++++ .../Common/Behaviors/ValidationBehavior.cs | 4 +- .../Converters/OptionalJsonConverter.cs | 2 +- .../OptionalJsonConverterFactory.cs | 4 +- .../ApplicationLayerServices.cs | 13 +- .../BookLibrary/BookMappingConfig.cs | 4 +- .../GetDirectoriesQueryHandler.cs | 3 +- .../GetDirectoryTreeQueryHandler.cs | 46 +- .../GetTreeDirectoriesQueryHandler.cs | 3 +- .../GetDrives/GetDrivesQueryHandler.cs | 2 +- .../Queries/GetFiles/GetFilesQueryHandler.cs | 2 +- .../GetTreeFiles/GetTreeFilesQueryHandler.cs | 2 +- .../CombinePath/CombinePathCommandHandler.cs | 3 +- .../SplitPath/SplitPathCommandHandler.cs | 2 +- .../GetPathParentQueryHandler.cs | 2 +- .../GetPathRoot/GetPathRootQueryHandler.cs | 2 +- .../Commands/AddBook/AddBookCommandHandler.cs | 38 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 4 +- .../Lumina.Application.csproj | 6 +- .../Enums/VideoLibrary/VideoContentType.cs | 2 +- src/Lumina.Contracts/Lumina.Contracts.csproj | 5 +- .../FileManagement/DirectoryResponse.cs | 2 +- .../Common/Configuration/BookConfiguration.cs | 6 +- .../DataAccessLayerServices.cs | 7 +- .../20240826201057_InitialMigration.cs | 372 ++++++------ .../Core/Repositories/Books/BookRepository.cs | 6 +- .../Common/Factory/RepositoryDictionary.cs | 2 +- .../Core/UoW/LuminaDbContext.cs | 4 +- .../Lumina.DataAccess.csproj | 5 +- .../DomainLayerServices.cs | 1 - .../Common/Errors/Errors.MediaContributor.cs | 2 +- .../Common/Models/Core/AggregateRoot.cs | 4 +- .../Common/Models/Core/Entity.cs | 4 +- .../Common/Models/Core/ValueObject.cs | 2 +- .../Common/Primitives/Optional.cs | 10 +- .../ValueObjects/Metadata/BaseMetadata.cs | 36 +- .../Common/ValueObjects/Metadata/Genre.cs | 4 +- .../ValueObjects/Metadata/LanguageInfo.cs | 12 +- .../Common/ValueObjects/Metadata/Rating.cs | 2 +- .../ValueObjects/Metadata/ReleaseInfo.cs | 34 +- .../Common/ValueObjects/Metadata/Tag.cs | 4 +- .../ValueObjects/AudioMetadata.cs | 76 +-- .../Entities/Directory.cs | 19 +- .../FileManagementAggregate/Entities/File.cs | 12 +- .../Entities/UnixRootItem.cs | 11 +- .../Entities/WindowsRootItem.cs | 19 +- .../Services/DirectoryProviderService.cs | 22 +- .../Services/DirectoryService.cs | 44 +- .../Services/DriveService.cs | 8 +- .../Services/FileProviderService.cs | 34 +- .../Services/FileService.cs | 70 +-- .../Services/FileSystemPermissionsService.cs | 8 +- .../Services/FileTypeService.cs | 15 +- .../Services/IPathService.cs | 1 - .../Services/IThumbnailService.cs | 2 +- .../Services/PathService.cs | 29 +- .../Services/ThumbnailService.cs | 41 +- .../Environment/EnvironmentContext.cs | 1 - .../Environment/IEnvironmentContext.cs | 1 - .../Strategies/Path/UnixPathStrategy.cs | 21 +- .../Strategies/Path/WindowsPathStrategy.cs | 39 +- .../Platform/WindowsPlatformContext.cs | 2 +- .../ValueObjects/FileSystemPathId.cs | 4 +- .../ValueObjects/StreamInfo.cs | 52 +- .../MediaContributor.cs | 16 +- .../ValueObjects/ContributorName.cs | 2 +- .../ValueObjects/MediaContributorId.cs | 4 +- .../MovieLibraryAggregate/Movie.cs | 12 +- .../Services/MovieLibraryService.cs | 5 +- .../ValueObjects/MovieId.cs | 6 +- .../ValueObjects/VideoMetadata.cs | 42 +- .../Entities/Episode.cs | 2 +- .../TvShowLibraryAggregate/Entities/Season.cs | 2 +- .../Services/TvShowLibraryService.cs | 5 +- .../TvShowLibraryAggregate/TvShow.cs | 2 +- .../BookLibraryAggregate/Book.cs | 15 +- .../Entities/BookSeries.cs | 11 +- .../Services/BookLibraryService.cs | 5 +- .../Services/IBookLibraryService.cs | 2 +- .../ValueObjects/BookRating.cs | 8 +- .../ValueObjects/WrittenContentMetadata.cs | 38 +- src/Lumina.Domain/Lumina.Domain.csproj | 5 +- .../InfrastructureLayerServices.cs | 2 +- .../SharedConfiguration.cs | 6 +- .../Validation/FluentValidationOptions.cs | 6 +- .../Lumina.Infrastructure.csproj | 6 +- .../Configuration/ConfigureSwaggerOptions.cs | 6 +- .../PresentationApiLayerConfiguration.cs | 2 +- .../PresentationApiLayerServices.cs | 11 +- .../Errors/CustomProblemDetailsFactory.cs | 15 +- .../Common/ModelBinders/UrlStringBinder.cs | 2 +- .../Core/Controllers/Common/ApiController.cs | 6 +- .../FileManagement/DirectoriesController.cs | 6 +- .../FileManagement/DrivesController.cs | 2 +- .../FileManagement/FileSystemController.cs | 7 +- .../FileManagement/FilesController.cs | 4 +- .../FileManagement/PathController.cs | 10 +- .../Maintenance/HealthController.cs | 4 +- .../BookLibrary/Books/BooksController.cs | 8 +- .../Lumina.Presentation.Api.csproj | 13 +- src/Lumina.Presentation.Api/Program.cs | 8 +- .../Common/Api/ApiHttpClient.cs | 28 +- .../PresentationWebLayerServices.cs | 8 +- .../FileManagement/FileSystemItemModel.cs | 1 - .../Validation/FluentValidationOptions.cs | 6 +- .../Lumina.Presentation.Web.csproj | 5 +- .../Pages/Library/Management/Item.razor | 19 +- .../BookLibrary/Books/Item.razor | 22 +- src/Lumina.Presentation.Web/Program.cs | 4 +- src/Lumina.sln | 5 + .../Common/Factory/RepositoryFactoryTests.cs | 4 +- .../Core/UoW/UnitOfWorkTests.cs | 6 +- .../Common/Converters/BookJsonConverter.cs | 114 ++-- .../Common/Setup/BogusExtensions.cs | 4 +- .../Common/Setup/DateOnlySpecimenBuilder.cs | 4 +- .../Common/Setup/LuminaApiFactory.cs | 15 +- .../Setup/NullableDateOnlySpecimenBuilder.cs | 4 +- .../Controllers/Books/BooksControllerTests.cs | 352 ++++++------ .../Books/Fixtures/AddBookRequestFixture.cs | 58 +- .../Common/Setup/BogusExtensions.cs | 4 +- .../Common/Setup/DateOnlySpecimenBuilder.cs | 4 +- .../Setup/NullableDateOnlySpecimenBuilder.cs | 4 +- .../Commands/AddBookCommandHandlerTests.cs | 46 +- .../Commands/AddBookCommandValidatorTests.cs | 531 +++++++++--------- .../Fixtures/AddBookCommandFixture.cs | 58 +- .../DataAccessLayerServicesTests.cs | 18 +- .../Common/Setup/BogusExtensions.cs | 4 +- .../Common/Setup/DateOnlySpecimenBuilder.cs | 4 +- .../Setup/NullableDateOnlySpecimenBuilder.cs | 4 +- .../Repositories/Books/BookRepositoryTests.cs | 46 +- .../Books/Fixtures/BookModelFixture.cs | 32 +- .../Factory/RepositoryDictionaryTests.cs | 24 +- .../Common/Factory/RepositoryFactoryTests.cs | 14 +- .../Core/UoW/UnitOfWorkTests.cs | 45 +- ...nsBuilderFluentValidationUtilitiesTests.cs | 24 +- .../FluentValidationOptionsTests.cs | 52 +- .../CommonSettingsModelValidatorTests.cs | 12 +- .../DatabaseSettingsModelValidatorTests.cs | 12 +- 138 files changed, 1799 insertions(+), 1629 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..f50a0b25 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,326 @@ +root = true + +#### Core EditorConfig Options #### + +[*] +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = lf +insert_final_newline = true +dotnet_style_operator_placement_when_wrapping = end_of_line +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:warning +dotnet_style_readonly_field = true:error +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning +dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:warning +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent + +# Development files +[*.{cs,csx,cshtml,csproj,razor,sln,props,targets,json,md,yml,gitignore,}] +charset = utf-8 + +#### .NET Coding Conventions #### +[*.cs] + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = false + +# this. and Me. preferences +dotnet_style_qualification_for_event = false:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_property = false:silent + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning + +# Expression-level preferences +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning + +# Field preferences +dotnet_style_readonly_field = true:error + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:warning + +# Strings +csharp_style_prefer_string_interpolation = true:suggestion + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:error # var should only be used with anonymous types, and target-typed new expression is encouraged +csharp_style_var_for_built_in_types = false:error +csharp_style_var_when_type_is_apparent = false:error + +# Expression-bodied members +csharp_style_expression_bodied_accessors = false:error +csharp_style_expression_bodied_constructors = false:error +csharp_style_expression_bodied_indexers = false:error +csharp_style_expression_bodied_lambdas = true:suggestion # lamdas don't always require block bodies and explicit return +csharp_style_expression_bodied_local_functions = false:error +csharp_style_expression_bodied_methods = false:error +csharp_style_expression_bodied_operators = false:error +csharp_style_expression_bodied_properties = when_on_single_line:suggestion # domain error properties are allowed to have this style + +# Pattern Matching +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning + + +# "Null" checking preferences +csharp_style_conditional_delegate_call = true:warning + +# Modifier preferences +csharp_prefer_static_local_function = true:suggestion +csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:error + +# Code-block preferences +csharp_prefer_braces = false:error # vertical scope space is vital for code readability, single conditional and iterative expressions waste it up +csharp_prefer_simple_using_statement = false:error # explicit using blocks provide clearer scope control and consistent disposal timing in local scope + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false + +#### Naming styles #### + +# Naming rules + +# Interfaces should begin with an I and be PascalCase +dotnet_naming_rule.interface_should_be_begins_with_i.severity = error +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = interface_style + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_style.interface_style.required_prefix = I +dotnet_naming_style.interface_style.required_suffix = +dotnet_naming_style.interface_style.word_separator = +dotnet_naming_style.interface_style.capitalization = pascal_case + +# Types should be PascalCase +dotnet_naming_rule.types_should_be_pascal_case.severity = error +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_style.types_style.capitalization = pascal_case + +# Non Field members should be PascalCase +dotnet_naming_rule.non_field_members_should_be_camel_case.severity = error +dotnet_naming_rule.non_field_members_should_be_camel_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_camel_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_style.non_field_members_style.capitalization = pascal_case + +# Non-private static fields are camel_case +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = error +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected internal, private protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Constants are UPPER_CASE +dotnet_naming_rule.constants_should_be_pascal_case.severity = error +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = all_upper +dotnet_naming_style.constant_style.word_separator = _ + +# Static fields are PascalCase and start with s_ +dotnet_naming_rule.static_fields_should_be_pascal_case.severity = error +dotnet_naming_rule.static_fields_should_be_pascal_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_pascal_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = pascal_case +dotnet_naming_style.static_field_style.required_prefix = s_ # static members should immediately distinguish themselves from other members + +# Local variables should be camelCase +dotnet_naming_rule.camel_case_for_local_variables.severity = error +dotnet_naming_rule.camel_case_for_local_variables.symbols = local_variables +dotnet_naming_rule.camel_case_for_local_variables.style = parameter_style + +dotnet_naming_symbols.local_variables.applicable_kinds = local + +dotnet_naming_style.local_variables_style.capitalization = camel_case + +# Parameters should be camelCase +dotnet_naming_rule.parameters_should_be_prefixed.severity = error +dotnet_naming_rule.parameters_should_be_prefixed.symbols = parameters +dotnet_naming_rule.parameters_should_be_prefixed.style = parameter_style + +dotnet_naming_symbols.parameters.applicable_kinds = parameter + +dotnet_naming_style.parameter_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = error +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# readonly fields are camelCase and they begin with underscore +dotnet_naming_symbols.readonly_fields.applicable_kinds = field +dotnet_naming_symbols.readonly_fields.required_modifiers = readonly + +dotnet_naming_style.underscore_camel_case_style.capitalization = camel_case +dotnet_naming_style.underscore_camel_case_style.required_prefix = _ + +dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.symbols = readonly_fields +dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.style = underscore_camel_case_style +dotnet_naming_rule.readonly_fields_should_be_underscore_camel_case.severity = warning + +# Additional C# style preferences +csharp_style_namespace_declarations = file_scoped:error # no need for an extra indentation for namespace, when a single type per file rule is enforced. +csharp_style_prefer_method_group_conversion = true:error # more explicit style is preferred +csharp_style_prefer_top_level_statements = false:error # this abomination needs to die! +csharp_style_prefer_primary_constructors = false:error # primary constructors don't inject into readonly fields, immutability is much more important than conciseness +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_prefer_static_anonymous_function = true:suggestion +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_prefer_switch_expression = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs index a3b6ef59..fb0d4e04 100644 --- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs +++ b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs @@ -44,12 +44,12 @@ public class ValidationBehavior : IPipelineBehavior Error.Validation(description: validationFailure.ErrorMessage)); + System.Collections.Generic.List errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage)); // the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic // this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!) return (dynamic)errors; diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs index 29607964..5753d3d9 100644 --- a/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs +++ b/src/Lumina.Application/Common/Converters/OptionalJsonConverter.cs @@ -25,7 +25,7 @@ public class OptionalJsonConverter : JsonConverter> { if (reader.TokenType == JsonTokenType.Null) return Optional.None(); - var value = JsonSerializer.Deserialize(ref reader, options); + TValue? value = JsonSerializer.Deserialize(ref reader, options); return Optional.Some(value!); } diff --git a/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs b/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs index 1f811ded..54df5399 100644 --- a/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs +++ b/src/Lumina.Application/Common/Converters/OptionalJsonConverterFactory.cs @@ -20,9 +20,7 @@ public class OptionalJsonConverterFactory : JsonConverterFactory /// if the type is , otherwise. public override bool CanConvert(Type typeToConvert) { - if (!typeToConvert.IsGenericType) - return false; - return typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>); + return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(Optional<>); } /// diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 2f7fc3a7..da1246f3 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using FluentValidation; using Lumina.Application.Common.Behaviors; +using Mapster; +using MapsterMapper; using Mediator; using Microsoft.Extensions.DependencyInjection; -using FluentValidation; -using MapsterMapper; -using Mapster; #endregion namespace Lumina.Application.Common.DependencyInjection; @@ -23,10 +23,7 @@ public static class ApplicationLayerServices public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services) { // register Mediator - services.AddMediator(options => - { - options.ServiceLifetime = ServiceLifetime.Scoped; - }); + services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); // register the validation behavior services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); @@ -35,7 +32,7 @@ public static class ApplicationLayerServices services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly); // register mapster configs in this assembly - var mapsterConfig = TypeAdapterConfig.GlobalSettings; + TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings; mapsterConfig.Scan(typeof(ApplicationLayerServices).Assembly); services.AddSingleton(mapsterConfig); services.AddScoped(); diff --git a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs index 0661c9e5..00ba4b88 100644 --- a/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs +++ b/src/Lumina.Application/Common/Mapping/WrittenContentLibrary/BookLibrary/BookMappingConfig.cs @@ -108,7 +108,7 @@ public class BookMappingConfig : IRegister Optional.FromNullable(!string.IsNullOrWhiteSpace(src.Format) ? Enum.Parse(src.Format) : default), Optional.FromNullable(src.Edition), Optional.FromNullable(src.VolumeNumber), - Optional.None(), + Optional.None(), Optional.FromNullable(src.ASIN), Optional.FromNullable(src.GoodreadsId), Optional.FromNullable(src.LCCN), @@ -121,7 +121,7 @@ public class BookMappingConfig : IRegister src.Created, Optional.FromNullable(src.Updated), src.ISBNs.Select(i => Isbn.Create(i.Value!, i.Format ?? default).Value).ToList(), - new List(), + new List(), src.Ratings.Select(r => BookRating.Create( r.Value ?? default, r.MaxValue ?? default, diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index d60acf47..5c8dec99 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -4,7 +4,6 @@ using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; -using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -44,7 +43,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) { - var result = _directoryService.GetSubdirectories(request.Path); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs index 9972206f..d4c041f5 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs @@ -56,27 +56,25 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler result = []; // retrieve the list of drives - var getDrivesResult = GetDrives(); + ErrorOr> getDrivesResult = GetDrives(); if (getDrivesResult.IsError) return getDrivesResult.Errors; result.AddRange(getDrivesResult.Value); - var pathPartsResults = _pathService.ParsePath(request.Path); + ErrorOr> pathPartsResults = _pathService.ParsePath(request.Path); if (pathPartsResults.IsError) return pathPartsResults.Errors; - var pathParts = pathPartsResults.Value.ToList(); - var currentPath = pathParts[0].Name; + List pathParts = pathPartsResults.Value.ToList(); + string currentPath = pathParts[0].Name; - var buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out var currentNode); + ErrorOr> buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out FileSystemTreeNodeResponse? currentNode); if (buildDirectoryTreeResult.IsError) return buildDirectoryTreeResult.Errors; // add subdirectories of the last directory node - var loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles); - if (loadChildrenResult.IsError) - return loadChildrenResult.Errors; - return await ValueTask.FromResult(result); + ErrorOr loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles); + return loadChildrenResult.IsError ? (ErrorOr>)loadChildrenResult.Errors : (ErrorOr>)await ValueTask.FromResult(result); } /// @@ -87,10 +85,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler private ErrorOr> GetDrives() { - var driveResult = _driveService.GetDrives(); - if (driveResult.IsError) - return driveResult.Errors; - return ErrorOrFactory.From(driveResult.Value.Adapt>()); + ErrorOr> driveResult = _driveService.GetDrives(); + return driveResult.IsError + ? (ErrorOr>)driveResult.Errors + : ErrorOrFactory.From(driveResult.Value.Adapt>()); } /// @@ -104,21 +102,21 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> BuildDirectoryTree(List drives, List pathParts, out FileSystemTreeNodeResponse currentNode) { // find the root drive that matches the first part of the path - var drive = drives.First(d => d.Name.Contains(pathParts[0].Name)); + FileSystemTreeNodeResponse drive = drives.First(d => d.Name.Contains(pathParts[0].Name)); drive.IsExpanded = true; currentNode = drive; - var currentPath = pathParts[0].Name; + string currentPath = pathParts[0].Name; // traverse the remaining path parts to build the tree structure - for (var i = 1; i < pathParts.Count; i++) + for (int i = 1; i < pathParts.Count; i++) { - var combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name); + ErrorOr combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name); if (combinedPathResult.IsError) return combinedPathResult.Errors; currentPath = combinedPathResult.Value; // create a new node for the directory and add it as a child of the current node - var newNode = new FileSystemTreeNodeResponse + FileSystemTreeNodeResponse newNode = new() { Path = currentPath, Name = pathParts[i].Name, @@ -140,13 +138,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles) { // get subdirectories under the current node's path - var subDirectoriesResult = _directoryService.GetSubdirectories(node.Path); + ErrorOr> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path); if (subDirectoriesResult.IsError) return subDirectoriesResult.Errors; // add each subdirectory as a child node of the current directory - foreach (var subDirectory in subDirectoriesResult.Value) + foreach (Directory subDirectory in subDirectoriesResult.Value) { - var subDirNode = new FileSystemTreeNodeResponse + FileSystemTreeNodeResponse subDirNode = new() { Name = subDirectory.Name, Path = subDirectory.Id.Path, @@ -159,13 +157,13 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> filesResult = _fileService.GetFiles(node.Path); if (filesResult.IsError) return filesResult.Errors; // add each file as a child node of the current directory - foreach (var file in filesResult.Value) + foreach (File file in filesResult.Value) { - var fileNode = new FileSystemTreeNodeResponse + FileSystemTreeNodeResponse fileNode = new() { Name = file.Name, Path = file.Id.Path, diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs index 7116c245..39ab2617 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs @@ -4,7 +4,6 @@ using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; -using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -44,7 +43,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) { - var result = _directoryService.GetSubdirectories(request.Path); + ErrorOr> result = _directoryService.GetSubdirectories(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index bdffd24c..e8b1bbdc 100644 --- a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetDrivesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) { - var result = _driveService.GetDrives(); + ErrorOr> result = _driveService.GetDrives(); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index a25ea467..cddf9b7d 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetFilesQuery request, CancellationToken cancellationToken) { - var result = _fileService.GetFiles(request.Path); + ErrorOr> result = _fileService.GetFiles(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 58e45e56..3a7c9242 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -43,7 +43,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) { - var result = _fileService.GetFiles(request.Path); + ErrorOr> result = _fileService.GetFiles(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs index e0ab6f82..6af4bb5b 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs @@ -3,7 +3,6 @@ using ErrorOr; using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Mapster; using Mediator; using System.Threading; using System.Threading.Tasks; @@ -42,7 +41,7 @@ public class CombinePathCommandHandler : IRequestHandler public ValueTask> Handle(CombinePathCommand request, CancellationToken cancellationToken) { - var result = _pathService.CombinePath(request.OriginalPath, request.NewPath); + ErrorOr result = _pathService.CombinePath(request.OriginalPath, request.NewPath); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index ceb5fb13..d2ad4bbd 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -43,7 +43,7 @@ public class SplitPathCommandHandler : IRequestHandler public ValueTask>> Handle(SplitPathCommand request, CancellationToken cancellationToken) { - var result = _pathService.ParsePath(request.Path); + ErrorOr> result = _pathService.ParsePath(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index faee9fe1..dbd7f8b7 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -43,7 +43,7 @@ public class GetPathParentQueryHandler : IRequestHandler public ValueTask>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) { - var result = _pathService.GoUpOneLevel(request.Path); + ErrorOr> result = _pathService.GoUpOneLevel(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index 8cb1cafc..b08dba31 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -40,7 +40,7 @@ public class GetPathRootQueryHandler : IRequestHandlerThe root of the specified path. public ValueTask> Handle(GetPathRootQuery request, CancellationToken cancellationToken) { - var result = _pathService.GetPathRoot(request.Path); + ErrorOr result = _pathService.GetPathRoot(request.Path); return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt()), errors => errors)); } #endregion diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 66529182..8da44021 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -57,7 +57,7 @@ public class AddBookCommandHandler : IRequestHandler contributorIds = []; - foreach (var mediaContributor in request.Contributors) + foreach (Contracts.Models.MediaContributors.MediaContributorModel mediaContributor in request.Contributors) { // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names } @@ -67,37 +67,37 @@ public class AddBookCommandHandler : IRequestHandler BookRating.Create( + List> domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create( rating.Value ?? default, rating.MaxValue ?? default, Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : default), Optional.FromNullable(rating.VoteCount))); // check if any of the results contain errors - var errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList(); + List errors = domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors).ToList(); if (errors.Count != 0) // if there are errors, return them return errors; - var domainRatings = domainRatingsResult.Select(rating => rating.Value).ToList(); + List domainRatings = domainRatingsResult.Select(rating => rating.Value).ToList(); - var domainGenresResult = request.Metadata.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); + List> domainGenresResult = request.Metadata.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); errors = domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors).ToList(); if (errors.Count != 0) return errors; - var domainGenres = domainGenresResult.Select(genre => genre.Value).ToList(); + List domainGenres = domainGenresResult.Select(genre => genre.Value).ToList(); - var domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); + List> domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); errors = domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors).ToList(); if (errors.Count != 0) return errors; - var domainTags = domainTagsResult.Select(tag => tag.Value).ToList(); + List domainTags = domainTagsResult.Select(tag => tag.Value).ToList(); - var domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); + List> domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList(); if (errors.Count != 0) return errors; - var domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList(); + List domainIsbns = domainIsbnsResult.Select(isbn => isbn.Value).ToList(); - var releaseInfoResult = ReleaseInfo.Create( + ErrorOr releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate), Optional.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear), Optional.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate), @@ -107,11 +107,11 @@ public class AddBookCommandHandler : IRequestHandler languageInfoResult = LanguageInfo.Create( request.Metadata.Language.LanguageCode!, request.Metadata.Language.LanguageName!, Optional.FromNullable(request.Metadata.Language.NativeName)); @@ -122,7 +122,7 @@ public class AddBookCommandHandler : IRequestHandler originalLanguageInfoResult = LanguageInfo.Create( request.Metadata.OriginalLanguage.LanguageCode!, request.Metadata.OriginalLanguage.LanguageName!, Optional.FromNullable(request.Metadata.OriginalLanguage.NativeName)); @@ -130,7 +130,7 @@ public class AddBookCommandHandler : IRequestHandler metadataResult = WrittenContentMetadata.Create( request.Metadata.Title!, Optional.FromNullable(request.Metadata.OriginalTitle), Optional.FromNullable(request.Metadata.Description), @@ -144,7 +144,7 @@ public class AddBookCommandHandler : IRequestHandler createBookResult = Book.Create( metadataResult.Value, Optional.FromNullable(request.Format), Optional.FromNullable(request.Edition), @@ -166,9 +166,9 @@ public class AddBookCommandHandler : IRequestHandler(); - var persistenceBook = _mapper.Map(createBookResult.Value); - var insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); + IBookRepository bookRepository = _unitOfWork.GetRepository(); + BookModel persistenceBook = _mapper.Map(createBookResult.Value); + ErrorOr insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); if (insertBookResult.IsError) return insertBookResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 8f8af998..ca2fc9e5 100644 --- a/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -43,8 +43,8 @@ public class GetBooksQueryHandler : IRequestHandler public async ValueTask>> Handle(GetBooksQuery request, CancellationToken cancellationToken) { - var bookRepository = _unitOfWork.GetRepository(); - var getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + IBookRepository bookRepository = _unitOfWork.GetRepository(); + ErrorOr> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return getBooksResult.Match(values => ErrorOrFactory.From(values.Adapt>()), errors => errors); } #endregion diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 73407fc8..e2318eaa 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -1,11 +1,11 @@ - - + net8.0 disable enable $(SolutionDir)..\bin\server\ - false + false + true diff --git a/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs b/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs index 2a72bbd4..f6f5f57a 100644 --- a/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs +++ b/src/Lumina.Contracts/Enums/VideoLibrary/VideoContentType.cs @@ -1,4 +1,4 @@ -namespace Lumina.Contracts.Enums.FileSystem.VideoLibrary; +namespace Lumina.Contracts.Enums.VideoLibrary; /// /// Enumeration for the types of video content libraries. diff --git a/src/Lumina.Contracts/Lumina.Contracts.csproj b/src/Lumina.Contracts/Lumina.Contracts.csproj index ab6554a1..0f38f5a4 100644 --- a/src/Lumina.Contracts/Lumina.Contracts.csproj +++ b/src/Lumina.Contracts/Lumina.Contracts.csproj @@ -1,11 +1,11 @@ - - + net8.0 disable enable $(SolutionDir)..\bin\server\ false + true @@ -15,5 +15,4 @@ - diff --git a/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs index 76227fb3..e518a7b9 100644 --- a/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs +++ b/src/Lumina.Contracts/Responses/FileManagement/DirectoryResponse.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Models.FileManagement; using System; using System.Collections.Generic; using System.Diagnostics; -using Lumina.Contracts.Models.FileManagement; #endregion namespace Lumina.Contracts.Responses.FileManagement; diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index 8e8ea41a..8f6505e0 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -126,7 +126,7 @@ public class BookConfiguration : IEntityTypeConfiguration ratingBuilder.Property(rating => rating.Source) .HasConversion() - .HasMaxLength(50) + .HasMaxLength(50) .IsRequired(); }); @@ -139,12 +139,12 @@ public class BookConfiguration : IEntityTypeConfiguration isbnBuilder.Property(isbn => isbn.Value) .HasColumnName("ISBN") - .HasMaxLength(13) + .HasMaxLength(13) .IsRequired(); isbnBuilder.Property(isbn => isbn.Format) .HasConversion() - .HasMaxLength(6) + .HasMaxLength(6) .IsRequired(); }); } diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index 8596916f..30e80c26 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -27,13 +27,10 @@ public static class DataAccessLayerServices /// The updated . public static void AddDataAccessLayerServices(this IServiceCollection services) { - var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!Directory.Exists(basePath)) throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); - services.AddDbContext(options => - { - options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"); - }); + services.AddDbContext(options => options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}")); services.AddScoped(); Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes(); diff --git a/src/Lumina.DataAccess/Common/Migrations/20240826201057_InitialMigration.cs b/src/Lumina.DataAccess/Common/Migrations/20240826201057_InitialMigration.cs index 728c6d60..d6a06f0c 100644 --- a/src/Lumina.DataAccess/Common/Migrations/20240826201057_InitialMigration.cs +++ b/src/Lumina.DataAccess/Common/Migrations/20240826201057_InitialMigration.cs @@ -1,216 +1,206 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; +using System; #nullable disable -namespace Lumina.DataAccess.Common.Migrations +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class InitialMigration : Migration { /// - public partial class InitialMigration : Migration + protected override void Up(MigrationBuilder migrationBuilder) { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Books", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Title = table.Column(type: "TEXT", maxLength: 255, nullable: false), - OriginalTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), - Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - OriginalReleaseDate = table.Column(type: "TEXT", nullable: true), - OriginalReleaseYear = table.Column(type: "INTEGER", nullable: true), - ReReleaseDate = table.Column(type: "TEXT", nullable: true), - ReReleaseYear = table.Column(type: "INTEGER", nullable: true), - ReleaseCountry = table.Column(type: "TEXT", nullable: true), - ReleaseVersion = table.Column(type: "TEXT", nullable: true), - LanguageCode = table.Column(type: "TEXT", nullable: true), - LanguageName = table.Column(type: "TEXT", nullable: true), - LanguageNativeName = table.Column(type: "TEXT", nullable: true), - OriginalLanguageCode = table.Column(type: "TEXT", nullable: true), - OriginalLanguageName = table.Column(type: "TEXT", nullable: true), - OriginalLanguageNativeName = table.Column(type: "TEXT", nullable: true), - Publisher = table.Column(type: "TEXT", maxLength: 100, nullable: true), - PageCount = table.Column(type: "INTEGER", nullable: true), - Format = table.Column(type: "TEXT", nullable: false), - Edition = table.Column(type: "TEXT", maxLength: 50, nullable: true), - VolumeNumber = table.Column(type: "INTEGER", nullable: true), - ASIN = table.Column(type: "TEXT", maxLength: 10, nullable: true), - GoodreadsId = table.Column(type: "TEXT", nullable: true), - LCCN = table.Column(type: "TEXT", nullable: true), - OCLCNumber = table.Column(type: "TEXT", nullable: true), - OpenLibraryId = table.Column(type: "TEXT", maxLength: 50, nullable: true), - LibraryThingId = table.Column(type: "TEXT", maxLength: 50, nullable: true), - GoogleBooksId = table.Column(type: "TEXT", maxLength: 12, nullable: true), - BarnesAndNobleId = table.Column(type: "TEXT", maxLength: 10, nullable: true), - AppleBooksId = table.Column(type: "TEXT", nullable: true), - Created = table.Column(type: "TEXT", nullable: false), - Updated = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Books", x => x.Id); - }); + migrationBuilder.CreateTable( + name: "Books", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 255, nullable: false), + OriginalTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), + Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + OriginalReleaseDate = table.Column(type: "TEXT", nullable: true), + OriginalReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReReleaseDate = table.Column(type: "TEXT", nullable: true), + ReReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReleaseCountry = table.Column(type: "TEXT", nullable: true), + ReleaseVersion = table.Column(type: "TEXT", nullable: true), + LanguageCode = table.Column(type: "TEXT", nullable: true), + LanguageName = table.Column(type: "TEXT", nullable: true), + LanguageNativeName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageCode = table.Column(type: "TEXT", nullable: true), + OriginalLanguageName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageNativeName = table.Column(type: "TEXT", nullable: true), + Publisher = table.Column(type: "TEXT", maxLength: 100, nullable: true), + PageCount = table.Column(type: "INTEGER", nullable: true), + Format = table.Column(type: "TEXT", nullable: false), + Edition = table.Column(type: "TEXT", maxLength: 50, nullable: true), + VolumeNumber = table.Column(type: "INTEGER", nullable: true), + ASIN = table.Column(type: "TEXT", maxLength: 10, nullable: true), + GoodreadsId = table.Column(type: "TEXT", nullable: true), + LCCN = table.Column(type: "TEXT", nullable: true), + OCLCNumber = table.Column(type: "TEXT", nullable: true), + OpenLibraryId = table.Column(type: "TEXT", maxLength: 50, nullable: true), + LibraryThingId = table.Column(type: "TEXT", maxLength: 50, nullable: true), + GoogleBooksId = table.Column(type: "TEXT", maxLength: 12, nullable: true), + BarnesAndNobleId = table.Column(type: "TEXT", maxLength: 10, nullable: true), + AppleBooksId = table.Column(type: "TEXT", nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Updated = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => table.PrimaryKey("PK_Books", x => x.Id)); - migrationBuilder.CreateTable( - name: "Genres", - columns: table => new - { - Name = table.Column(type: "TEXT", maxLength: 50, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Genres", x => x.Name); - }); + migrationBuilder.CreateTable( + name: "Genres", + columns: table => new + { + Name = table.Column(type: "TEXT", maxLength: 50, nullable: false) + }, + constraints: table => table.PrimaryKey("PK_Genres", x => x.Name)); - migrationBuilder.CreateTable( - name: "Tags", - columns: table => new - { - Name = table.Column(type: "TEXT", maxLength: 50, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Tags", x => x.Name); - }); + migrationBuilder.CreateTable( + name: "Tags", + columns: table => new + { + Name = table.Column(type: "TEXT", maxLength: 50, nullable: false) + }, + constraints: table => table.PrimaryKey("PK_Tags", x => x.Name)); - migrationBuilder.CreateTable( - name: "BookISBNs", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ISBN = table.Column(type: "TEXT", maxLength: 13, nullable: false), - Format = table.Column(type: "TEXT", maxLength: 6, nullable: false), - BookId = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_BookISBNs", x => x.Id); - table.ForeignKey( - name: "FK_BookISBNs_Books_BookId", - column: x => x.BookId, - principalTable: "Books", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); + migrationBuilder.CreateTable( + name: "BookISBNs", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ISBN = table.Column(type: "TEXT", maxLength: 13, nullable: false), + Format = table.Column(type: "TEXT", maxLength: 6, nullable: false), + BookId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_BookISBNs", x => x.Id); + table.ForeignKey( + name: "FK_BookISBNs_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); - migrationBuilder.CreateTable( - name: "BookRatings", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Source = table.Column(type: "TEXT", maxLength: 50, nullable: false), - BookId = table.Column(type: "TEXT", nullable: false), - Value = table.Column(type: "decimal(3,2)", nullable: false), - MaxValue = table.Column(type: "decimal(3,2)", nullable: false), - VoteCount = table.Column(type: "INTEGER", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_BookRatings", x => x.Id); - table.ForeignKey( - name: "FK_BookRatings_Books_BookId", - column: x => x.BookId, - principalTable: "Books", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); + migrationBuilder.CreateTable( + name: "BookRatings", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Source = table.Column(type: "TEXT", maxLength: 50, nullable: false), + BookId = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "decimal(3,2)", nullable: false), + MaxValue = table.Column(type: "decimal(3,2)", nullable: false), + VoteCount = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BookRatings", x => x.Id); + table.ForeignKey( + name: "FK_BookRatings_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); - migrationBuilder.CreateTable( - name: "BookGenres", - columns: table => new - { - BookId = table.Column(type: "TEXT", nullable: false), - GenreId = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId }); - table.ForeignKey( - name: "FK_BookGenres_Books_BookId", - column: x => x.BookId, - principalTable: "Books", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_BookGenres_Genres_GenreId", - column: x => x.GenreId, - principalTable: "Genres", - principalColumn: "Name", - onDelete: ReferentialAction.Cascade); - }); + migrationBuilder.CreateTable( + name: "BookGenres", + columns: table => new + { + BookId = table.Column(type: "TEXT", nullable: false), + GenreId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_BookGenres", x => new { x.BookId, x.GenreId }); + table.ForeignKey( + name: "FK_BookGenres_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_BookGenres_Genres_GenreId", + column: x => x.GenreId, + principalTable: "Genres", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); - migrationBuilder.CreateTable( - name: "BookTags", - columns: table => new - { - BookId = table.Column(type: "TEXT", nullable: false), - TagId = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId }); - table.ForeignKey( - name: "FK_BookTags_Books_BookId", - column: x => x.BookId, - principalTable: "Books", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_BookTags_Tags_TagId", - column: x => x.TagId, - principalTable: "Tags", - principalColumn: "Name", - onDelete: ReferentialAction.Cascade); - }); + migrationBuilder.CreateTable( + name: "BookTags", + columns: table => new + { + BookId = table.Column(type: "TEXT", nullable: false), + TagId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_BookTags", x => new { x.BookId, x.TagId }); + table.ForeignKey( + name: "FK_BookTags_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_BookTags_Tags_TagId", + column: x => x.TagId, + principalTable: "Tags", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); - migrationBuilder.CreateIndex( - name: "IX_BookGenres_GenreId", - table: "BookGenres", - column: "GenreId"); + migrationBuilder.CreateIndex( + name: "IX_BookGenres_GenreId", + table: "BookGenres", + column: "GenreId"); - migrationBuilder.CreateIndex( - name: "IX_BookISBNs_BookId", - table: "BookISBNs", - column: "BookId"); + migrationBuilder.CreateIndex( + name: "IX_BookISBNs_BookId", + table: "BookISBNs", + column: "BookId"); - migrationBuilder.CreateIndex( - name: "IX_BookRatings_BookId", - table: "BookRatings", - column: "BookId"); + migrationBuilder.CreateIndex( + name: "IX_BookRatings_BookId", + table: "BookRatings", + column: "BookId"); - migrationBuilder.CreateIndex( - name: "IX_BookTags_TagId", - table: "BookTags", - column: "TagId"); - } + migrationBuilder.CreateIndex( + name: "IX_BookTags_TagId", + table: "BookTags", + column: "TagId"); + } - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "BookGenres"); + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "BookGenres"); - migrationBuilder.DropTable( - name: "BookISBNs"); + migrationBuilder.DropTable( + name: "BookISBNs"); - migrationBuilder.DropTable( - name: "BookRatings"); + migrationBuilder.DropTable( + name: "BookRatings"); - migrationBuilder.DropTable( - name: "BookTags"); + migrationBuilder.DropTable( + name: "BookTags"); - migrationBuilder.DropTable( - name: "Genres"); + migrationBuilder.DropTable( + name: "Genres"); - migrationBuilder.DropTable( - name: "Books"); + migrationBuilder.DropTable( + name: "Books"); - migrationBuilder.DropTable( - name: "Tags"); - } + migrationBuilder.DropTable( + name: "Tags"); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index fd4fc02e..bd7a110e 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -43,16 +43,16 @@ internal sealed class BookRepository : IBookRepository /// An representing either a successfull operation, or an error. public async Task> InsertAsync(BookModel book, CancellationToken cancellationToken) { - var jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + bool jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (jobExists) return Errors.WrittenContent.BookAlreadyExists; // fetch existing tags and genres - var existingTags = await _luminaDbContext.Set() + List existingTags = await _luminaDbContext.Set() .Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name)) .ToListAsync(cancellationToken).ConfigureAwait(false); - var existingGenres = await _luminaDbContext.Set() + List existingGenres = await _luminaDbContext.Set() .Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name)) .ToListAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs b/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs index c9760531..42b4dd82 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs @@ -20,7 +20,7 @@ public class RepositoryDictionary /// /// Gets the number of added repositories. /// - public int Count { get { return _container.Count; } } + public int Count => _container.Count; #endregion #region ===================================================================== METHODS =================================================================================== diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index be38c9c4..e063843f 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -53,10 +53,10 @@ public class LuminaDbContext : DbContext public override int SaveChanges() { // get all the entity entries that are either added or modified - var entries = ChangeTracker.Entries() + IEnumerable entries = ChangeTracker.Entries() .Where(e => e.Entity is IStorageEntity && (e.State is EntityState.Added or EntityState.Modified)); - foreach (var entityEntry in entries) + foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? entityEntry in entries) { // if the entity is in Added state, set the Created property to the current date and time if (entityEntry.State == EntityState.Added) diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index 0ebac19e..d67b0576 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -1,11 +1,11 @@ - - + net8.0 disable enable $(SolutionDir)..\bin\server\ false + true @@ -30,5 +30,4 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index 4265cbd7..326cf2cf 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index e92821a9..7882132b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -13,7 +13,7 @@ public static partial class Errors { #region ==================================================================== PROPERTIES ================================================================================= - public static Error ContributorsListCannotBeNull => Error.Validation(nameof(ContributorsListCannotBeNull)); + public static Error ContributorsListCannotBeNull => Error.Validation(nameof(ContributorsListCannotBeNull)); public static Error ContributorNameCannotBeEmpty => Error.Validation(nameof(ContributorNameCannotBeEmpty)); public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(nameof(ContributorDisplayNameCannotBeEmpty)); public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(nameof(ContributorDisplayNameMustBeMaximum100CharactersLong)); diff --git a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs index 264dc0db..c616be3c 100644 --- a/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs +++ b/src/Lumina.Domain/Common/Models/Core/AggregateRoot.cs @@ -21,8 +21,8 @@ public abstract class AggregateRoot : Entity where TId : notnull /// Initializes a new instance of the class. /// protected AggregateRoot() // only needed during reflection - { - + { + } #pragma warning restore CS8618 #endregion diff --git a/src/Lumina.Domain/Common/Models/Core/Entity.cs b/src/Lumina.Domain/Common/Models/Core/Entity.cs index f473976d..d0dcd5ee 100644 --- a/src/Lumina.Domain/Common/Models/Core/Entity.cs +++ b/src/Lumina.Domain/Common/Models/Core/Entity.cs @@ -42,8 +42,8 @@ public abstract class Entity : IEquatable> where TId : notnull /// Initializes a new instance of the class. /// protected Entity() // only needed during reflection - { - + { + } #pragma warning restore CS8618 #endregion diff --git a/src/Lumina.Domain/Common/Models/Core/ValueObject.cs b/src/Lumina.Domain/Common/Models/Core/ValueObject.cs index b3b3fdd2..308e0f54 100644 --- a/src/Lumina.Domain/Common/Models/Core/ValueObject.cs +++ b/src/Lumina.Domain/Common/Models/Core/ValueObject.cs @@ -37,7 +37,7 @@ public abstract class ValueObject : IEquatable { if (obj is null || obj.GetType() != GetType()) return false; - var valueObject = (ValueObject)obj; + ValueObject valueObject = (ValueObject)obj; return GetEqualityComponents().SequenceEqual(valueObject.GetEqualityComponents()); } diff --git a/src/Lumina.Domain/Common/Primitives/Optional.cs b/src/Lumina.Domain/Common/Primitives/Optional.cs index c0c04098..28b60d10 100644 --- a/src/Lumina.Domain/Common/Primitives/Optional.cs +++ b/src/Lumina.Domain/Common/Primitives/Optional.cs @@ -16,17 +16,11 @@ public readonly struct Optional /// Gets a value indicating whether this structure has a value. /// public bool HasValue { get; } - + /// /// Gets the value represented by this structure. /// - public TValue Value - { - get - { - return HasValue ? _value! : default!; - } - } + public TValue Value => HasValue ? _value! : default!; #endregion #region ====================================================================== CTOR ===================================================================================== diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs index d9a90a1b..8c94ebd3 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs @@ -18,12 +18,12 @@ public abstract class BaseMetadata : ValueObject private readonly List _tags; private readonly List _genres; #endregion - + #region ==================================================================== PROPERTIES ================================================================================= /// /// Gets the title of the media item. /// - public string Title { get; private set;} + public string Title { get; private set; } /// /// Gets the original title of the media item. @@ -44,7 +44,7 @@ public abstract class BaseMetadata : ValueObject /// Gets the optional language of the media item. /// public Optional Language { get; private set; } - + /// /// Gets the optional original language of the media item. /// @@ -53,18 +53,12 @@ public abstract class BaseMetadata : ValueObject /// /// Gets the list of tags associated with the media item. /// - public IReadOnlyCollection Tags - { - get { return _tags.AsReadOnly(); } - } - + public IReadOnlyCollection Tags => _tags.AsReadOnly(); + /// /// Gets the list of genres associated with the media item. /// - public IReadOnlyCollection Genres - { - get { return _genres.AsReadOnly(); } - } + public IReadOnlyCollection Genres => _genres.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -81,13 +75,13 @@ public abstract class BaseMetadata : ValueObject /// The optional original language of the element to which this metadata object belongs to. /// Thrown when the value is protected BaseMetadata( - string title, - Optional originalTitle, - Optional description, - ReleaseInfo releaseInfo, - List genres, - List tags, - Optional language, + string title, + Optional originalTitle, + Optional description, + ReleaseInfo releaseInfo, + List genres, + List tags, + Optional language, Optional originalLanguage) { Title = title ?? throw new ArgumentNullException(nameof(title)); @@ -109,9 +103,9 @@ public abstract class BaseMetadata : ValueObject yield return OriginalTitle; yield return Description; yield return ReleaseInfo; - foreach (var genre in _genres) + foreach (Genre genre in _genres) yield return genre; - foreach (var tag in _tags) + foreach (Tag tag in _tags) yield return tag; yield return Language; yield return OriginalLanguage; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index 10138b69..4ae81afd 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -41,9 +41,7 @@ public class Genre : ValueObject /// public static ErrorOr Create(string name) { - if (string.IsNullOrWhiteSpace(name)) - return Errors.Errors.Metadata.GenreNameCannotBeEmpty; - return new Genre(name); + return string.IsNullOrWhiteSpace(name) ? (ErrorOr)Errors.Errors.Metadata.GenreNameCannotBeEmpty : (ErrorOr)new Genre(name); } /// diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index 2218744f..a8808543 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -58,13 +58,11 @@ public class LanguageInfo : ValueObject /// public static ErrorOr Create(string languageCode, string languageName, Optional nativeName) { - if (string.IsNullOrWhiteSpace(languageCode)) - return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty; - if (string.IsNullOrWhiteSpace(languageName)) - return Errors.Errors.Metadata.LanguageNameCannotBeEmpty; - if (languageCode.Length != 2) - return Errors.Errors.Metadata.InvalidIsoCode; - return new LanguageInfo(languageCode, languageName, nativeName); + return string.IsNullOrWhiteSpace(languageCode) + ? (ErrorOr)Errors.Errors.Metadata.LanguageCodeCannotBeEmpty + : string.IsNullOrWhiteSpace(languageName) + ? (ErrorOr)Errors.Errors.Metadata.LanguageNameCannotBeEmpty + : languageCode.Length != 2 ? (ErrorOr)Errors.Errors.Metadata.InvalidIsoCode : (ErrorOr)new LanguageInfo(languageCode, languageName, nativeName); } /// diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs index e93f2355..e444494a 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Rating.cs @@ -51,7 +51,7 @@ public abstract class Rating : ValueObject /// The rating value as a percentage of the maximum value. public decimal AsPercentage() { - return (Value / MaxValue) * 100; + return Value / MaxValue * 100; } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs index 30e17d37..b7151d90 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/ReleaseInfo.cs @@ -59,11 +59,11 @@ public class ReleaseInfo : ValueObject /// The optional country or region of release. /// The optional release version or edition. private ReleaseInfo( - Optional originalReleaseDate, + Optional originalReleaseDate, Optional originalReleaseYear, - Optional reReleaseDate, - Optional reReleaseYear, - Optional releaseCountry, + Optional reReleaseDate, + Optional reReleaseYear, + Optional releaseCountry, Optional releaseVersion) { OriginalReleaseDate = originalReleaseDate; @@ -89,22 +89,22 @@ public class ReleaseInfo : ValueObject /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( - Optional originalReleaseDate, + Optional originalReleaseDate, Optional originalReleaseYear, - Optional reReleaseDate, - Optional reReleaseYear, - Optional releaseCountry, + Optional reReleaseDate, + Optional reReleaseYear, + Optional releaseCountry, Optional releaseVersion) { - if (originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value) - return Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch; - if (reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value) - return Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch; - if (originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value) - return Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate; - if (originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value) - return Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear; - return new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion); + return originalReleaseDate.HasValue && originalReleaseYear.HasValue && originalReleaseDate.Value.Year != originalReleaseYear.Value + ? (ErrorOr)Errors.Errors.Metadata.OriginalReleaseDateAndYearMustMatch + : reReleaseDate.HasValue && reReleaseYear.HasValue && reReleaseDate.Value.Year != reReleaseYear.Value + ? (ErrorOr)Errors.Errors.Metadata.ReReleaseDateAndYearMustMatch + : originalReleaseDate.HasValue && reReleaseDate.HasValue && originalReleaseDate.Value > reReleaseDate.Value + ? (ErrorOr)Errors.Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate + : originalReleaseYear.HasValue && reReleaseYear.HasValue && originalReleaseYear.Value > reReleaseYear.Value + ? (ErrorOr)Errors.Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear + : (ErrorOr)new ReleaseInfo(originalReleaseDate, originalReleaseYear, reReleaseDate, reReleaseYear, releaseCountry, releaseVersion); } /// diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index abf923c5..67cb76ea 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -41,9 +41,7 @@ public class Tag : ValueObject /// public static ErrorOr Create(string name) { - if (string.IsNullOrWhiteSpace(name)) - return Errors.Errors.Metadata.TagNameCannotBeEmpty; - return new Tag(name); + return string.IsNullOrWhiteSpace(name) ? (ErrorOr)Errors.Errors.Metadata.TagNameCannotBeEmpty : (ErrorOr)new Tag(name); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs b/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs index 4c108c84..4da5b369 100644 --- a/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/AudioLibrary/AudioLibraryAggregate/ValueObjects/AudioMetadata.cs @@ -64,19 +64,19 @@ public class AudioMetadata : BaseMetadata /// The genres of the audio. /// The tags associated with the audio. public AudioMetadata( - string title, - Optional originalTitle, - int durationInSeconds, - int sampleRate, - int channels, - ReleaseInfo releaseInfo, + string title, + Optional originalTitle, + int durationInSeconds, + int sampleRate, + int channels, + ReleaseInfo releaseInfo, Optional description, - List genres, - List tags, - Optional language, - Optional originalLanguage, - Optional bitDepth, - Optional audioCodec, + List genres, + List tags, + Optional language, + Optional originalLanguage, + Optional bitDepth, + Optional audioCodec, Optional bitrate) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { @@ -110,43 +110,43 @@ public class AudioMetadata : BaseMetadata /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( - string title, - Optional originalTitle, - int durationInSeconds, - int sampleRate, - int channels, - ReleaseInfo release, - Optional + string title, + Optional originalTitle, + int durationInSeconds, + int sampleRate, + int channels, + ReleaseInfo release, + Optional description, - List genres, - List tags, - Optional language, - Optional originalLanguage, - Optional bitDepth, - Optional audioCodec, + List genres, + List tags, + Optional language, + Optional originalLanguage, + Optional bitDepth, + Optional audioCodec, Optional bitrate) { return new AudioMetadata( - title, - originalTitle, - durationInSeconds, - sampleRate, - channels, - release, - description, - genres, + title, + originalTitle, + durationInSeconds, + sampleRate, + channels, + release, + description, + genres, tags, - language, - originalLanguage, - bitDepth, - audioCodec, + language, + originalLanguage, + bitDepth, + audioCodec, bitrate); } /// public override IEnumerable GetEqualityComponents() { - foreach (var component in base.GetEqualityComponents()) + foreach (object component in base.GetEqualityComponents()) yield return component; yield return DurationInSeconds; yield return SampleRate; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs index e35e5721..ac7de505 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/Directory.cs @@ -19,7 +19,7 @@ public sealed class Directory : FileSystemItem #region ================================================================== FIELD MEMBERS ================================================================================ private readonly List _items = []; #endregion - + #region ==================================================================== PROPERTIES ================================================================================= /// /// Gets or sets the creation date of the file system item. Can be optional if the information is not available. @@ -34,10 +34,7 @@ public sealed class Directory : FileSystemItem /// /// Gets the collection of file system items that are children to the current directory entity. /// - public IReadOnlyCollection Items - { - get { return _items.AsReadOnly(); } - } + public IReadOnlyCollection Items => _items.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -77,15 +74,13 @@ public sealed class Directory : FileSystemItem ErrorOr createPathResult = FileSystemPathId.Create(path); if (createPathResult.IsError) return createPathResult.Errors; - Directory newDirectory = new Directory( + Directory newDirectory = new( createPathResult.Value, name, dateCreated, dateModified); ErrorOr setStatusResult = newDirectory.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newDirectory; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newDirectory; } /// @@ -106,15 +101,13 @@ public sealed class Directory : FileSystemItem FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - Directory newDirectory = new Directory( + Directory newDirectory = new( id, name, dateCreated, dateModified); ErrorOr setStatusResult = newDirectory.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newDirectory; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newDirectory; } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs index ab230f43..df9ce2b1 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/File.cs @@ -74,16 +74,14 @@ public sealed class File : FileSystemItem ErrorOr createPathResult = FileSystemPathId.Create(path); if (createPathResult.IsError) return createPathResult.Errors; - File newFile = new File( + File newFile = new( createPathResult.Value, name, dateCreated, dateModified, size); ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newFile; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; } /// @@ -107,16 +105,14 @@ public sealed class File : FileSystemItem FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - File newFile = new File( + File newFile = new( id, name, dateCreated, dateModified, size); ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newFile; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs index c192b8a4..8054bbbc 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/UnixRootItem.cs @@ -23,10 +23,7 @@ public sealed class UnixRootItem : FileSystemItem /// /// Gets the collection of file system items that are children to the current file system root entity. /// - public IReadOnlyCollection Items - { - get { return _items.AsReadOnly(); } - } + public IReadOnlyCollection Items => _items.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -54,13 +51,11 @@ public sealed class UnixRootItem : FileSystemItem ErrorOr createPathResult = FileSystemPathId.Create(PATH); if (createPathResult.IsError) return createPathResult.Errors; - UnixRootItem newRoot = new UnixRootItem( + UnixRootItem newRoot = new( createPathResult.Value, PATH); ErrorOr setStatusResult = newRoot.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newRoot; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newRoot; } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs index a2475ec8..2dbdc9cf 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Entities/WindowsRootItem.cs @@ -22,10 +22,7 @@ public sealed class WindowsRootItem : FileSystemItem /// /// Gets the collection of file system items that are children to the current file system root entity. /// - public IReadOnlyCollection Items - { - get { return _items.AsReadOnly(); } - } + public IReadOnlyCollection Items => _items.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -35,7 +32,7 @@ public sealed class WindowsRootItem : FileSystemItem /// The unique identifier of the root item in the file system path. /// The name of the root item. private WindowsRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root) - { + { } #endregion @@ -58,13 +55,11 @@ public sealed class WindowsRootItem : FileSystemItem ErrorOr createPathResult = FileSystemPathId.Create(path); if (createPathResult.IsError) return createPathResult.Errors; - WindowsRootItem newRoot = new WindowsRootItem( + WindowsRootItem newRoot = new( createPathResult.Value, name); ErrorOr setStatusResult = newRoot.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newRoot; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newRoot; } /// @@ -82,13 +77,11 @@ public sealed class WindowsRootItem : FileSystemItem FileSystemItemStatus status = FileSystemItemStatus.Accessible) { // TODO: enforce invariants - WindowsRootItem newFile = new WindowsRootItem( + WindowsRootItem newFile = new( id, name); ErrorOr setStatusResult = newFile.SetStatus(status); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return newFile; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : (ErrorOr)newFile; } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs index 30c470dc..0d08904d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs @@ -44,12 +44,12 @@ internal class DirectoryProviderService : IDirectoryProviderService public ErrorOr> GetSubdirectoryPaths(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false)) - return Errors.Permission.UnauthorizedAccess; - return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path) + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path) .OrderBy(path => path) .Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar) - .Select(path => FileSystemPathId.Create(path)) + .Select(FileSystemPathId.Create) .Where(errorOrPathId => !errorOrPathId.IsError) .Select(errorOrPathId => errorOrPathId.Value) .AsEnumerable()); @@ -85,9 +85,9 @@ internal class DirectoryProviderService : IDirectoryProviderService public ErrorOr> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) - return Errors.Permission.UnauthorizedAccess; - return Optional.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : (ErrorOr>)Optional.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); } /// @@ -98,9 +98,9 @@ internal class DirectoryProviderService : IDirectoryProviderService public ErrorOr> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false)) - return Errors.Permission.UnauthorizedAccess; - return Optional.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : (ErrorOr>)Optional.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); } /// @@ -270,7 +270,7 @@ internal class DirectoryProviderService : IDirectoryProviderService string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); if (!string.IsNullOrEmpty(newDirectory)) { - var newDirectoryPathResult = FileSystemPathId.Create(newDirectory); + ErrorOr newDirectoryPathResult = FileSystemPathId.Create(newDirectory); if (newDirectoryPathResult.IsError) return newDirectoryPathResult.Errors; if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false)) diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs index d942fba7..472e291c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs @@ -45,9 +45,7 @@ public class DirectoryService : IDirectoryService public ErrorOr> GetSubdirectories(string path) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return GetSubdirectories(fileSystemPathIdResult.Value); + return fileSystemPathIdResult.IsError ? (ErrorOr>)fileSystemPathIdResult.Errors : GetSubdirectories(fileSystemPathIdResult.Value); } /// @@ -84,9 +82,9 @@ public class DirectoryService : IDirectoryService if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorDirResult = Directory.Create(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); - if(errorDirResult.IsError) + if (errorDirResult.IsError) return errorDirResult.Errors; ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); if (setStatusResult.IsError) @@ -113,9 +111,7 @@ public class DirectoryService : IDirectoryService public ErrorOr CreateDirectory(string path, string name) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return CreateDirectory(fileSystemPathIdResult.Value, name); + return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : CreateDirectory(fileSystemPathIdResult.Value, name); } /// @@ -148,14 +144,12 @@ public class DirectoryService : IDirectoryService if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); if (errorDirResult.IsError) return errorDirResult.Errors; ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return errorDirResult; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : errorDirResult; } else return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); @@ -180,9 +174,9 @@ public class DirectoryService : IDirectoryService if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - if (fileSystemDestinationPathIdResult.IsError) - return fileSystemDestinationPathIdResult.Errors; - return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return fileSystemDestinationPathIdResult.IsError + ? (ErrorOr)fileSystemDestinationPathIdResult.Errors + : CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -226,9 +220,9 @@ public class DirectoryService : IDirectoryService if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); - if (fileSystemDestinationPathIdResult.IsError) - return fileSystemDestinationPathIdResult.Errors; - return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return fileSystemDestinationPathIdResult.IsError + ? (ErrorOr)fileSystemDestinationPathIdResult.Errors + : MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -263,9 +257,7 @@ public class DirectoryService : IDirectoryService public ErrorOr RenameDirectory(string path, string name) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return RenameDirectory(fileSystemPathIdResult.Value, name); + return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : RenameDirectory(fileSystemPathIdResult.Value, name); } /// @@ -298,14 +290,12 @@ public class DirectoryService : IDirectoryService if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None()); if (errorDirResult.IsError) return errorDirResult.Errors; ErrorOr setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return errorDirResult; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : errorDirResult; } else return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value); @@ -320,9 +310,7 @@ public class DirectoryService : IDirectoryService public ErrorOr DeleteDirectory(string path) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return DeleteDirectory(fileSystemPathIdResult.Value); + return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : DeleteDirectory(fileSystemPathIdResult.Value); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs index 3e998e43..dc66ad92 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DriveService.cs @@ -41,10 +41,8 @@ public class DriveService : IDriveService { if (_platformContext.Platform == PlatformType.Unix) { - var unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); - if (unixRootResult.IsError) - return unixRootResult.Errors; - return new List() { unixRootResult.Value }; + ErrorOr unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible); + return unixRootResult.IsError ? (ErrorOr>)unixRootResult.Errors : (ErrorOr>)new List() { unixRootResult.Value }; } else return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives() @@ -53,7 +51,7 @@ public class DriveService : IDriveService .Select(driveInfo => { ErrorOr root; - var windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name); + ErrorOr windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name); if (windowsRootResult.IsError) return windowsRootResult.Errors; else diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs index e5a6e068..3f5f0182 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs @@ -44,11 +44,11 @@ internal class FileProviderService : IFileProviderService public ErrorOr> GetFilePaths(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory)) - return Errors.Permission.UnauthorizedAccess; - return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path) + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path) .OrderBy(p => p) - .Select(p => FileSystemPathId.Create(p)) + .Select(FileSystemPathId.Create) .Where(errorOrPathId => !errorOrPathId.IsError) .Select(errorOrPathId => errorOrPathId.Value) .AsEnumerable()); @@ -82,9 +82,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr GetFileAsync(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) - return Errors.Permission.UnauthorizedAccess; - return System.IO.File.ReadAllBytes(path.Path); + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents) + ? (ErrorOr)Errors.Permission.UnauthorizedAccess + : (ErrorOr)System.IO.File.ReadAllBytes(path.Path); } /// @@ -95,9 +95,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr> GetLastWriteTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) - return Errors.Permission.UnauthorizedAccess; - return Optional.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : (ErrorOr>)Optional.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); } /// @@ -108,9 +108,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr> GetCreationTime(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) - return Errors.Permission.UnauthorizedAccess; - return Optional.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) + ? (ErrorOr>)Errors.Permission.UnauthorizedAccess + : (ErrorOr>)Optional.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); } /// @@ -121,9 +121,9 @@ internal class FileProviderService : IFileProviderService public ErrorOr GetSize(FileSystemPathId path) { // check if the user has access permissions to the provided path - if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties)) - return Errors.Permission.UnauthorizedAccess; - return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0; + return !_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties) + ? (ErrorOr)Errors.Permission.UnauthorizedAccess + : (ErrorOr)(_fileSystem.FileInfo.New(path.Path)?.Length ?? 0); } /// @@ -233,7 +233,7 @@ internal class FileProviderService : IFileProviderService string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name); if (!string.IsNullOrEmpty(newFile)) { - var newFilePathResult = FileSystemPathId.Create(newFile); + ErrorOr newFilePathResult = FileSystemPathId.Create(newFile); if (newFilePathResult.IsError) return newFilePathResult.Errors; // check if the user has access permissions to the provided path diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs index abd1d105..24670a41 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs @@ -44,10 +44,8 @@ public class FileService : IFileService /// An containing either a collection of files or an error. public ErrorOr> GetFiles(string path) { - var fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return GetFiles(fileSystemPathIdResult.Value); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + return fileSystemPathIdResult.IsError ? (ErrorOr>)fileSystemPathIdResult.Errors : GetFiles(fileSystemPathIdResult.Value); } /// @@ -71,7 +69,7 @@ public class FileService : IFileService ErrorOr> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path); if (filePathsResult.IsError) return filePathsResult.Errors; - List result = new(); + List result = []; IEnumerable filePaths = filePathsResult.Value; foreach (FileSystemPathId filePath in filePaths) { @@ -85,7 +83,7 @@ public class FileService : IFileService if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorFileResult = File.Create(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); if (errorFileResult.IsError) return errorFileResult.Errors; @@ -96,7 +94,7 @@ public class FileService : IFileService } else { - var fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); + ErrorOr fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); if (fileResult.IsError) return fileResult.Errors; result.Add(fileResult.Value); @@ -117,13 +115,13 @@ public class FileService : IFileService // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; - var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; - var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - if (fileSystemDestinationPathIdResult.IsError) - return fileSystemDestinationPathIdResult.Errors; - return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + return fileSystemDestinationPathIdResult.IsError + ? (ErrorOr)fileSystemDestinationPathIdResult.Errors + : CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -135,7 +133,7 @@ public class FileService : IFileService /// An containing either the copied file, or an error. public ErrorOr CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { - var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == false) @@ -155,14 +153,12 @@ public class FileService : IFileService if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return errorFileResult; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : errorFileResult; } else return File.Create(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); @@ -181,13 +177,13 @@ public class FileService : IFileService // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; - var fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); + ErrorOr fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); if (fileSystemSourcePathIdResult.IsError) return fileSystemSourcePathIdResult.Errors; - var fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); - if (fileSystemDestinationPathIdResult.IsError) - return fileSystemDestinationPathIdResult.Errors; - return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + ErrorOr fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); + return fileSystemDestinationPathIdResult.IsError + ? (ErrorOr)fileSystemDestinationPathIdResult.Errors + : MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); } /// @@ -199,7 +195,7 @@ public class FileService : IFileService /// An containing either the moved file, or an error. public ErrorOr MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) { - var fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); + ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == false) @@ -219,14 +215,12 @@ public class FileService : IFileService if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return errorFileResult; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : errorFileResult; } else return File.Create(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); @@ -241,10 +235,8 @@ public class FileService : IFileService /// An containing either the renamed file, or an error. public ErrorOr RenameFile(string path, string name) { - var fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return RenameFile(fileSystemPathIdResult.Value, name); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : RenameFile(fileSystemPathIdResult.Value, name); } /// @@ -256,10 +248,10 @@ public class FileService : IFileService public ErrorOr RenameFile(FileSystemPathId path, string name) { // first, check if the directory about to be created does not already exist - var combinedPath = _platformContext.PathStrategy.CombinePath(path, name); + ErrorOr combinedPath = _platformContext.PathStrategy.CombinePath(path, name); if (combinedPath.IsError) return combinedPath.Errors; - var fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); + ErrorOr fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value); if (fileExists.IsError) return fileExists.Errors; else if (fileExists.Value == true) @@ -279,14 +271,12 @@ public class FileService : IFileService if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { ErrorOr errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!, - !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), + !dateCreatedResult.IsError ? dateCreatedResult.Value : Optional.None(), !dateModifiedResult.IsError ? dateModifiedResult.Value : Optional.None(), size); if (errorFileResult.IsError) return errorFileResult.Errors; ErrorOr setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible); - if (setStatusResult.IsError) - return setStatusResult.Errors; - return errorFileResult; + return setStatusResult.IsError ? (ErrorOr)setStatusResult.Errors : errorFileResult; } else return File.Create(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size); @@ -300,10 +290,8 @@ public class FileService : IFileService /// An containing either the result of deleting a file, or an error. public ErrorOr DeleteFile(string path) { - var fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return DeleteFile(fileSystemPathIdResult.Value); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + return fileSystemPathIdResult.IsError ? (ErrorOr)fileSystemPathIdResult.Errors : DeleteFile(fileSystemPathIdResult.Value); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs index 8f2451a5..820b7943 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs @@ -29,7 +29,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService /// Injected facade service for platform contextual services. public FileSystemPermissionsService(IPlatformContextManager platformContextManager) { - _platformContextManager = platformContextManager; + _platformContextManager = platformContextManager; } #endregion @@ -85,7 +85,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService modes = AccessModes.F_OK; // check existence, not an exact match but the closest break; case FileAccessMode.Delete: - if (fileInfo.FileType == FileTypes.Directory) + if (fileInfo.FileType == FileTypes.Directory) return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself else { @@ -147,7 +147,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService _ = fileSystemInfo.CreationTime; // trigger potential access denial break; case FileAccessMode.ReadContents: - using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) stream.Close(); break; } @@ -203,7 +203,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService } } - catch + catch { return false; } diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs index a4e36bc6..249643bf 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs @@ -60,7 +60,7 @@ public class FileTypeService : IFileTypeService if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) return Errors.Permission.UnauthorizedAccess; Memory buffer = new byte[BUFFER_SIZE]; - using var stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); + using FileSystemStream stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); // check if the file's length is less than the buffer size if (stream.Length < BUFFER_SIZE) return ImageType.None; @@ -73,12 +73,9 @@ public class FileTypeService : IFileTypeService return type; // no known image header types were found, check other methods string content = Encoding.UTF8.GetString(buffer.ToArray()); - if (IsSvg(content, path.Path)) - return ImageType.SVG; - else if (IsTga(buffer.ToArray())) - return ImageType.TGA; - else - return ImageType.None; + return IsSvg(content, path.Path) + ? (ErrorOr)ImageType.SVG + : IsTga(buffer.ToArray()) ? (ErrorOr)ImageType.TGA : (ErrorOr)ImageType.None; } /// @@ -96,7 +93,7 @@ public class FileTypeService : IFileTypeService if (initialContent.StartsWith(" diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs index a66289d6..1e258251 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using System; using System.Collections.Generic; #endregion diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs index 58765b81..39dfd506 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs @@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S /// /// Interface for the service for handling thumbnails. /// -public interface IThumbnailService +public interface IThumbnailService { #region ===================================================================== METHODS =================================================================================== /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs index df583aff..cb017401 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs @@ -20,10 +20,7 @@ public class PathService : IPathService /// /// Gets the character used to separate path segments. /// - public char PathSeparator - { - get { return _platformContext.PathStrategy.PathSeparator; } - } + public char PathSeparator => _platformContext.PathStrategy.PathSeparator; #endregion #region ====================================================================== CTOR ===================================================================================== @@ -46,9 +43,7 @@ public class PathService : IPathService public bool IsValidPath(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) - return false; - return _platformContext.PathStrategy.IsValidPath(newPathResult.Value); + return !newPathResult.IsError && _platformContext.PathStrategy.IsValidPath(newPathResult.Value); } /// @@ -59,9 +54,7 @@ public class PathService : IPathService public bool Exists(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) - return false; - return _platformContext.PathStrategy.Exists(newPathResult.Value); + return !newPathResult.IsError && _platformContext.PathStrategy.Exists(newPathResult.Value); } /// @@ -76,9 +69,7 @@ public class PathService : IPathService if (newPathResult.IsError) return newPathResult.Errors; ErrorOr combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name); - if (combinedPathResult.IsError) - return combinedPathResult.Errors; - return combinedPathResult.Value.Path; + return combinedPathResult.IsError ? (ErrorOr)combinedPathResult.Errors : (ErrorOr)combinedPathResult.Value.Path; } /// @@ -89,9 +80,7 @@ public class PathService : IPathService public ErrorOr> ParsePath(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) - return newPathResult.Errors; - return _platformContext.PathStrategy.ParsePath(newPathResult.Value); + return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : _platformContext.PathStrategy.ParsePath(newPathResult.Value); } /// @@ -102,9 +91,7 @@ public class PathService : IPathService public ErrorOr> GoUpOneLevel(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) - return newPathResult.Errors; - return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); + return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value); } /// @@ -124,9 +111,7 @@ public class PathService : IPathService public ErrorOr GetPathRoot(string path) { ErrorOr newPathResult = FileSystemPathId.Create(path); - if (newPathResult.IsError) - return newPathResult.Errors; - return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); + return newPathResult.IsError ? (ErrorOr)newPathResult.Errors : _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs index 9bfb310b..bfacbd7c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs @@ -44,10 +44,10 @@ public class ThumbnailService : IThumbnailService /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. public async Task> GetThumbnailAsync(string path, int quality) { - var fileSystemPathIdResult = FileSystemPathId.Create(path); - if (fileSystemPathIdResult.IsError) - return fileSystemPathIdResult.Errors; - return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + return fileSystemPathIdResult.IsError + ? (ErrorOr)fileSystemPathIdResult.Errors + : await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); } /// @@ -59,21 +59,21 @@ public class ThumbnailService : IThumbnailService public async Task> GetThumbnailAsync(FileSystemPathId path, int quality) { // first, get the type of the image file - var imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path); + ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path); if (imageTypeResult.IsError) return imageTypeResult.Errors; if (imageTypeResult.Value != ImageType.None) { // then, get its bytes - var resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); + ErrorOr resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); if (resultFileContents.IsError) return resultFileContents.Errors; byte[] fileContents = resultFileContents.Value; // finally, resize or adjust quality based on image type byte[]? adjustedImage = null; - if (imageTypeResult.Value == ImageType.JPEG || imageTypeResult.Value == ImageType.JPEG_CANON || imageTypeResult.Value == ImageType.JPEG2000 - || imageTypeResult.Value == ImageType.JPEG_UNKNOWN || imageTypeResult.Value == ImageType.PNG || imageTypeResult.Value == ImageType.BMP - || imageTypeResult.Value == ImageType.WEBP || imageTypeResult.Value == ImageType.GIF || imageTypeResult.Value == ImageType.TIFF || imageTypeResult.Value == ImageType.TGA) + if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000 + or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP + or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA) adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality); return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); } @@ -90,8 +90,8 @@ public class ThumbnailService : IThumbnailService /// A byte array representing the processed image. private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality) { - using var inputMemoryStream = new MemoryStream(imageBytes); - using var outputMemoryStream = new MemoryStream(); + using MemoryStream inputMemoryStream = new(imageBytes); + using MemoryStream outputMemoryStream = new(); switch (imageType) { case ImageType.JPEG: @@ -99,22 +99,23 @@ public class ThumbnailService : IThumbnailService case ImageType.JPEG_CANON: case ImageType.JPEG_UNKNOWN: { - using var image = await Image.LoadAsync(inputMemoryStream); + using Image image = await Image.LoadAsync(inputMemoryStream); await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }); break; } case ImageType.PNG: { - using var image = await Image.LoadAsync(inputMemoryStream); + using Image image = await Image.LoadAsync(inputMemoryStream); // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression int compressionLevel = MapRange(quality, 1, 100, 1, 9); - var encoder = new PngEncoder { CompressionLevel = (PngCompressionLevel)compressionLevel }; + PngEncoder encoder = new() + { CompressionLevel = (PngCompressionLevel)compressionLevel }; await image.SaveAsync(outputMemoryStream, encoder); break; } case ImageType.BMP: { - using var image = await Image.LoadAsync(inputMemoryStream); + using Image image = await Image.LoadAsync(inputMemoryStream); await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression break; } @@ -133,8 +134,8 @@ public class ThumbnailService : IThumbnailService /// The bytes of the adjusted image. private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality) { - using var inputMemoryStream = new MemoryStream(imageBytes); - using var outputMemoryStream = new MemoryStream(); + using MemoryStream inputMemoryStream = new(imageBytes); + using MemoryStream outputMemoryStream = new(); Image image = await Image.LoadAsync(inputMemoryStream); double ratio = quality / 100.0; int newWidth = (int)(image.Width * ratio); @@ -142,7 +143,7 @@ public class ThumbnailService : IThumbnailService // ensure new dimensions are not zero newWidth = Math.Max(1, newWidth); newHeight = Math.Max(1, newHeight); - var options = new ResizeOptions + ResizeOptions options = new() { Size = new Size(newWidth, newHeight), Mode = ResizeMode.Max @@ -166,7 +167,7 @@ public class ThumbnailService : IThumbnailService break; default: return imageBytes; // for unsupported formats, just return the original bytes - } + } return outputMemoryStream.ToArray(); } @@ -183,7 +184,7 @@ public class ThumbnailService : IThumbnailService /// private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget) { - return (value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource) + fromTarget; + return ((value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource)) + fromTarget; } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs index 12114b94..fe6568cc 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/EnvironmentContext.cs @@ -1,5 +1,4 @@ using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs index 8e0dae20..42eb1168 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Environment/IEnvironmentContext.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; #endregion namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 8fd35fd5..187d5856 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -21,10 +21,7 @@ public class UnixPathStrategy : IUnixPathStrategy #endregion #region ==================================================================== PROPERTIES ================================================================================= - public char PathSeparator - { - get { return '/'; } - } + public char PathSeparator => '/'; #endregion #region ====================================================================== CTOR ===================================================================================== @@ -47,13 +44,13 @@ public class UnixPathStrategy : IUnixPathStrategy public bool IsValidPath(FileSystemPathId path) { // check for invalid path characters - var invalidChars = GetInvalidPathCharsForPlatform(); + char[] invalidChars = GetInvalidPathCharsForPlatform(); if (path.Path.IndexOfAny(invalidChars) >= 0) return false; // check for relative paths if (path.Path.StartsWith("./") || path.Path.StartsWith("../")) return false; - var pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$"; + string pathPattern = @"^\/([\w\-\.\~!$&'()*+,;=:@ ]+(\/[\w\-\.\~!$&'()*+,;=:@ ]+)*)?\/?$"; return Regex.IsMatch(path.Path, pathPattern); } @@ -124,15 +121,13 @@ public class UnixPathStrategy : IUnixPathStrategy if (tempPath.EndsWith('/')) tempPath = tempPath.TrimEnd(PathSeparator); // find the last occurrence of a slash - var lastIndex = tempPath.LastIndexOf(PathSeparator); + int lastIndex = tempPath.LastIndexOf(PathSeparator); // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error if (lastIndex < 0) return Errors.FileManagement.CannotNavigateUp; // return the path up to the last slash, or, if there's only the root slash, return that one instead ErrorOr newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); - if (newPathResult.IsError) - return newPathResult.Errors; - return ParsePath(newPathResult.Value); + return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : ParsePath(newPathResult.Value); } /// @@ -155,9 +150,9 @@ public class UnixPathStrategy : IUnixPathStrategy return Errors.FileManagement.InvalidPath; // On Unix-like systems, the root is always "/" - if (path.Path.StartsWith(PathSeparator)) - return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true); - return Errors.FileManagement.InvalidPath; + return path.Path.StartsWith(PathSeparator) + ? (ErrorOr)new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true) + : (ErrorOr)Errors.FileManagement.InvalidPath; } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index ece8a564..e6237684 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using System; using ErrorOr; -using System.Collections.Generic; using Lumina.Domain.Common.Errors; -using System.Text.RegularExpressions; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using System.Linq; +using System; +using System.Collections.Generic; using System.IO.Abstractions; +using System.Linq; +using System.Text.RegularExpressions; #endregion namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; @@ -21,10 +21,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy #endregion #region ==================================================================== PROPERTIES ================================================================================= - public char PathSeparator - { - get { return '\\'; } - } + public char PathSeparator => '\\'; #endregion #region ====================================================================== CTOR ===================================================================================== @@ -47,12 +44,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy public bool IsValidPath(FileSystemPathId path) { // check for invalid path characters - var invalidChars = GetInvalidPathCharsForPlatform(); + char[] invalidChars = GetInvalidPathCharsForPlatform(); if (path.Path.IndexOfAny(invalidChars) >= 0) return false; // regular expression to match valid absolute paths // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) - var pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$"; + string pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$"; return Regex.IsMatch(path.Path, pathPattern); } @@ -92,18 +89,18 @@ public class WindowsPathStrategy : IWindowsPathStrategy public ErrorOr> ParsePath(FileSystemPathId path) { // Windows paths usually start with a drive letter and colon, e.g., "C:" - if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator) - return Errors.FileManagement.InvalidPath; - return ErrorOrFactory.From(GetPathSegments()); + return !path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator + ? (ErrorOr>)Errors.FileManagement.InvalidPath + : ErrorOrFactory.From(GetPathSegments()); IEnumerable GetPathSegments() { // the drive segment yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true); // extract the other segments - var segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); - for (var i = 0; i < segments.Length; i++) + string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < segments.Length; i++) { - var segment = segments[i]; + string segment = segments[i]; bool isDirectory; if (segment.Contains('.')) isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter @@ -132,15 +129,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy if (tempPath.EndsWith('\\')) tempPath = tempPath.TrimEnd(PathSeparator); // find the last occurrence of a slash - var lastIndex = tempPath.LastIndexOf(PathSeparator); + int lastIndex = tempPath.LastIndexOf(PathSeparator); // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error if (lastIndex < 0) return Errors.FileManagement.CannotNavigateUp; // if we are at the drive root level after trimming, return drive root, otherwise, return the path up to the last slash ErrorOr newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]); - if (newPathResult.IsError) - return newPathResult.Errors; - return ParsePath(newPathResult.Value); + return newPathResult.IsError ? (ErrorOr>)newPathResult.Errors : ParsePath(newPathResult.Value); } /// @@ -172,11 +167,11 @@ public class WindowsPathStrategy : IWindowsPathStrategy // check for UNC paths (e.g., "\\server\share") if (path.Path.StartsWith('\\')) { - var parseResult = ParsePath(path); + ErrorOr> parseResult = ParsePath(path); if (parseResult.IsError) return parseResult.Errors; - var segments = parseResult.Value.ToList(); + List segments = parseResult.Value.ToList(); if (segments.Count >= 2) { string root = $@"\\{segments[0].Name}\{segments[1].Name}\"; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs index b8193c2b..38ccb4cd 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs @@ -15,7 +15,7 @@ public class WindowsPlatformContext : IWindowsPlatformContext /// Gets the platform type, which is Windows for this context. /// public PlatformType Platform { get; } = PlatformType.Windows; - + /// /// Gets the path strategy for Windows platforms. /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs index 94ccc366..0b418a1d 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemPathId.cs @@ -48,9 +48,7 @@ public sealed class FileSystemPathId : ValueObject /// public static ErrorOr Create(string path) { - if (string.IsNullOrWhiteSpace(path)) - return Errors.FileManagement.InvalidPath; - return new FileSystemPathId(path); + return string.IsNullOrWhiteSpace(path) ? (ErrorOr)Errors.FileManagement.InvalidPath : (ErrorOr)new FileSystemPathId(path); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs index 282e7e8e..c4aa295f 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/StreamInfo.cs @@ -20,37 +20,37 @@ public class StreamInfo : ValueObject /// Gets the id of the stream. /// public string StreamId { get; } - + /// /// Gets the MimeType of the stream. /// public string MimeType { get; } - + /// /// Gets the bitrate of the stream. /// public int Bitrate { get; } - + /// /// Gets the codec of the stream. /// public string Codec { get; } - + /// /// Gets the optional resolution of the stream. /// public Optional Resolution { get; } - + /// /// Gets the optional frame rate of the stream. /// public Optional FrameRate { get; } - + /// /// Gets the optional sample rate of the stream. /// public Optional SampleRate { get; } - + /// /// Gets the optional channels of the stream. /// @@ -70,13 +70,13 @@ public class StreamInfo : ValueObject /// The sample rate of the stream (for audio). /// The number of channels (for audio). private StreamInfo( - string streamId, - string mimeType, - int bitrate, + string streamId, + string mimeType, + int bitrate, string codec, - Optional resolution, + Optional resolution, Optional frameRate, - Optional sampleRate, + Optional sampleRate, Optional channels) { StreamId = streamId; @@ -106,24 +106,24 @@ public class StreamInfo : ValueObject /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( - string streamId, - string mimeType, - int bitrate, + string streamId, + string mimeType, + int bitrate, string codec, - Optional resolution, - Optional frameRate, - Optional sampleRate, + Optional resolution, + Optional frameRate, + Optional sampleRate, Optional channels) { - if (streamId is null) - return Errors.FileManagement.StreamIdCannotBeEmpty; - if (codec is null) - return Errors.FileManagement.CodecCannotBeEmpty; - if (bitrate <= 0) - return Errors.FileManagement.BitrateMustBeAPositiveNumber; - return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); + return streamId is null + ? (ErrorOr)Errors.FileManagement.StreamIdCannotBeEmpty + : codec is null + ? (ErrorOr)Errors.FileManagement.CodecCannotBeEmpty + : bitrate <= 0 + ? (ErrorOr)Errors.FileManagement.BitrateMustBeAPositiveNumber + : (ErrorOr)new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); } - + /// public override IEnumerable GetEqualityComponents() { diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs index 64345de3..48490e0a 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs +++ b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/MediaContributor.cs @@ -53,10 +53,10 @@ public class MediaContributor : AggregateRoot /// The optional date of birth of the contributor. /// The optional date of death of the contributor. private MediaContributor( - MediaContributorId id, - MediaContributorName name, - MediaContributorRole role, - Optional dateOfBirth, + MediaContributorId id, + MediaContributorName name, + MediaContributorRole role, + Optional dateOfBirth, Optional dateOfDeath) { Id = id; @@ -87,10 +87,10 @@ public class MediaContributor : AggregateRoot /// The name of the contributor. /// The created instance. public static ErrorOr Create( - MediaContributorId id, - MediaContributorName name, - MediaContributorRole role, - Optional dateOfBirth, + MediaContributorId id, + MediaContributorName name, + MediaContributorRole role, + Optional dateOfBirth, Optional dateOfDeath) { return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath); diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs index f4e126d7..1e0ae8e0 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs +++ b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/ContributorName.cs @@ -49,7 +49,7 @@ public sealed class MediaContributorName : ValueObject public static ErrorOr Create(string displayName, Optional legalName) { // TODO: enforce invariants - return new MediaContributorName(displayName, legalName); + return new MediaContributorName(displayName, legalName); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs index b17c5585..ecf165f3 100644 --- a/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs +++ b/src/Lumina.Domain/Core/Aggregates/MediaContributor/MediaContributorAggregate/ValueObjects/MediaContributorId.cs @@ -29,7 +29,7 @@ public sealed class MediaContributorId : EntityId public static MediaContributorId CreateUnique() { // TODO: enforce invariants - return new MediaContributorId(Guid.NewGuid()); + return new MediaContributorId(Guid.NewGuid()); } /// @@ -40,7 +40,7 @@ public sealed class MediaContributorId : EntityId public static MediaContributorId Create(Guid value) { // TODO: enforce invariants - return new MediaContributorId(value); + return new MediaContributorId(value); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs index 0fd35d76..4cc0ca3c 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Movie.cs @@ -30,18 +30,12 @@ public sealed class Movie : Entity /// /// Gets the list of ratings for this movie. /// - public IReadOnlyCollection Ratings - { - get { return _ratings.AsReadOnly(); } - } + public IReadOnlyCollection Ratings => _ratings.AsReadOnly(); /// /// Gets the list of media contributors (actors, directors, etc) starring in this movie. /// - public IReadOnlyCollection Contributors - { - get { return _contributors.AsReadOnly(); } - } + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -66,7 +60,7 @@ public sealed class Movie : Entity /// private Movie() // only needed during reflection { - + } #pragma warning restore CS8618 #endregion diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs index 9b524a6f..4032ed89 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/Services/MovieLibraryService.cs @@ -14,9 +14,6 @@ public sealed class MovieLibraryService : IMovieLibraryService /// /// Gets the collection of movies in the library. /// - public ICollection Movies - { - get { throw new NotImplementedException(); } - } + public ICollection Movies => throw new NotImplementedException(); #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs index 9b80e714..52eb20d6 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/MovieId.cs @@ -12,7 +12,7 @@ namespace Lumina.Domain.Core.Aggregates.VideoLibrary.MovieLibraryAggregate.Value /// [DebuggerDisplay("{Value}")] public sealed class MovieId : EntityId -{ +{ #region ====================================================================== CTOR ===================================================================================== /// /// Initializes a new instance of the class. @@ -31,7 +31,7 @@ public sealed class MovieId : EntityId public static MovieId CreateUnique() { // TODO: enforce invariants - return new MovieId(Guid.NewGuid()); + return new MovieId(Guid.NewGuid()); } /// @@ -42,7 +42,7 @@ public sealed class MovieId : EntityId public static MovieId Create(Guid value) { // TODO: enforce invariants - return new MovieId(value); + return new MovieId(value); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs index 8c3ca07b..1970510e 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs @@ -60,18 +60,18 @@ public class VideoMetadata : BaseMetadata /// The genres of the video. /// The tags associated with the video. private VideoMetadata( - string title, - Optional originalTitle, - int durationInSeconds, - string resolution, + string title, + Optional originalTitle, + int durationInSeconds, + string resolution, Optional description, - ReleaseInfo releaseInfo, - Optional language, - Optional originalLanguage, - Optional frameRate, - Optional videoCodec, + ReleaseInfo releaseInfo, + Optional language, + Optional originalLanguage, + Optional frameRate, + Optional videoCodec, Optional audioCodec, - List genres, + List genres, List tags) : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { @@ -104,18 +104,18 @@ public class VideoMetadata : BaseMetadata /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( - string title, - Optional originalTitle, - int durationInSeconds, - string resolution, + string title, + Optional originalTitle, + int durationInSeconds, + string resolution, Optional description, - ReleaseInfo releaseInfo, - Optional language, - Optional originalLanguage, - Optional frameRate, - Optional videoCodec, + ReleaseInfo releaseInfo, + Optional language, + Optional originalLanguage, + Optional frameRate, + Optional videoCodec, Optional audioCodec, - List genres, + List genres, List tags) { return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo, @@ -125,7 +125,7 @@ public class VideoMetadata : BaseMetadata /// public override IEnumerable GetEqualityComponents() { - foreach (var component in base.GetEqualityComponents()) + foreach (object component in base.GetEqualityComponents()) yield return component; yield return DurationInSeconds; yield return Resolution; diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs index 700bfb79..373e9252 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Episode.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using System.Diagnostics; #endregion namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs index 84a93371..61053207 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Entities/Season.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using System.Diagnostics; #endregion namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.Entities; diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs index 595d7018..c6108585 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/Services/TvShowLibraryService.cs @@ -14,9 +14,6 @@ public class TvShowLibraryService : ITvShowLibraryService /// /// Gets the collection of TV shows in the library. /// - public ICollection TvShows - { - get { throw new NotImplementedException(); } - } + public ICollection TvShows => throw new NotImplementedException(); #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs index 19302372..747b4906 100644 --- a/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs +++ b/src/Lumina.Domain/Core/Aggregates/VideoLibrary/TvShowLibraryAggregate/TvShow.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate.ValueObjects; +using System.Diagnostics; #endregion namespace Lumina.Domain.Core.Aggregates.VideoLibrary.TvShowLibraryAggregate; diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs index d1588074..a4023107 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs @@ -99,26 +99,17 @@ public sealed class Book : AggregateRoot /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// - public IReadOnlyCollection ISBNs - { - get { return _isbns.AsReadOnly(); } - } + public IReadOnlyCollection ISBNs => _isbns.AsReadOnly(); /// /// Gets the list of media contributors (actors, directors, etc) starring in this book. /// - public IReadOnlyCollection Contributors - { - get { return _contributors.AsReadOnly(); } - } + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); /// /// Gets the list of ratings for this book. /// - public IReadOnlyCollection Ratings - { - get { return _ratings.AsReadOnly(); } - } + public IReadOnlyCollection Ratings => _ratings.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs index 1b8ca4c0..75e22dcc 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Entities/BookSeries.cs @@ -33,10 +33,7 @@ public sealed class BookSeries : Entity /// /// Gets the collection of books in the series. /// - public IReadOnlyCollection Books - { - get { return _books.AsReadOnly(); } - } + public IReadOnlyCollection Books => _books.AsReadOnly(); #endregion #region ====================================================================== CTOR ===================================================================================== @@ -69,9 +66,9 @@ public sealed class BookSeries : Entity /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( - BookSeriesId id, - WrittenContentMetadata metadata, - bool isComplete, + BookSeriesId id, + WrittenContentMetadata metadata, + bool isComplete, List books) { // TODO: enforce invariants diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs index 2a4fcc98..8f30c656 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/BookLibraryService.cs @@ -14,9 +14,6 @@ public sealed class BookLibraryService : IBookLibraryService /// /// Gets the collection of books in the library. /// - public ICollection Books - { - get { throw new NotImplementedException(); } - } + public ICollection Books => throw new NotImplementedException(); #endregion } \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs index d0299042..f27b296b 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Services/IBookLibraryService.cs @@ -14,7 +14,7 @@ public interface IBookLibraryService /// Gets the collection of books in the library. /// ICollection Books { get; } - + // ICollection Series { get; } #endregion diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs index b8eff9c4..6b54dc6f 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/BookRating.cs @@ -51,11 +51,9 @@ public class BookRating : Rating /// public static ErrorOr Create(decimal value, decimal maxValue, Optional source, Optional voteCount) { - if (maxValue < 0 || value < 0) - return Errors.Metadata.RatingValueMustBePositive; - if (value > maxValue) - return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue; - return new BookRating(value, maxValue, source, voteCount); + return maxValue < 0 || value < 0 + ? (ErrorOr)Errors.Metadata.RatingValueMustBePositive + : value > maxValue ? (ErrorOr)Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue : (ErrorOr)new BookRating(value, maxValue, source, voteCount); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs index b6c0ec80..e489b82f 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/WrittenContentMetadata.cs @@ -48,7 +48,7 @@ public class WrittenContentMetadata : BaseMetadata ReleaseInfo releaseInfo, List genres, List tags, - Optional language, + Optional language, Optional originalLanguage, Optional publisher, Optional pageCount) @@ -88,23 +88,23 @@ public class WrittenContentMetadata : BaseMetadata Optional publisher, Optional pageCount) { - if (string.IsNullOrWhiteSpace(title)) - return Errors.Metadata.TitleCannotBeEmpty; - if (releaseInfo is null) - return Errors.Metadata.ReleaseInfoCannotBeNull; - if (genres is null) - return Errors.Metadata.GenresListCannotBeNull; - if (tags is null) - return Errors.Metadata.TagsListCannotBeNull; - return new WrittenContentMetadata( - title, - originalTitle, - description, - releaseInfo, - genres, tags, - language, - originalLanguage, - publisher, + return string.IsNullOrWhiteSpace(title) + ? (ErrorOr)Errors.Metadata.TitleCannotBeEmpty + : releaseInfo is null + ? (ErrorOr)Errors.Metadata.ReleaseInfoCannotBeNull + : genres is null + ? (ErrorOr)Errors.Metadata.GenresListCannotBeNull + : tags is null + ? (ErrorOr)Errors.Metadata.TagsListCannotBeNull + : (ErrorOr)new WrittenContentMetadata( + title, + originalTitle, + description, + releaseInfo, + genres, tags, + language, + originalLanguage, + publisher, pageCount ); } @@ -112,7 +112,7 @@ public class WrittenContentMetadata : BaseMetadata /// public override IEnumerable GetEqualityComponents() { - foreach (var component in base.GetEqualityComponents()) + foreach (object component in base.GetEqualityComponents()) yield return component; yield return Publisher; yield return PageCount; diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 852c7da2..23a37f47 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -1,11 +1,11 @@ - - + net8.0 disable enable $(SolutionDir)..\bin\server\ false + true @@ -24,5 +24,4 @@ - diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 75aa6fc8..b087af26 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using System.Reflection; using FluentValidation; using Microsoft.Extensions.DependencyInjection; +using System.Reflection; #endregion namespace Lumina.Infrastructure.Common.DependencyInjection; diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index 1b2250f5..82df2fde 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -24,14 +24,14 @@ public static class SharedConfiguration /// Thrown when the base path where the configuration files should be located, does not exist. public static IServiceCollection BindSharedConfiguration(this IServiceCollection services, IConfigurationManager configuration) { - var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!Directory.Exists(basePath)) throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); configuration.SetBasePath(basePath); configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true); configuration.AddEnvironmentVariables(); // environment variables should override the configuration files - + // bind the common settings section services.AddOptions() .Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName)) @@ -42,7 +42,7 @@ public static class SharedConfiguration services.AddOptions() .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName)) .ValidateFluently() - .ValidateOnStart(); + .ValidateOnStart(); return services; } #endregion diff --git a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs index e7d828fd..a5c2f18e 100644 --- a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs @@ -52,15 +52,15 @@ public class FluentValidationOptions : IValidateOptions wher ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null - var validationResult = _validator.Validate(options); // validate the options using the validator + FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator // return a response based on the validation result if (validationResult.IsValid) return ValidateOptionsResult.Success; - + // if the validation fails, collect the error messages // TODO: add translation support for the error messages - var errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") + string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") .ToArray(); // and return them with a failure result diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 318a9632..90e66265 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -1,18 +1,17 @@ - - + net8.0 disable enable $(SolutionDir)..\bin\server\ false + true - @@ -35,5 +34,4 @@ - diff --git a/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs b/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs index b00573e2..8d29a56f 100644 --- a/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs +++ b/src/Lumina.Presentation.Api/Common/Configuration/ConfigureSwaggerOptions.cs @@ -36,8 +36,8 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions public void Configure(SwaggerGenOptions options) { // add swagger document for every API version discovered - foreach (var description in _provider.ApiVersionDescriptions) - options.SwaggerDoc(description.GroupName,CreateVersionInfo(description)); + foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions) + options.SwaggerDoc(description.GroupName, CreateVersionInfo(description)); } /// @@ -57,7 +57,7 @@ public class ConfigureSwaggerOptions : IConfigureNamedOptions /// The created instance. private OpenApiInfo CreateVersionInfo(ApiVersionDescription description) { - var info = new OpenApiInfo() + OpenApiInfo info = new() { Title = "Lumina API", Version = description.ApiVersion.ToString() diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs index 2166147e..5c04e7d6 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs @@ -22,7 +22,7 @@ internal static class PresentationApiLayerConfiguration /// Thrown when the base path where the configuration files should be located, does not exist. public static IServiceCollection BindPresentationApiLayerConfiguration(this IServiceCollection services, IConfigurationManager configuration) { - var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!Directory.Exists(basePath)) throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); configuration.SetBasePath(basePath); diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 657d5a21..ea78865b 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -25,14 +25,11 @@ public static class PresentationApiLayerServices /// The updated . public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) { - services.AddCors(options => - { - options.AddPolicy("AllowAll", + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder .AllowAnyOrigin() .AllowAnyMethod() - .AllowAnyHeader()); - }); + .AllowAnyHeader())); // add services to the container services.AddControllers().AddJsonOptions(options => @@ -45,7 +42,7 @@ public static class PresentationApiLayerServices services.AddEndpointsApiExplorer(); services.AddSwaggerGen(); services.ConfigureOptions(); - + services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); @@ -62,7 +59,7 @@ public static class PresentationApiLayerServices services.AddSingleton(); // register mapster configs - var mapsterConfig = TypeAdapterConfig.GlobalSettings; + TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings; mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly); services.AddSingleton(mapsterConfig); services.AddScoped(); diff --git a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs index cc2189e9..ed715fb9 100644 --- a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs +++ b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs @@ -53,7 +53,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory string? detail = null, string? instance = null) { statusCode ??= 500; - var problemDetails = new ProblemDetails + ProblemDetails problemDetails = new() { Status = statusCode, Title = title, @@ -81,7 +81,7 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory { ArgumentNullException.ThrowIfNull(modelStateDictionary); statusCode ??= 400; - var problemDetails = new ValidationProblemDetails(modelStateDictionary) + ValidationProblemDetails problemDetails = new(modelStateDictionary) { Status = statusCode, Type = type, @@ -104,23 +104,20 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode) { problemDetails.Status ??= statusCode; - if (_options.ClientErrorMapping.TryGetValue(statusCode, out var clientErrorData)) + if (_options.ClientErrorMapping.TryGetValue(statusCode, out ClientErrorData? clientErrorData)) { problemDetails.Title ??= clientErrorData.Title; problemDetails.Type ??= clientErrorData.Link; } - var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier; + string? traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier; if (traceId != null) problemDetails.Extensions["traceId"] = traceId; // get any errors that might be sent by ApiController base class' Problem() method - var errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List; + List? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List; // add any extra custom properties if (errors is not null) { - problemDetails.Extensions.Add("errors", errors.Select(error => - { - return error.Code; - })); + problemDetails.Extensions.Add("errors", errors.Select(error => error.Code)); } //problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString())); _configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails }); diff --git a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs b/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs index de4ab200..b3065f1d 100644 --- a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs +++ b/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs @@ -23,7 +23,7 @@ public class UrlStringBinder : IModelBinder throw new ArgumentNullException(nameof(bindingContext)); string modelName = bindingContext.ModelName; // try to fetch the value of the argument by name - var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); + ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); if (valueProviderResult == ValueProviderResult.None) return Task.CompletedTask; string? value = valueProviderResult.FirstValue; diff --git a/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs index 487fd5e9..17615fa5 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/Common/ApiController.cs @@ -43,7 +43,7 @@ public abstract class ApiController : ControllerBase /// The error to convert. protected internal IActionResult Problem(Error error) { - var statusCode = error.Type switch + int statusCode = error.Type switch { ErrorType.Conflict => StatusCodes.Status409Conflict, ErrorType.NotFound => StatusCodes.Status404NotFound, @@ -62,8 +62,8 @@ public abstract class ApiController : ControllerBase /// The list of errors to convert. protected internal IActionResult ValidationProblem(List errors) { - var modelStateDictionary = new ModelStateDictionary(); - foreach (var error in errors) + ModelStateDictionary modelStateDictionary = new(); + foreach (Error error in errors) modelStateDictionary.AddModelError(error.Code, error.Description); return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred."); } diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs index 90a73504..167b6b2e 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs @@ -49,7 +49,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (var treeNode in result.Value) + foreach (FileSystemTreeNodeResponse treeNode in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; @@ -69,7 +69,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (var directory in result.Value) + foreach (FileSystemTreeNodeResponse directory in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; @@ -89,7 +89,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (var directory in result.Value) + foreach (DirectoryResponse directory in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs index af92c7b6..fc3551c3 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DrivesController.cs @@ -43,7 +43,7 @@ public class DrivesController : ApiController public async Task GetDrives(CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + return result.Match(Ok, Problem); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs index 541afa9e..b8eb2a8a 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs @@ -1,5 +1,6 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem; +using Lumina.Contracts.Responses.FileManagement; using Lumina.Presentation.Api.Core.Controllers.Common; using Mediator; using Microsoft.AspNetCore.Mvc; @@ -39,8 +40,8 @@ public class FileSystemController : ApiController [HttpGet("get-type")] public async Task GetType(CancellationToken cancellationToken) { - var platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); + FileSystemTypeResponse platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false); return Ok(platformType); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs index 9743f703..73a02faf 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs @@ -47,7 +47,7 @@ public class FilesController : ApiController public async IAsyncEnumerable GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path), cancellationToken).ConfigureAwait(false); - foreach (var file in result.Value) + foreach (FileSystemTreeNodeResponse file in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; @@ -66,7 +66,7 @@ public class FilesController : ApiController ErrorOr> result = await _mediator.Send(new GetFilesQuery(path), cancellationToken).ConfigureAwait(false); if (!result.IsError) { - foreach (var file in result.Value) + foreach (FileResponse file in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs index 0e64494a..ee7a8858 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs @@ -40,7 +40,7 @@ public class PathController : ApiController _mediator = mediator; } #endregion - + #region ===================================================================== METHODS =================================================================================== /// /// Gets the root of . @@ -51,7 +51,7 @@ public class PathController : ApiController public async Task GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + return result.Match(Ok, Problem); } /// @@ -74,7 +74,7 @@ public class PathController : ApiController public async Task GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + return result.Match(Ok, Problem); } /// @@ -87,7 +87,7 @@ public class PathController : ApiController public async Task CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken) { ErrorOr result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + return result.Match(Ok, Problem); } /// @@ -99,7 +99,7 @@ public class PathController : ApiController public async Task SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + return result.Match(Ok, Problem); } /// diff --git a/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs b/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs index 15f9b0d9..51b65871 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/Maintenance/HealthController.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Api.Core.Controllers.Common; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; @@ -20,7 +20,7 @@ public class HealthController : ApiController public async Task CheckHealth() { // TODO: to be implemented - return Ok(); + return await Task.FromResult(Ok()); } #endregion } diff --git a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs b/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs index f9819b7c..105ca527 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksController.cs @@ -43,8 +43,8 @@ public class BooksController : ApiController [HttpGet()] public async Task GetBooks() { - var result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false); - return result.Match(result => Ok(result), errors => Problem(errors)); + ErrorOr.ErrorOr> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false); + return result.Match(Ok, Problem); } /// @@ -54,8 +54,8 @@ public class BooksController : ApiController [HttpPost()] public async Task AddBook(AddBookRequest request) { - var result = await _mediator.Send(_mapper.Map(request)).ConfigureAwait(false); - return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors)); + ErrorOr.ErrorOr result = await _mediator.Send(_mapper.Map(request)).ConfigureAwait(false); + return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem); } #endregion } \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index 55eae991..605f2e47 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -1,11 +1,11 @@ - - + net8.0 enable disable $(SolutionDir)..\bin\server\ false + true 37d55c87-4374-4971-82e9-012fcaad1853 Linux lumina-server @@ -17,7 +17,6 @@ - @@ -53,6 +52,10 @@ - - + + + + + $(NoWarn);CS0436 + diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 2de42179..8b029eb2 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DependencyInjection; using Lumina.DataAccess.Common.DependencyInjection; +using Lumina.Domain.Common.DependencyInjection; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Presentation.Api.Common.DependencyInjection; -using Lumina.Domain.Common.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Hosting; using System.Threading.Tasks; @@ -23,8 +23,8 @@ public class Program /// Optional command line arguments. public static async Task Main(string[] args) { - var builder = WebApplication.CreateBuilder(args); - + WebApplicationBuilder builder = WebApplication.CreateBuilder(args); + builder.Services.BindSharedConfiguration(builder.Configuration); builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); @@ -34,7 +34,7 @@ public class Program builder.Services.AddDataAccessLayerServices(); builder.Services.AddDomainLayerServices(); - var app = builder.Build(); + WebApplication app = builder.Build(); app.UseCors("AllowAll"); diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 8ca404aa..c545cec5 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -39,7 +39,7 @@ public class ApiHttpClient : IApiHttpClient { _httpClient = httpClient; // read the API server configuration values from the configuration, and assign them to the injected client - var serverConfigurationModel = serverConfigurationOptions.Value; + ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value; httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/"); _jsonOptions = new JsonSerializerOptions @@ -62,7 +62,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the GET request. public async Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + using HttpRequestMessage request = new(HttpMethod.Get, endpoint); if (!string.IsNullOrEmpty(token)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); @@ -78,7 +78,7 @@ public class ApiHttpClient : IApiHttpClient /// An object, which allows for asynchronous iteration over the deserialized items. public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + using HttpRequestMessage request = new(HttpMethod.Get, endpoint); // HttpClient is implemented differently in Blazor WASM, because there are no sockets in the browser, so its BrowserHttpHandler is implemented on top of Fetch API, // which can provide response content in one of two forms: BrowserHttpContent, which is based on arrayBuffer method (this means that it will always read the response stream to its completion, // before making the content available), and StreamContent that is wrapping WasmHttpReadStream, which is based on readable streams (this one allows for reading response as it comes). @@ -88,11 +88,11 @@ public class ApiHttpClient : IApiHttpClient if (!string.IsNullOrEmpty(token)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); // send the request and expect only headers initially - this prevents the client from buffering the entire response - using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using System.IO.Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); // Deserialize the JSON content asynchronously as an enumerable of TResponse items - await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) + await foreach (TResponse? item in JsonSerializer.DeserializeAsyncEnumerable(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) { if (cancellationToken.IsCancellationRequested) yield break; @@ -109,14 +109,14 @@ public class ApiHttpClient : IApiHttpClient /// A model containing the deserialized blob. public async Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + using HttpRequestMessage request = new(HttpMethod.Get, endpoint); if (!string.IsNullOrEmpty(token)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { // read the content as a string, for error messages - var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); ProblemDetailsModel? problemDetails = null; try { @@ -141,7 +141,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the DELETE request. public async Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Delete, endpoint); + using HttpRequestMessage request = new(HttpMethod.Delete, endpoint); if (!string.IsNullOrEmpty(token)) _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); @@ -159,7 +159,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the PUT request. public async Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Put, endpoint); + using HttpRequestMessage request = new(HttpMethod.Put, endpoint); if (!string.IsNullOrEmpty(token)) _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); @@ -178,7 +178,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the POST request. public async Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) { - using var request = new HttpRequestMessage(HttpMethod.Post, endpoint); + using HttpRequestMessage request = new(HttpMethod.Post, endpoint); if (!string.IsNullOrEmpty(token)) _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); @@ -197,8 +197,8 @@ public class ApiHttpClient : IApiHttpClient private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // send the HTTP request and read the response - var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // if the response is successful, deserialize the content to TResponse and return it if (response.IsSuccessStatusCode) return JsonSerializer.Deserialize(content, _jsonOptions)!; diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 3509faa9..0b854e36 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -29,7 +29,7 @@ public static class PresentationWebLayerServices services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); // handle transient errors like network timeouts or intermittent failures - var retryPolicy = Policy + Polly.Retry.AsyncRetryPolicy retryPolicy = Policy .Handle() .OrResult(r => !r.IsSuccessStatusCode && @@ -39,17 +39,17 @@ public static class PresentationWebLayerServices TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // use a circuit breaker to prevent repeatedly calling a failing service - var circuitBreakerPolicy = Policy + Polly.CircuitBreaker.AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy .Handle() .OrResult(r => r.StatusCode == HttpStatusCode.InternalServerError) .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); - var policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); + Polly.Wrap.AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); // register the typed client used for the API interaction services.AddHttpClient() .AddPolicyHandler(retryPolicy) - .AddPolicyHandler(circuitBreakerPolicy); + .AddPolicyHandler(circuitBreakerPolicy); services.AddSingleton(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs index 360152a8..7b30cff6 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileManagement/FileSystemItemModel.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.FileSystem; using System; using System.Diagnostics; #endregion diff --git a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs index f1b93c54..43e3e4ba 100644 --- a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs @@ -52,15 +52,15 @@ public class FluentValidationOptions : IValidateOptions wher ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null - var validationResult = _validator.Validate(options); // validate the options using the validator + FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator // return a response based on the validation result if (validationResult.IsValid) return ValidateOptionsResult.Success; - + // if the validation fails, collect the error messages // TODO: add translation support for the error messages - var errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") + string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") .ToArray(); // and return them with a failure result diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index f94765f7..4e026534 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -1,11 +1,11 @@ - - + net8.0 enable disable $(SolutionDir)..\bin\client\ false + true @@ -22,5 +22,4 @@ - diff --git a/src/Lumina.Presentation.Web/Pages/Library/Management/Item.razor b/src/Lumina.Presentation.Web/Pages/Library/Management/Item.razor index c5c1eee8..1fcd2dd0 100644 --- a/src/Lumina.Presentation.Web/Pages/Library/Management/Item.razor +++ b/src/Lumina.Presentation.Web/Pages/Library/Management/Item.razor @@ -1,4 +1,4 @@ -@page "/library/manage/item" +@page "/library/manage/item" @page "/library/manage/item/{id:guid}" @using Lumina.Presentation.Web.Common.Enums.AudioLibrary @@ -51,7 +51,7 @@ @item.Column1 @item.Column2 - + @* *@ } @@ -165,14 +165,19 @@ // Perform save operation isSaving = false; Console.WriteLine("saved"); + await Task.CompletedTask; } private async Task CancelOperation() { isCancelling = true; // Perform cancel operation - isCancelling = false; - Console.WriteLine("cancelled"); + if (!isCancelling) + isCancelling = false; + selectedValue2 = new ComboboxItem(); + if (selectedValue2 is not null) + Console.WriteLine("cancelled"); + await Task.CompletedTask; } private List tableData = new List @@ -183,8 +188,8 @@ public class TableItem { - public string Column1 { get; set; } - public string Column2 { get; set; } - public List Directories { get; set; } + public string? Column1 { get; set; } + public string? Column2 { get; set; } + public List? Directories { get; set; } } } diff --git a/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Item.razor b/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Item.razor index 29bab801..0bfc1cdd 100644 --- a/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Item.razor +++ b/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Item.razor @@ -1,4 +1,4 @@ -@page "/library/written-content-library/books-library/books/item/{id:guid}" +@page "/library/written-content-library/books-library/books/item/{id:guid}" @using Lumina.Presentation.Web.Common.Enums.BookLibrary @using Lumina.Presentation.Web.Common.Models.Common @@ -17,7 +17,7 @@
- +
@@ -33,7 +33,7 @@

Release Information

- +
@@ -42,7 +42,7 @@

Genres

- @foreach (var genre in bookRequest.Metadata.Genres) + @foreach (var genre in bookRequest.Metadata.Genres!) {
@@ -53,7 +53,7 @@

Language

- +
@@ -80,7 +80,7 @@

Identifiers

- + @foreach (var format in Enum.GetValues(typeof(IsbnFormat))) { @@ -90,11 +90,11 @@

Contributors

- @foreach (var contributor in bookRequest.Contributors) + @foreach (var contributor in bookRequest.Contributors!) {
@* *@ - +
} @@ -117,12 +117,12 @@ private void AddGenre() { - bookRequest.Metadata.Genres.Add(new GenreModel()); + bookRequest.Metadata!.Genres!.Add(new GenreModel()); } private void AddContributor() { - bookRequest.Contributors.Add(new MediaContributorModel { Role = new MediaContributorRoleModel() }); + bookRequest.Contributors!.Add(new MediaContributorModel { Role = new MediaContributorRoleModel() }); } private async Task HandleValidSubmit() @@ -143,4 +143,4 @@ @code { [Parameter] public Guid? Id { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 93a09f80..6a786a00 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -19,7 +19,7 @@ public class Program /// Optional command line arguments. public static async Task Main(string[] args) { - var builder = WebAssemblyHostBuilder.CreateDefault(args); + WebAssemblyHostBuilder builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); @@ -29,7 +29,7 @@ public class Program //builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); - var webAssemblyHost = builder.Build(); + WebAssemblyHost webAssemblyHost = builder.Build(); await webAssemblyHost.RunAsync().ConfigureAwait(false); } diff --git a/src/Lumina.sln b/src/Lumina.sln index 3b7a5f2d..32eba438 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -73,6 +73,11 @@ Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-co EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts", "Lumina.Contracts\Lumina.Contracts.csproj", "{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5DD47F82-699B-4E71-A10A-238E80EA5814}" + ProjectSection(SolutionItems) = preProject + ..\.editorconfig = ..\.editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs index 1382c3d0..07b097b9 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs @@ -16,8 +16,8 @@ public class RepositoryFactoryTests public void RepositoryFactoryImplementsRepositoryFactoryInterface_InterfaceIsImplemented_ReturnsTrue() { // Arrange - var repositoryFactory = new RepositoryFactory(null!); - + RepositoryFactory repositoryFactory = new(null!); + // Assert Assert.True(repositoryFactory is IRepositoryFactory); } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs index 4245457b..2d6645d2 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs @@ -20,10 +20,10 @@ public class UnitOfWorkTests public void UnitOfWorkImplementsUnitOfWorkInterface_InterfaceIsImplemented_ReturnsTrue() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); // Assert Assert.True(unitOfWork is IUnitOfWork); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs index c29d140d..a72a7818 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -34,36 +34,36 @@ public class BookJsonConverter : JsonConverter { JsonElement root = doc.RootElement; - var id = root.GetProperty("id").GetProperty("value").GetGuid(); - var created = root.GetProperty("created").GetDateTime(); - var metadata = DeserializeMetadata(root.GetProperty("metadata")); + Guid id = root.GetProperty("id").GetProperty("value").GetGuid(); + DateTime created = root.GetProperty("created").GetDateTime(); + WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata")); BookFormat? format = null; - if (root.TryGetProperty("format", out var formatElement)) + if (root.TryGetProperty("format", out JsonElement formatElement)) { if (formatElement.ValueKind == JsonValueKind.String) { - var formatString = formatElement.GetString()!; + string formatString = formatElement.GetString()!; if (Enum.TryParse(formatString, out BookFormat parsedFormat)) format = parsedFormat; } } - var edition = root.GetProperty("edition").GetString(); - var volumeNumber = root.GetProperty("volumeNumber").GetInt32(); - var series = DeserializeBookSeries(root.GetProperty("series")); - var asin = root.GetProperty("asin").GetString(); - var goodreadsId = root.GetProperty("goodreadsId").GetString(); - var lccn = root.GetProperty("lccn").GetString(); - var oclcNumber = root.GetProperty("oclcNumber").GetString(); - var openLibraryId = root.GetProperty("openLibraryId").GetString(); - var libraryThingId = root.GetProperty("libraryThingId").GetString(); - var googleBooksId = root.GetProperty("googleBooksId").GetString(); - var barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString(); - var appleBooksId = root.GetProperty("appleBooksId").GetString(); - var isbns = DeserializeIsbns(root.GetProperty("isbNs")); - var contributorIds = DeserializeContributorIds(root.GetProperty("contributors")); - var ratings = DeserializeRatings(root.GetProperty("ratings")); + string? edition = root.GetProperty("edition").GetString(); + int volumeNumber = root.GetProperty("volumeNumber").GetInt32(); + BookSeries series = DeserializeBookSeries(root.GetProperty("series")); + string? asin = root.GetProperty("asin").GetString(); + string? goodreadsId = root.GetProperty("goodreadsId").GetString(); + string? lccn = root.GetProperty("lccn").GetString(); + string? oclcNumber = root.GetProperty("oclcNumber").GetString(); + string? openLibraryId = root.GetProperty("openLibraryId").GetString(); + string? libraryThingId = root.GetProperty("libraryThingId").GetString(); + string? googleBooksId = root.GetProperty("googleBooksId").GetString(); + string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString(); + string? appleBooksId = root.GetProperty("appleBooksId").GetString(); + List isbns = DeserializeIsbns(root.GetProperty("isbNs")); + List contributorIds = DeserializeContributorIds(root.GetProperty("contributors")); + List ratings = DeserializeRatings(root.GetProperty("ratings")); - var createBookResult = Book.Create( + ErrorOr.ErrorOr createBookResult = Book.Create( BookId.Create(id), metadata, Optional.FromNullable(format), @@ -85,9 +85,9 @@ public class BookJsonConverter : JsonConverter contributorIds, ratings: ratings ); - if (createBookResult.IsError) - throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}"); - return createBookResult.Value; + return createBookResult.IsError + ? throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}") + : createBookResult.Value; } } @@ -109,20 +109,20 @@ public class BookJsonConverter : JsonConverter /// The deserialized . private WrittenContentMetadata DeserializeMetadata(JsonElement element) { - var title = element.GetProperty("title").GetString(); - var originalTitle = element.GetProperty("originalTitle").GetString(); - var description = element.GetProperty("description").GetString(); - var releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo")); - var genres = DeserializeGenres(element.GetProperty("genres")); - var tags = DeserializeTags(element.GetProperty("tags")); - var language = DeserializeLanguageInfo(element.GetProperty("language")); - var originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage")); - var publisher = element.GetProperty("publisher").GetString(); + string? title = element.GetProperty("title").GetString(); + string? originalTitle = element.GetProperty("originalTitle").GetString(); + string? description = element.GetProperty("description").GetString(); + ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo")); + List genres = DeserializeGenres(element.GetProperty("genres")); + List tags = DeserializeTags(element.GetProperty("tags")); + LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language")); + LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage")); + string? publisher = element.GetProperty("publisher").GetString(); int? pageCount = null; - if (element.TryGetProperty("pageCount", out var pageCountElement)) + if (element.TryGetProperty("pageCount", out JsonElement pageCountElement)) if (pageCountElement.ValueKind != JsonValueKind.Null) pageCount = pageCountElement.GetInt32(); - var metadataResult = WrittenContentMetadata.Create( + ErrorOr.ErrorOr metadataResult = WrittenContentMetadata.Create( title!, Optional.FromNullable(originalTitle), Optional.FromNullable(description), @@ -135,10 +135,9 @@ public class BookJsonConverter : JsonConverter Optional.FromNullable(pageCount) ); - if (metadataResult.IsError) - throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}"); - - return metadataResult.Value; + return metadataResult.IsError + ? throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}") + : metadataResult.Value; } /// @@ -148,20 +147,20 @@ public class BookJsonConverter : JsonConverter /// The deserialized . private ReleaseInfo DeserializeReleaseInfo(JsonElement element) { - var originalReleaseDate = element.TryGetProperty("originalReleaseDate", out var ordElement) ? + DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) ? DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null; - var originalReleaseYear = element.TryGetProperty("originalReleaseYear", out var oryElement) && oryElement.ValueKind == JsonValueKind.Number + int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number ? oryElement.GetInt32() : (int?)null; - var reReleaseDate = element.TryGetProperty("reReleaseDate", out var rrdElement) && rrdElement.ValueKind == JsonValueKind.String ? + DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ? DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null; - var reReleaseYear = element.TryGetProperty("reReleaseYear", out var rryElement) && rryElement.ValueKind == JsonValueKind.Number + int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number ? rryElement.GetInt32() : (int?)null; - var releaseCountry = element.TryGetProperty("releaseCountry", out var rcElement) ? + string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ? rcElement.GetString() : null; - var releaseVersion = element.TryGetProperty("releaseVersion", out var rvElement) ? + string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ? rvElement.GetString() : null; - var releaseInfoResult = ReleaseInfo.Create( + ErrorOr.ErrorOr releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(originalReleaseDate), Optional.FromNullable(originalReleaseYear), Optional.FromNullable(reReleaseDate), @@ -170,9 +169,9 @@ public class BookJsonConverter : JsonConverter Optional.FromNullable(releaseVersion) ); - if (releaseInfoResult.IsError) - throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}"); - return releaseInfoResult.Value; + return releaseInfoResult.IsError + ? throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}") + : releaseInfoResult.Value; } /// @@ -208,20 +207,19 @@ public class BookJsonConverter : JsonConverter { if (element.ValueKind != JsonValueKind.Null) { - var languageCode = element.GetProperty("languageCode").GetString(); - var languageName = element.GetProperty("languageName").GetString(); - var nativeName = element.TryGetProperty("nativeName", out var nnElement) ? nnElement.GetString() : null; + string? languageCode = element.GetProperty("languageCode").GetString(); + string? languageName = element.GetProperty("languageName").GetString(); + string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null; - var languageInfoResult = LanguageInfo.Create( + ErrorOr.ErrorOr languageInfoResult = LanguageInfo.Create( languageCode!, languageName!, Optional.FromNullable(nativeName) ); - if (languageInfoResult.IsError) - throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}"); - - return languageInfoResult.Value; + return languageInfoResult.IsError + ? throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}") + : languageInfoResult.Value; } else return null; @@ -259,7 +257,7 @@ public class BookJsonConverter : JsonConverter private List DeserializeContributorIds(JsonElement element) { // TODO: implement when contributors are implemented - return new List(); + return []; } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs index ee94dc64..779edcaa 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs @@ -32,8 +32,8 @@ public static class BogusExtensions /// A random instance. public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) { - var startDateTime = start.ToDateTime(TimeOnly.MinValue); - var endDateTime = end.ToDateTime(TimeOnly.MinValue); + DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); + DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } #endregion diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs index 6d6714c7..39cd2e8e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly)) - return DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index 0f6adb68..755a2419 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -42,18 +42,15 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { builder.ConfigureServices(services => { - var descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions)); + ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions)); if (descriptor is not null) services.Remove(descriptor); - services.AddDbContext(options => + services.AddDbContext(options => options.UseSqlite(_connection)); + ServiceProvider servicePreovider = services.BuildServiceProvider(); + using (IServiceScope scope = servicePreovider.CreateScope()) { - options.UseSqlite(_connection); - }); - var servicePreovider = services.BuildServiceProvider(); - using (var scope = servicePreovider.CreateScope()) - { - var scopedServices = scope.ServiceProvider; - var dbContext = scopedServices.GetRequiredService(); + IServiceProvider scopedServices = scope.ServiceProvider; + LuminaDbContext dbContext = scopedServices.GetRequiredService(); dbContext.Database.EnsureCreated(); } }); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 769a2653..5fbe4bf7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly?)) - return (DateOnly?)DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs index 08618814..5280b527 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs @@ -54,7 +54,7 @@ public class BooksControllerTests : IClassFixture public async Task GetBooks_WhenCalled_ShouldReturnBooks() { // Arrange - var response = await _client.GetAsync("/api/v1/books"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); // Act response.EnsureSuccessStatusCode(); @@ -62,7 +62,7 @@ public class BooksControllerTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.OK); - var bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + Book[]? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); bookResponse.Should().NotBeNull(); } @@ -73,11 +73,11 @@ public class BooksControllerTests : IClassFixture AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert response.EnsureSuccessStatusCode(); - var bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); response.StatusCode.Should().Be(HttpStatusCode.Created); bookResponse.Should().NotBeNull(); @@ -155,11 +155,11 @@ public class BooksControllerTests : IClassFixture // check Location header response.Headers.Location.Should().NotBeNull(); - var locationUri = response.Headers.Location!.ToString(); + string locationUri = response.Headers.Location!.ToString(); locationUri.Should().StartWith("/api/v1/books/"); // extract ID from Location header - var idFromHeader = locationUri.Split('/').Last(); + string idFromHeader = locationUri.Split('/').Last(); // compare with bookResponse id bookResponse!.Id.ToString().Should().Be(idFromHeader); @@ -169,11 +169,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = null! } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleCannotBeEmpty.Code); @@ -183,11 +183,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); @@ -197,7 +197,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalTitle_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = null! } }; // Act & Assert @@ -208,11 +208,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Code); @@ -222,7 +222,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyDescription_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = null! } }; // Act & Assert @@ -233,11 +233,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Code); @@ -247,11 +247,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = null! } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReleaseInfoCannotBeNull.Code); @@ -261,7 +261,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalReleaseYear_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = null! } } }; // Act & Assert @@ -272,11 +272,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); @@ -286,7 +286,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReReleaseYear_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReReleaseYear = null!, ReReleaseDate = null } } }; // Act & Assert @@ -297,7 +297,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -309,7 +309,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); @@ -319,7 +319,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseCountry_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseCountry = null! } } }; // Act & Assert @@ -330,7 +330,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleaseCountry_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -340,7 +340,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.CountryCodeMustBe2CharactersLong.Code); @@ -350,7 +350,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseVersion_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseVersion = null! } } }; // Act & Assert @@ -361,7 +361,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -371,7 +371,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Code); @@ -381,7 +381,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -400,7 +400,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -412,7 +412,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Code); @@ -422,7 +422,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -441,7 +441,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -453,7 +453,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); @@ -463,11 +463,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Genres = null! } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenresListCannotBeNull.Code); @@ -477,7 +477,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -487,7 +487,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenreNameCannotBeEmpty.Code); @@ -497,7 +497,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -506,7 +506,7 @@ public class BooksControllerTests : IClassFixture } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Code); @@ -516,11 +516,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullTags_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Tags = null! } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagsListCannotBeNull.Code); @@ -530,7 +530,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -540,7 +540,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagNameCannotBeEmpty.Code); @@ -550,7 +550,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -559,7 +559,7 @@ public class BooksControllerTests : IClassFixture } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Code); @@ -569,7 +569,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguage_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = null! } }; // Act & Assert @@ -580,11 +580,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Code); @@ -594,20 +594,20 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); - bookRequest = bookRequest with - { - Metadata = bookRequest.Metadata! with + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + bookRequest = bookRequest with + { + Metadata = bookRequest.Metadata! with { - Language = bookRequest.Metadata.Language! with + Language = bookRequest.Metadata.Language! with { - LanguageCode = new Faker().Random.String2(10) + LanguageCode = new Faker().Random.String2(10) } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); @@ -617,11 +617,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Code); @@ -631,7 +631,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -644,7 +644,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); @@ -654,7 +654,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageNativeName_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { NativeName = null } } }; // Act & Assert @@ -665,7 +665,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -678,7 +678,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); @@ -688,7 +688,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguage_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = null! } }; // Act & Assert @@ -699,11 +699,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeCannotBeEmpty.Code); @@ -713,7 +713,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -726,7 +726,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); @@ -736,11 +736,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameCannotBeEmpty.Code); @@ -750,7 +750,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -763,7 +763,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); @@ -773,7 +773,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -786,7 +786,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); @@ -796,7 +796,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageNativeName_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { NativeName = null } } }; // Act & Assert @@ -807,7 +807,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPublisher_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = null } }; // Act & Assert @@ -818,11 +818,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = new Faker().Random.String2(150) } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Code); @@ -832,7 +832,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPageCount_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = null } }; // Act & Assert @@ -843,11 +843,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = -1 } }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); @@ -857,7 +857,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyFormat_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Format = null }; // Act & Assert @@ -868,11 +868,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Format = (BookFormat)99 }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.UnknownBookFormat.Code); @@ -882,7 +882,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyEdition_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Edition = null }; // Act & Assert @@ -893,11 +893,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Edition = new Faker().Random.String2(100) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Code); @@ -907,7 +907,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyVolumeNumber_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { VolumeNumber = null }; // Act & Assert @@ -918,11 +918,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { VolumeNumber = -1 }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); @@ -932,7 +932,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptySeries_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Series = null }; // Act & Assert @@ -974,7 +974,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAsin_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ASIN = null }; // Act & Assert @@ -985,11 +985,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ASIN = new Faker().Random.String2(15) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.AsinMustBe10CharactersLong.Code); @@ -999,7 +999,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoodreadsId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoodreadsId = null }; // Act & Assert @@ -1010,11 +1010,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoodreadsId = new Faker().Random.String2(2) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); @@ -1024,7 +1024,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLccn_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LCCN = null }; // Act & Assert @@ -1035,11 +1035,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LCCN = new Faker().Random.String2(200) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidLccnFormat.Code); @@ -1049,7 +1049,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOclcNumber_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OCLCNumber = null }; // Act & Assert @@ -1060,11 +1060,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OCLCNumber = new Faker().Random.String2(200) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidOclcFormat.Code); @@ -1074,7 +1074,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOpenLibraryId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OpenLibraryId = null }; // Act & Assert @@ -1085,11 +1085,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { OpenLibraryId = new Faker().Random.String2(200) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidOpenLibraryId.Code); @@ -1099,7 +1099,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LibraryThingId = null }; // Act & Assert @@ -1110,11 +1110,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { LibraryThingId = new Faker().Random.String2(200) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Code); @@ -1124,7 +1124,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoogleBooksId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoogleBooksId = null }; // Act & Assert @@ -1135,11 +1135,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(20) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Code); @@ -1149,11 +1149,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidGoogleBooksIdFormat.Code); @@ -1163,7 +1163,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyBarnesAndNobleId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { BarnesAndNobleId = null }; // Act & Assert @@ -1174,11 +1174,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(20) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Code); @@ -1188,11 +1188,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(10) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Code); @@ -1202,7 +1202,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { AppleBooksId = null }; // Act & Assert @@ -1213,11 +1213,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { AppleBooksId = new Faker().Random.String2(10) }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidAppleBooksIdFormat.Code); @@ -1227,11 +1227,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = null! }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.IsbnListCannotBeNull.Code); @@ -1241,14 +1241,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null } : isbn).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.IsbnValueCannotBeEmpty.Code); @@ -1258,14 +1258,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn10Format.Code); @@ -1275,14 +1275,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.InvalidIsbn13Format.Code); @@ -1292,13 +1292,13 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.WrittenContent.UnknownIsbnFormat.Code); @@ -1308,11 +1308,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = null! }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Code); @@ -1322,14 +1322,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Code); @@ -1339,14 +1339,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = string.Empty } } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); @@ -1356,14 +1356,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); @@ -1373,14 +1373,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(150) } } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Code); @@ -1390,14 +1390,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(150) } } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Code); @@ -1407,14 +1407,14 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Code); @@ -1424,15 +1424,15 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Name = null } } : contributor).ToList() + Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with + { Role = contributor.Role! with { Name = null } } : contributor).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Code); @@ -1442,7 +1442,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with @@ -1450,7 +1450,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Code); @@ -1460,7 +1460,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with @@ -1468,7 +1468,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Code); @@ -1478,7 +1478,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with @@ -1486,7 +1486,7 @@ public class BooksControllerTests : IClassFixture }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Code); @@ -1496,11 +1496,11 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = null! }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingsListCannotBeNull.Code); @@ -1510,13 +1510,13 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -3 } : rating).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingValueMustBePositive.Code); @@ -1526,13 +1526,13 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 3, MaxValue = 2 } : rating).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Code); @@ -1542,13 +1542,13 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -3 } : rating).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingMaxValueMustBePositive.Code); @@ -1558,7 +1558,7 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyRatingVoteCount_ShouldAddBook() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating).ToList() @@ -1571,13 +1571,13 @@ public class BooksControllerTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnBadRequest() { // Arrange - var bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); bookRequest = bookRequest with { Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -3 } : rating).ToList() }; // Act - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); // Assert await AssertBadRequestWithValidationErrors(response, Errors.Metadata.RatingVoteCountMustBePositive.Code); @@ -1588,17 +1588,17 @@ public class BooksControllerTests : IClassFixture response.StatusCode.Should().Be(HttpStatusCode.BadRequest); response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); - var problemDetails = await response.Content.ReadFromJsonAsync(); + ProblemDetails? problemDetails = await response.Content.ReadFromJsonAsync(); problemDetails.Should().NotBeNull(); problemDetails!.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.1"); problemDetails.Title.Should().Be("One or more validation errors occurred."); // TODO: update when localization is implemented problemDetails.Status.Should().Be(400); - var errors = problemDetails.Extensions["errors"] as JsonElement?; + JsonElement? errors = problemDetails.Extensions["errors"] as JsonElement?; errors.Should().NotBeNull(); - var actualErrorCodes = new List(); - foreach (var property in errors!.Value.EnumerateObject()) + List actualErrorCodes = []; + foreach (JsonProperty property in errors!.Value.EnumerateObject()) actualErrorCodes.AddRange(property.Value.EnumerateArray().Select(e => e.GetString()!)); actualErrorCodes.Should().Contain(expectedErrorCodes, because: "all expected error codes should be present"); Console.WriteLine($"All error codes: {string.Join(", ", actualErrorCodes)}"); @@ -1606,12 +1606,12 @@ public class BooksControllerTests : IClassFixture problemDetails.Extensions.Should().ContainKey("traceId"); problemDetails.Extensions["traceId"]!.ToString().Should().MatchRegex(@"^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$"); } - + private async Task AssertCreated(AddBookRequest bookRequest) { - var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); + HttpResponseMessage response = await _client.PostAsJsonAsync("api/v1/books", bookRequest); response.EnsureSuccessStatusCode(); - var bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); response.StatusCode.Should().Be(HttpStatusCode.Created); bookResponse.Should().NotBeNull(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs index 1d2dd62b..a3f28c9a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs @@ -48,10 +48,10 @@ public class AddBookRequestFixture /// The created request to add a book. public AddBookRequest CreateRequestBook() { - var releaseYear = _random.Next(2000, 2010); - var reReleaseYear = _random.Next(2010, 2020); + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); - var releaseInfo = new Faker() + ReleaseInfoModel releaseInfo = new Faker() .CustomInstantiator(f => new ReleaseInfoModel( default, default, @@ -68,19 +68,19 @@ public class AddBookRequestFixture .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) .Generate(); - var genre = new Faker() + Faker genre = new Faker() .CustomInstantiator(f => new GenreModel( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - var tag = new Faker() + Faker tag = new Faker() .CustomInstantiator(f => new TagModel( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributorRole = new Faker() + Faker mediaContributorRole = new Faker() .CustomInstantiator(f => new MediaContributorRoleModel( default!, default! @@ -88,7 +88,7 @@ public class AddBookRequestFixture .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributorName = new Faker() + Faker mediaContributorName = new Faker() .CustomInstantiator(f => new MediaContributorNameModel( default!, default! @@ -96,7 +96,7 @@ public class AddBookRequestFixture .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributor = new Faker() + Faker mediaContributor = new Faker() .CustomInstantiator(f => new MediaContributorModel( default!, default! @@ -104,7 +104,7 @@ public class AddBookRequestFixture .RuleFor(e => e.Name, mediaContributorName) .RuleFor(e => e.Role, mediaContributorRole); - var rating = new Faker() + Faker rating = new Faker() .CustomInstantiator(f => new BookRatingModel( default, default, @@ -116,7 +116,7 @@ public class AddBookRequestFixture .RuleFor(e => e.Source, _fixture.Create()) .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - var language = new Faker() + Faker language = new Faker() .CustomInstantiator(f => new LanguageInfoModel( default!, default!, @@ -126,7 +126,7 @@ public class AddBookRequestFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - var originalLanguage = new Faker() + Faker originalLanguage = new Faker() .CustomInstantiator(f => new LanguageInfoModel( default!, default!, @@ -136,7 +136,7 @@ public class AddBookRequestFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - var metadata = new Faker() + Faker metadata = new Faker() .CustomInstantiator(f => new WrittenContentMetadataModel( default!, default, @@ -160,30 +160,30 @@ public class AddBookRequestFixture .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)); - var isbn = new Faker() + Faker isbn = new Faker() .CustomInstantiator(f => new IsbnModel( default!, default )) .RuleFor(i => i.Value, f => { - var isIsbn13 = f.Random.Bool(); + bool isIsbn13 = f.Random.Bool(); if (isIsbn13) { - var prefix = f.Random.Bool() ? "978" : "979"; - var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}"; + string prefix = f.Random.Bool() ? "978" : "979"; + string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; for (int i = 0; i < 12; i++) sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); int checkDigit = (10 - (sum % 10)) % 10; - return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}"; + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; } else { - var digits = new int[9]; + int[] digits = new int[9]; for (int i = 0; i < 9; i++) digits[i] = f.Random.Number(0, 9); int sum = 0; @@ -224,16 +224,16 @@ public class AddBookRequestFixture .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) .RuleFor(x => x.LCCN, f => { - var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3)) + string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) .Select(_ => f.Random.Char('a', 'z')) .ToArray()); - var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; }) .RuleFor(x => x.OCLCNumber, f => { string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; - var prefix = f.Random.ArrayElement(prefixes); + string prefix = f.Random.ArrayElement(prefixes); string number; switch (prefix) { @@ -257,9 +257,9 @@ public class AddBookRequestFixture }) .RuleFor(x => x.OpenLibraryId, f => { - var firstDigit = f.Random.Number(1, 9); - var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + int firstDigit = f.Random.Number(1, 9); + string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); + char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); return $"OL{firstDigit}{remainingDigits}{suffix}"; }) .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) @@ -280,8 +280,8 @@ public class AddBookRequestFixture private void ConfigureCustomRequestTypes() { - var releaseYear = _random.Next(2000, 2010); - var reReleaseYear = _random.Next(2010, 2020); + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); _fixture.Register(() => new ReleaseInfoModel( _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs index 32c37e40..6457004d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs @@ -32,8 +32,8 @@ public static class BogusExtensions /// A random instance. public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) { - var startDateTime = start.ToDateTime(TimeOnly.MinValue); - var endDateTime = end.ToDateTime(TimeOnly.MinValue); + DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); + DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } #endregion diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs index e24b46fe..50721b0b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly)) - return DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index e9bc0c3d..c754ba23 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly?)) - return (DateOnly?)DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandlerTests.cs index 55903152..d574498a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandHandlerTests.cs @@ -64,15 +64,15 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); - var bookModel = _fixture.Create(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + BookModel bookModel = _fixture.Create(); _mockMapper.Map(Arg.Any()).Returns(bookModel); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); @@ -85,11 +85,11 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenBookCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with { Title = null } }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -102,15 +102,15 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenRepositoryInsertFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); - var bookModel = _fixture.Create(); - + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + BookModel bookModel = _fixture.Create(); + _mockMapper.Map(Arg.Any()).Returns(bookModel); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookAlreadyExists); // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -123,11 +123,11 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = [new IsbnModel("invalid", IsbnFormat.Isbn13)] }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -140,11 +140,11 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = [new BookRatingModel(-1, 5, null, null)] }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -157,7 +157,7 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with @@ -167,7 +167,7 @@ public class AddBookCommandHandlerTests }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -180,7 +180,7 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with @@ -190,7 +190,7 @@ public class AddBookCommandHandlerTests }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -203,7 +203,7 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with @@ -220,7 +220,7 @@ public class AddBookCommandHandlerTests }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -233,7 +233,7 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with @@ -243,7 +243,7 @@ public class AddBookCommandHandlerTests }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -256,7 +256,7 @@ public class AddBookCommandHandlerTests public async Task Handle_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata with @@ -266,7 +266,7 @@ public class AddBookCommandHandlerTests }; // Act - var result = await _sut.Handle(bookCommand, CancellationToken.None); + ErrorOr result = await _sut.Handle(bookCommand, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidatorTests.cs index b48b33a1..12ab6f9a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBookCommandValidatorTests.cs @@ -39,11 +39,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Code); @@ -53,11 +53,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Code); @@ -67,11 +67,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(200) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Title); @@ -81,11 +81,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalTitle).WithErrorMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Code); @@ -95,11 +95,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(200) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalTitle); @@ -109,11 +109,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalTitle); @@ -123,11 +123,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Description).WithErrorMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Code); @@ -137,11 +137,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(1500) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); @@ -151,11 +151,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); @@ -165,11 +165,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = string.Empty } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Description); @@ -179,11 +179,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo).WithErrorMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Code); @@ -193,11 +193,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear); @@ -207,11 +207,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 0 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); @@ -221,11 +221,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.OriginalReleaseYear).WithErrorMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Code); @@ -235,12 +235,19 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! - with { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010) } } }; + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + bookCommand = bookCommand with + { + Metadata = bookCommand.Metadata! with + { + ReleaseInfo = bookCommand.Metadata.ReleaseInfo! + with + { OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010) } + } + }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear); @@ -250,11 +257,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 0 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); @@ -264,11 +271,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 10000 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Code); @@ -278,11 +285,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(2).ToUpper() } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseCountry); @@ -292,11 +299,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsInvalid_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(3) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseCountry).WithErrorMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Code); @@ -306,11 +313,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(50) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseVersion); @@ -320,11 +327,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(51) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReleaseVersion).WithErrorMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Code); @@ -334,11 +341,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear); @@ -348,11 +355,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000 } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseYear).WithErrorMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Code); @@ -362,11 +369,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseDate = new DateOnly(2001, 1, 1) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseDate); @@ -376,11 +383,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseDate = new DateOnly(2000, 1, 1) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.ReleaseInfo!.ReReleaseDate).WithErrorMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code); @@ -390,11 +397,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Genres).WithErrorMessage(Errors.Metadata.GenresListCannotBeNull.Code); @@ -404,11 +411,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre).ToList() } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameCannotBeEmpty.Code); @@ -418,11 +425,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre).ToList() } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Metadata.Genres[0].Name").WithErrorMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Code); @@ -432,7 +439,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -442,7 +449,7 @@ public class AddBookCommandValidatorTests }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Genres); @@ -452,11 +459,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Tags).WithErrorMessage(Errors.Metadata.TagsListCannotBeNull.Code); @@ -466,11 +473,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag).ToList() } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameCannotBeEmpty.Code); @@ -480,11 +487,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag).ToList() } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Metadata.Tags[0].Name").WithErrorMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Code); @@ -494,7 +501,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -504,7 +511,7 @@ public class AddBookCommandValidatorTests }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Tags); @@ -514,11 +521,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Language); @@ -528,11 +535,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = string.Empty } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code); @@ -542,11 +549,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); @@ -556,11 +563,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = string.Empty } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code); @@ -570,11 +577,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = new Faker().Random.String2(51) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); @@ -584,11 +591,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = null! } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Language!.NativeName); @@ -598,11 +605,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = new Faker().Random.String2(51) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Language!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); @@ -612,11 +619,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalLanguage); @@ -626,11 +633,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = string.Empty } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeCannotBeEmpty.Code); @@ -640,11 +647,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageCode).WithErrorMessage(Errors.Metadata.LanguageCodeMustBe2CharactersLong.Code); @@ -654,11 +661,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = string.Empty } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameCannotBeEmpty.Code); @@ -668,11 +675,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = new Faker().Random.String2(51) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.LanguageName).WithErrorMessage(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Code); @@ -682,11 +689,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = null! } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.NativeName); @@ -696,11 +703,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = new Faker().Random.String2(51) } } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.OriginalLanguage!.NativeName).WithErrorMessage(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Code); @@ -710,11 +717,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = null! } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Publisher); @@ -724,11 +731,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(100) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.Publisher); @@ -738,11 +745,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(101) } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.Publisher).WithErrorMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Code); @@ -752,11 +759,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = null } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.PageCount); @@ -766,11 +773,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 0 } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); @@ -780,11 +787,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = -1 } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Metadata.PageCount).WithErrorMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Code); @@ -794,11 +801,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 100 } }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Metadata.PageCount); @@ -808,11 +815,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Format = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Format); @@ -822,11 +829,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Format = BookFormat.Hardcover }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Format); @@ -836,11 +843,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Format = (BookFormat)99 }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Format).WithErrorMessage(Errors.WrittenContent.UnknownBookFormat.Code); @@ -850,11 +857,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Edition = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Edition); @@ -864,11 +871,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Edition = new Faker().Random.String2(50) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Edition); @@ -878,11 +885,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Edition = new Faker().Random.String2(51) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Edition).WithErrorMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Code); @@ -892,11 +899,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { VolumeNumber = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.VolumeNumber); @@ -906,11 +913,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { VolumeNumber = 0 }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); @@ -920,11 +927,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { VolumeNumber = -1 }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.VolumeNumber).WithErrorMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Code); @@ -934,11 +941,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { VolumeNumber = 1 }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.VolumeNumber); @@ -948,11 +955,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Series = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Series); @@ -1004,11 +1011,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ASIN = new Faker().Random.String2(10) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.ASIN); @@ -1018,11 +1025,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ASIN = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.ASIN); @@ -1032,11 +1039,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ASIN = new Faker().Random.String2(9) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.ASIN).WithErrorMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Code); @@ -1046,11 +1053,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoodreadsId = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.GoodreadsId); @@ -1060,11 +1067,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoodreadsId = "123456789" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.GoodreadsId); @@ -1074,11 +1081,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoodreadsId = "abc123" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); @@ -1088,11 +1095,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoodreadsId = "123 456" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); @@ -1102,11 +1109,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoodreadsId = "123-456" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.GoodreadsId).WithErrorMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Code); @@ -1116,11 +1123,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LCCN = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.LCCN); @@ -1130,11 +1137,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LCCN = "n78890351" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.LCCN); @@ -1144,11 +1151,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LCCN = "invalid123" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); @@ -1158,11 +1165,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LCCN = new Faker().Random.String2(15) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); @@ -1172,11 +1179,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LCCN = "n12" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.LCCN).WithErrorMessage(Errors.WrittenContent.InvalidLccnFormat.Code); @@ -1186,11 +1193,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1200,11 +1207,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "ocm12345678" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1214,11 +1221,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "ocn123456789" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1228,11 +1235,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "on1234567890" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1242,11 +1249,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "(OCoLC)1234567890" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1256,11 +1263,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "12345678" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OCLCNumber); @@ -1270,11 +1277,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OCLCNumber = "invalid_oclc_number" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.OCLCNumber).WithErrorMessage(Errors.WrittenContent.InvalidOclcFormat.Code); @@ -1284,11 +1291,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OpenLibraryId = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OpenLibraryId); @@ -1298,11 +1305,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OpenLibraryId = "OL123456M" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.OpenLibraryId); @@ -1312,11 +1319,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OpenLibraryId = "InvalidID" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); @@ -1326,11 +1333,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OpenLibraryId = "OL123ABC" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); @@ -1340,11 +1347,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { OpenLibraryId = "OL123456X" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.OpenLibraryId).WithErrorMessage(Errors.WrittenContent.InvalidOpenLibraryId.Code); @@ -1354,11 +1361,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LibraryThingId = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.LibraryThingId); @@ -1368,11 +1375,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(50) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.LibraryThingId); @@ -1382,11 +1389,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(51) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.LibraryThingId).WithErrorMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Code); @@ -1396,11 +1403,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoogleBooksId = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.GoogleBooksId); @@ -1410,11 +1417,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Code); @@ -1424,11 +1431,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.GoogleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Code); @@ -1438,11 +1445,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.GoogleBooksId); @@ -1452,11 +1459,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { BarnesAndNobleId = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.BarnesAndNobleId); @@ -1466,11 +1473,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.String2(11) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Code); @@ -1480,11 +1487,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.AlphaNumeric(10) }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.BarnesAndNobleId).WithErrorMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Code); @@ -1494,11 +1501,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.Number(1000000000, 999999999).ToString() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.BarnesAndNobleId); @@ -1508,11 +1515,11 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { AppleBooksId = null }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.AppleBooksId); @@ -1522,11 +1529,11 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { AppleBooksId = "id123456" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.AppleBooksId); @@ -1536,11 +1543,11 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { AppleBooksId = "invalid_id" }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.AppleBooksId).WithErrorMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Code); @@ -1550,11 +1557,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.ISBNs).WithErrorMessage(Errors.WrittenContent.IsbnListCannotBeNull.Code); @@ -1564,11 +1571,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Code); @@ -1578,11 +1585,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn10Format.Code); @@ -1592,11 +1599,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("ISBNs[0].Value").WithErrorMessage(Errors.WrittenContent.InvalidIsbn13Format.Code); @@ -1606,11 +1613,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("ISBNs[0].Format").WithErrorMessage(Errors.WrittenContent.UnknownIsbnFormat.Code); @@ -1620,11 +1627,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.ISBNs[0].Value); @@ -1634,11 +1641,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { ISBNs = bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.ISBNs[0].Value); @@ -1648,11 +1655,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Contributors).WithErrorMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Code); @@ -1662,11 +1669,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Name").WithErrorMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Code); @@ -1676,11 +1683,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Code); @@ -1690,11 +1697,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Name.DisplayName").WithErrorMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Code); @@ -1704,11 +1711,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Name.LegalName").WithErrorMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Code); @@ -1718,11 +1725,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Role").WithErrorMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Code); @@ -1732,11 +1739,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Code); @@ -1746,11 +1753,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Role.Name").WithErrorMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Code); @@ -1760,11 +1767,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Code); @@ -1774,11 +1781,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Contributors = bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Contributors[0].Role.Category").WithErrorMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Code); @@ -1788,11 +1795,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = null! }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor(x => x.Ratings).WithErrorMessage(Errors.Metadata.RatingsListCannotBeNull.Code); @@ -1802,11 +1809,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueMustBePositive.Code); @@ -1816,11 +1823,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Ratings[0].Value").WithErrorMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Code); @@ -1830,11 +1837,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Ratings[0].MaxValue").WithErrorMessage(Errors.Metadata.RatingMaxValueMustBePositive.Code); @@ -1844,11 +1851,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldHaveValidationErrorFor("Ratings[0].VoteCount").WithErrorMessage(Errors.Metadata.RatingVoteCountMustBePositive.Code); @@ -1858,12 +1865,16 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); - bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating - with { Value = 4, MaxValue = 5, VoteCount = 100 } : rating).ToList() }; + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + bookCommand = bookCommand with + { + Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating + with + { Value = 4, MaxValue = 5, VoteCount = 100 } : rating).ToList() + }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Ratings); @@ -1873,11 +1884,11 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - var bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); bookCommand = bookCommand with { Ratings = bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating).ToList() }; // Act - var result = _validator.TestValidate(bookCommand); + TestValidationResult result = _validator.TestValidate(bookCommand); // Assert result.ShouldNotHaveValidationErrorFor(x => x.Ratings[0].VoteCount); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs index 886f7bf2..b6d47f58 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/Fixtures/AddBookCommandFixture.cs @@ -48,10 +48,10 @@ public class AddBookCommandFixture /// The created command to add a book. public AddBookCommand CreateCommandBook() { - var releaseYear = _random.Next(2000, 2010); - var reReleaseYear = _random.Next(2010, 2020); + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); - var releaseInfo = new Faker() + ReleaseInfoModel releaseInfo = new Faker() .CustomInstantiator(f => new ReleaseInfoModel( default, default, @@ -68,33 +68,33 @@ public class AddBookCommandFixture .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) .Generate(); - var genre = new Faker() + Faker genre = new Faker() .CustomInstantiator(f => new GenreModel( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - var tag = new Faker() + Faker tag = new Faker() .CustomInstantiator(f => new TagModel( default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributorRole = new Faker() + Faker mediaContributorRole = new Faker() .CustomInstantiator(f => new MediaContributorRoleModel( default!, default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributorName = new Faker() + Faker mediaContributorName = new Faker() .CustomInstantiator(f => new MediaContributorNameModel( default!, default! )) .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); - var mediaContributor = new Faker() + Faker mediaContributor = new Faker() .CustomInstantiator(f => new MediaContributorModel( default!, default! @@ -102,7 +102,7 @@ public class AddBookCommandFixture .RuleFor(e => e.Name, mediaContributorName) .RuleFor(e => e.Role, mediaContributorRole); - var rating = new Faker() + Faker rating = new Faker() .CustomInstantiator(f => new BookRatingModel( default, default, @@ -114,7 +114,7 @@ public class AddBookCommandFixture .RuleFor(e => e.Source, _fixture.Create()) .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - var language = new Faker() + Faker language = new Faker() .CustomInstantiator(f => new LanguageInfoModel( default!, default!, @@ -124,7 +124,7 @@ public class AddBookCommandFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - var originalLanguage = new Faker() + Faker originalLanguage = new Faker() .CustomInstantiator(f => new LanguageInfoModel( default!, default!, @@ -134,7 +134,7 @@ public class AddBookCommandFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - var metadata = new Faker() + Faker metadata = new Faker() .CustomInstantiator(f => new WrittenContentMetadataModel( default!, default, @@ -158,30 +158,30 @@ public class AddBookCommandFixture .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)); - var isbn = new Faker() + Faker isbn = new Faker() .CustomInstantiator(f => new IsbnModel( default!, default )) .RuleFor(i => i.Value, f => { - var isIsbn13 = f.Random.Bool(); + bool isIsbn13 = f.Random.Bool(); if (isIsbn13) { - var prefix = f.Random.Bool() ? "978" : "979"; - var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}"; + string prefix = f.Random.Bool() ? "978" : "979"; + string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; for (int i = 0; i < 12; i++) sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); int checkDigit = (10 - (sum % 10)) % 10; - return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}"; + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; } else { - var digits = new int[9]; + int[] digits = new int[9]; for (int i = 0; i < 9; i++) digits[i] = f.Random.Number(0, 9); int sum = 0; @@ -222,16 +222,16 @@ public class AddBookCommandFixture .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) .RuleFor(x => x.LCCN, f => { - var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3)) + string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) .Select(_ => f.Random.Char('a', 'z')) .ToArray()); - var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; }) .RuleFor(x => x.OCLCNumber, f => { string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; - var prefix = f.Random.ArrayElement(prefixes); + string prefix = f.Random.ArrayElement(prefixes); string number; switch (prefix) { @@ -255,9 +255,9 @@ public class AddBookCommandFixture }) .RuleFor(x => x.OpenLibraryId, f => { - var firstDigit = f.Random.Number(1, 9); - var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + int firstDigit = f.Random.Number(1, 9); + string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); + char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); return $"OL{firstDigit}{remainingDigits}{suffix}"; }) .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) @@ -278,8 +278,8 @@ public class AddBookCommandFixture private void ConfigureCustomRequestTypes() { - var releaseYear = _random.Next(2000, 2010); - var reReleaseYear = _random.Next(2010, 2020); + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); _fixture.Register(() => new ReleaseInfoModel( _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs index 344e740b..26d5e158 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs @@ -42,8 +42,8 @@ public class DataAccessLayerServicesTests public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices() { // Arrange - var services = new ServiceCollection(); - var basePath = Path.GetTempPath(); // use a real existing path + ServiceCollection services = new(); + string basePath = Path.GetTempPath(); // use a real existing path // Act DataAccessLayerServices.AddDataAccessLayerServices(services); @@ -59,16 +59,16 @@ public class DataAccessLayerServicesTests public void AddDataAccessLayerServices_ShouldRegisterDbContextWithCorrectConnectionString() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); // Act DataAccessLayerServices.AddDataAccessLayerServices(services); // Assert - var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); + ServiceDescriptor? descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); descriptor.Should().NotBeNull(); - var serviceProvider = services.BuildServiceProvider(); - var context = serviceProvider.GetService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + LuminaDbContext? context = serviceProvider.GetService(); context.Should().NotBeNull(); context!.Database.GetDbConnection().ConnectionString.Should().Contain("Lumina.db"); @@ -78,14 +78,14 @@ public class DataAccessLayerServicesTests public void AddDataAccessLayerServices_WhenCalled_ShouldRegisterRepositories() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); // Act DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - var repository = serviceProvider.GetService(); + IBookRepository? repository = serviceProvider.GetService(); repository.Should().NotBeNull(); } #endregion diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs index 6dd188cb..2812f195 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs @@ -32,8 +32,8 @@ public static class BogusExtensions /// A random instance. public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) { - var startDateTime = start.ToDateTime(TimeOnly.MinValue); - var endDateTime = end.ToDateTime(TimeOnly.MinValue); + DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); + DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } #endregion diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs index 249e821c..948aae55 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class DateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly)) - return DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly) ? DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 447f4768..e83daf4f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -21,9 +21,7 @@ public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder /// A specimen based on the request. public object Create(object request, ISpecimenContext context) { - if (request is Type type && type == typeof(DateOnly?)) - return (DateOnly?)DateOnly.FromDateTime(DateTime.Now); - return new NoSpecimen(); + return request is Type type && type == typeof(DateOnly?) ? (DateOnly?)DateOnly.FromDateTime(DateTime.Now) : (object)new NoSpecimen(); } #endregion } \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index ae3bff8b..3402e242 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -48,17 +48,17 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() { // Arrange - var bookModel = _bookModelFixture.CreateBookModel(); + BookModel bookModel = _bookModelFixture.CreateBookModel(); // Act - var result = await _sut.InsertAsync(bookModel, CancellationToken.None); + ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().Be(Result.Created); // Check if the book was added to the context's ChangeTracker - var addedBook = _mockContext.ChangeTracker.Entries() + Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); } @@ -67,13 +67,13 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError() { // Arrange - var bookModel = _bookModelFixture.CreateBookModel(); + BookModel bookModel = _bookModelFixture.CreateBookModel(); _mockContext.Books.Add(bookModel); await _mockContext.SaveChangesAsync(); // Act - var result = await _sut.InsertAsync(bookModel, CancellationToken.None); + ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert result.IsError.Should().BeTrue(); @@ -85,24 +85,24 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() { // Arrange - var existingTag = new TagModel("Existing"); + TagModel existingTag = new("Existing"); _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); - var bookModel = _bookModelFixture.CreateBookModel(); + BookModel bookModel = _bookModelFixture.CreateBookModel(); bookModel.Tags = [new("Existing"), new("New")]; // Act - var result = await _sut.InsertAsync(bookModel, CancellationToken.None); + ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().Be(Result.Created); - var addedBook = _mockContext.ChangeTracker.Entries() + Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); - var addedBookEntity = addedBook!.Entity; + BookModel addedBookEntity = addedBook!.Entity; addedBookEntity.Tags.Should().HaveCount(2); addedBookEntity.Tags.Should().Contain(t => t.Name == "Existing" && t == existingTag); addedBookEntity.Tags.Should().Contain(t => t.Name == "New" && t != existingTag); @@ -112,24 +112,24 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes() { // Arrange - var existingGenre = new GenreModel("Existing"); + GenreModel existingGenre = new("Existing"); _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); - var bookModel = _bookModelFixture.CreateBookModel(); + BookModel bookModel = _bookModelFixture.CreateBookModel(); bookModel.Genres = [new("Existing"), new("New")]; // Act - var result = await _sut.InsertAsync(bookModel, CancellationToken.None); + ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().Be(Result.Created); - var addedBook = _mockContext.ChangeTracker.Entries() + Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry? addedBook = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id); addedBook.Should().NotBeNull(); - var addedBookEntity = addedBook!.Entity; + BookModel addedBookEntity = addedBook!.Entity; addedBookEntity.Genres.Should().HaveCount(2); addedBookEntity.Genres.Should().Contain(g => g.Name == "Existing" && g == existingGenre); addedBookEntity.Genres.Should().Contain(g => g.Name == "New" && g != existingGenre); @@ -139,17 +139,17 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks() { // Arrange - var books = new List - { + List books = + [ _bookModelFixture.CreateBookModel(), _bookModelFixture.CreateBookModel(), _bookModelFixture.CreateBookModel() - }; + ]; _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); // Act - var result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); @@ -162,7 +162,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList() { // Act - var result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); @@ -174,7 +174,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities() { // Arrange - var book = _bookModelFixture.CreateBookModel(); + BookModel book = _bookModelFixture.CreateBookModel(); book.Tags = [new TagModel("Tag1"), new TagModel("Tag2")]; book.Genres = [new GenreModel("Genre1"), new GenreModel("Genre2")]; book.ISBNs = [new IsbnModel("1234567890", IsbnFormat.Isbn10), new IsbnModel("1234567890123", IsbnFormat.Isbn13)]; @@ -182,13 +182,13 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - var result = await _sut.GetAllAsync(CancellationToken.None); + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); // Assert result.IsError.Should().BeFalse(); result.Value.Should().NotBeNull(); result.Value.Should().HaveCount(1); - var retrievedBook = result.Value.First(); + BookModel retrievedBook = result.Value.First(); retrievedBook.Tags.Should().HaveCount(2); retrievedBook.Genres.Should().HaveCount(2); retrievedBook.ISBNs.Should().HaveCount(2); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs index b8081405..422ea5fa 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs @@ -46,8 +46,8 @@ public class BookModelFixture /// The created BookModel. public BookModel CreateBookModel() { - var releaseYear = _random.Next(2000, 2010); - var reReleaseYear = _random.Next(2010, 2020); + int releaseYear = _random.Next(2000, 2010); + int reReleaseYear = _random.Next(2010, 2020); return new Faker() .RuleFor(x => x.Id, f => f.Random.Guid()) @@ -105,17 +105,17 @@ public class BookModelFixture private string CreateLCCN(Faker f) { - var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3)) + string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) .Select(_ => f.Random.Char('a', 'z')) .ToArray()); - var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; } private string CreateOCLCNumber(Faker f) { string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; - var prefix = f.Random.ArrayElement(prefixes); + string prefix = f.Random.ArrayElement(prefixes); string number = prefix switch { "ocm" => f.Random.String2(8, "0123456789"), @@ -129,9 +129,9 @@ public class BookModelFixture private string CreateOpenLibraryId(Faker f) { - var firstDigit = f.Random.Number(1, 9); - var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + int firstDigit = f.Random.Number(1, 9); + string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); + char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); return $"OL{firstDigit}{remainingDigits}{suffix}"; } @@ -152,23 +152,23 @@ public class BookModelFixture private string CreateIsbn(Faker f) { - var isIsbn13 = f.Random.Bool(); + bool isIsbn13 = f.Random.Bool(); if (isIsbn13) { - var prefix = f.Random.Bool() ? "978" : "979"; - var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}"; + string prefix = f.Random.Bool() ? "978" : "979"; + string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; for (int i = 0; i < 12; i++) sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); int checkDigit = (10 - (sum % 10)) % 10; - return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}"; + return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; } else { - var digits = new int[9]; + int[] digits = new int[9]; for (int i = 0; i < 9; i++) digits[i] = f.Random.Number(0, 9); int sum = 0; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs index 5f01ad4a..cf3cdaca 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs @@ -36,8 +36,8 @@ public class RepositoryDictionaryTests public void Add_WhenValidRepositoryItemIsAdded_ShouldIncreaseCount() { // Arrange - var bookRepository = _fixture.Create(); - var repositoryDictionary = new RepositoryDictionary(); + BookRepository bookRepository = _fixture.Create(); + RepositoryDictionary repositoryDictionary = new(); // Act repositoryDictionary.Add(bookRepository); @@ -50,8 +50,8 @@ public class RepositoryDictionaryTests public void Clear_WhenCalled_ShouldRemoveAllItems() { // Arrange - var bookRepository = _fixture.Create(); - var repositoryDictionary = new RepositoryDictionary(); + BookRepository bookRepository = _fixture.Create(); + RepositoryDictionary repositoryDictionary = new(); repositoryDictionary.Add(bookRepository); // Act @@ -65,12 +65,12 @@ public class RepositoryDictionaryTests public void Get_WhenRepositoryExists_ShouldReturnCorrectRepository() { // Arrange - var expected = _fixture.Create(); - var repositoryDictionary = new RepositoryDictionary(); + BookRepository expected = _fixture.Create(); + RepositoryDictionary repositoryDictionary = new(); repositoryDictionary.Add(expected); // Act - var actual = repositoryDictionary.Get(typeof(BookRepository)); + IBookRepository actual = repositoryDictionary.Get(typeof(BookRepository)); // Assert actual.Should().BeSameAs(expected); @@ -80,7 +80,7 @@ public class RepositoryDictionaryTests public void Add_WhenNullValueIsProvided_ShouldThrowArgumentException() { // Arrange - var repositoryDictionary = new RepositoryDictionary(); + RepositoryDictionary repositoryDictionary = new(); // Act & Assert Action act = () => repositoryDictionary.Add(null!); @@ -91,8 +91,8 @@ public class RepositoryDictionaryTests public void Add_WhenDuplicateValueIsAdded_ShouldThrowArgumentException() { // Arrange - var bookRepository = _fixture.Create(); - var repositoryDictionary = new RepositoryDictionary(); + BookRepository bookRepository = _fixture.Create(); + RepositoryDictionary repositoryDictionary = new(); repositoryDictionary.Add(bookRepository); // Act & Assert @@ -104,8 +104,8 @@ public class RepositoryDictionaryTests public void Add_WhenNonRepositoryValueIsAdded_ShouldThrowArgumentException() { // Arrange - var nonRepository = new object(); - var repositoryDictionary = new RepositoryDictionary(); + object nonRepository = new(); + RepositoryDictionary repositoryDictionary = new(); // Act & Assert Action act = () => repositoryDictionary.Add(nonRepository); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs index 531480d1..02bdb024 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs @@ -21,13 +21,13 @@ public class RepositoryFactoryTests public void CreateRepository_WhenCalled_ShouldReturnCorrectRepository() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var repositoryFactory = new RepositoryFactory(serviceProvider); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + RepositoryFactory repositoryFactory = new(serviceProvider); // Act - var result = repositoryFactory.CreateRepository(); + IBookRepository result = repositoryFactory.CreateRepository(); // Assert result.Should().NotBeNull(); @@ -38,10 +38,10 @@ public class RepositoryFactoryTests public void CreateRepository_WhenUnregisteredTypeRequested_ShouldThrowException() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var repositoryFactory = new RepositoryFactory(serviceProvider); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + RepositoryFactory repositoryFactory = new(serviceProvider); // Act & Assert Action act = () => repositoryFactory.CreateRepository(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 4a7e3565..e00bcb83 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -35,8 +35,9 @@ public class UnitOfWorkTests public UnitOfWorkTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _fixture.Customize(composer => composer.FromFactory(() => { - var options = new DbContextOptionsBuilder() + _fixture.Customize(composer => composer.FromFactory(() => + { + DbContextOptions options = new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) .Options; return Substitute.ForPartsOf(options); @@ -49,10 +50,10 @@ public class UnitOfWorkTests public void ResetRepositories_WhenCalled_ShouldClearAllRepositories() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); // Act unitOfWork.ResetRepositories(); @@ -65,10 +66,10 @@ public class UnitOfWorkTests public void AddRepositories_WhenCalled_ShouldAddRepositories() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); int initialCount = unitOfWork.Repositories.Count; // Act @@ -84,11 +85,11 @@ public class UnitOfWorkTests public void Constructor_WhenCalled_ShouldAddRepositories() { // Arrange - var repositoryFactory = _fixture.Create(); - var dbContext = _fixture.Create(); + IRepositoryFactory repositoryFactory = _fixture.Create(); + LuminaDbContext dbContext = _fixture.Create(); // Act - var unitOfWork = new UnitOfWork(repositoryFactory, dbContext); + UnitOfWork unitOfWork = new(repositoryFactory, dbContext); // Assert unitOfWork.Repositories.Count.Should().BeGreaterThan(0); @@ -98,14 +99,14 @@ public class UnitOfWorkTests public void GetRepository_WhenRepositoryNotAdded_ShouldReturnNull() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); unitOfWork.ResetRepositories(); // Act - var result = unitOfWork.GetRepository(); + IBookRepository result = unitOfWork.GetRepository(); // Assert result.Should().BeNull(); @@ -115,10 +116,10 @@ public class UnitOfWorkTests public void GetRepository_WhenRepositoriesAdded_ShouldReturnRepositories() { // Arrange - var services = new ServiceCollection(); + ServiceCollection services = new(); DataAccessLayerServices.AddDataAccessLayerServices(services); - var serviceProvider = services.BuildServiceProvider(); - var unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); // Act & Assert unitOfWork.GetRepository().Should().NotBeNull(); @@ -128,10 +129,10 @@ public class UnitOfWorkTests public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync() { // Arrange - var repositoryFactory = _fixture.Create(); - var dbContext = _fixture.Create(); - var unitOfWork = new UnitOfWork(repositoryFactory, dbContext); - var cancellationToken = new CancellationToken(); + IRepositoryFactory repositoryFactory = _fixture.Create(); + LuminaDbContext dbContext = _fixture.Create(); + UnitOfWork unitOfWork = new(repositoryFactory, dbContext); + CancellationToken cancellationToken = new(); // Act await unitOfWork.SaveChangesAsync(cancellationToken); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs index d2c17ba4..4d7ffb8d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderFluentValidationUtilitiesTests.cs @@ -41,12 +41,12 @@ public class OptionsBuilderFluentValidationUtilitiesTests public void ValidateFluently_WhenCalled_ShouldRegisterFluentValidationOptions() { // Arrange - var services = Substitute.For(); - var name = _fixture.Create(); - var optionsBuilder = new OptionsBuilder(services, name); + IServiceCollection services = Substitute.For(); + string name = _fixture.Create(); + OptionsBuilder optionsBuilder = new(services, name); // Act - var result = optionsBuilder.ValidateFluently(); + OptionsBuilder result = optionsBuilder.ValidateFluently(); // Assert result.Should().BeSameAs(optionsBuilder); @@ -60,30 +60,30 @@ public class OptionsBuilderFluentValidationUtilitiesTests public void ValidateFluently_WhenCalled_ShouldUseCorrectName() { // Arrange - var services = new ServiceCollection(); - var name = _fixture.Create(); - var optionsBuilder = new OptionsBuilder(services, name); + ServiceCollection services = new(); + string name = _fixture.Create(); + OptionsBuilder optionsBuilder = new(services, name); // Act optionsBuilder.ValidateFluently(); // Assert - var serviceDescriptor = services.FirstOrDefault(sd => + ServiceDescriptor? serviceDescriptor = services.FirstOrDefault(sd => sd.ServiceType == typeof(IValidateOptions) && sd.Lifetime == ServiceLifetime.Singleton && sd.ImplementationFactory != null); serviceDescriptor.Should().NotBeNull(); - var implementationFactory = serviceDescriptor!.ImplementationFactory; + Func? implementationFactory = serviceDescriptor!.ImplementationFactory; implementationFactory.Should().NotBeNull(); - var serviceProvider = Substitute.For(); - var mockValidator = Substitute.For>(); + IServiceProvider serviceProvider = Substitute.For(); + IValidator mockValidator = Substitute.For>(); serviceProvider.GetService(typeof(IValidator)) .Returns(mockValidator); - var fluentValidationOptions = implementationFactory!(serviceProvider) as FluentValidationOptions; + FluentValidationOptions? fluentValidationOptions = implementationFactory!(serviceProvider) as FluentValidationOptions; fluentValidationOptions.Should().NotBeNull(); fluentValidationOptions!.Name.Should().Be(name); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs index 78773ef1..16bf384a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/FluentValidationOptionsTests.cs @@ -40,14 +40,14 @@ public class FluentValidationOptionsTests public void Validate_WhenMatchingName_ShouldValidateOptions() { // Arrange - var name = _fixture.Create(); - var options = _fixture.Create(); - var validator = Substitute.For>(); + string name = _fixture.Create(); + FluentValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); validator.Validate(options).Returns(new ValidationResult()); - var sut = new FluentValidationOptions(name, validator); + FluentValidationOptions sut = new(name, validator); // Act - var result = sut.Validate(name, options); + ValidateOptionsResult result = sut.Validate(name, options); // Assert result.Should().BeOfType(); @@ -59,14 +59,14 @@ public class FluentValidationOptionsTests public void Validate_WhenNonMatchingName_ShouldSkipValidation() { // Arrange - var name = _fixture.Create(); - var differentName = _fixture.Create(); - var options = _fixture.Create(); - var validator = Substitute.For>(); - var sut = new FluentValidationOptions(name, validator); + string name = _fixture.Create(); + string differentName = _fixture.Create(); + FluentValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + FluentValidationOptions sut = new(name, validator); // Act - var result = sut.Validate(differentName, options); + ValidateOptionsResult result = sut.Validate(differentName, options); // Assert result.Should().Be(ValidateOptionsResult.Skip); @@ -77,13 +77,13 @@ public class FluentValidationOptionsTests public void Validate_WhenNullName_ShouldValidateOptions() { // Arrange - var options = _fixture.Create(); - var validator = Substitute.For>(); + FluentValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); validator.Validate(options).Returns(new ValidationResult()); - var sut = new FluentValidationOptions(null, validator); + FluentValidationOptions sut = new(null, validator); // Act - var result = sut.Validate(_fixture.Create(), options); + ValidateOptionsResult result = sut.Validate(_fixture.Create(), options); // Assert result.Should().BeOfType(); @@ -95,9 +95,9 @@ public class FluentValidationOptionsTests public void Validate_WhenNullOptions_ShouldThrowArgumentNullException() { // Arrange - var name = _fixture.Create(); - var validator = Substitute.For>(); - var sut = new FluentValidationOptions(name, validator); + string name = _fixture.Create(); + IValidator validator = Substitute.For>(); + FluentValidationOptions sut = new(name, validator); // Act Action act = () => sut.Validate(name, null!); @@ -110,18 +110,18 @@ public class FluentValidationOptionsTests public void Validate_WhenInvalidOptions_ShouldReturnFailureResult() { // Arrange - var name = _fixture.Create(); - var options = _fixture.Create(); - var validator = Substitute.For>(); - var validationFailures = new List - { + string name = _fixture.Create(); + FluentValidationOptionsFixture options = _fixture.Create(); + IValidator validator = Substitute.For>(); + List validationFailures = + [ new("PropertyName", "Error Message") - }; + ]; validator.Validate(options).Returns(new ValidationResult(validationFailures)); - var sut = new FluentValidationOptions(name, validator); + FluentValidationOptions sut = new(name, validator); // Act - var result = sut.Validate(name, options); + ValidateOptionsResult result = sut.Validate(name, options); // Assert result.Should().BeOfType(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs index efb7f129..f7ac6348 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsModelValidatorTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics.CodeAnalysis; using AutoFixture; using AutoFixture.AutoNSubstitute; using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Validators; -using Lumina.Infrastructure.Common.Errors; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Infrastructure.UnitTests.Common.Validators; @@ -38,12 +38,12 @@ public class CommonSettingsModelValidatorTests public void CommonSettingsModelValidator_WhenThemeProvided_ShouldNotHaveValidationError() { // Arrange - var model = _fixture.Build() + CommonSettingsModel model = _fixture.Build() .With(x => x.Theme, "Dark") .Create(); // Act - var result = _validator.Validate(model); + FluentValidation.Results.ValidationResult result = _validator.Validate(model); // Assert result.IsValid.Should().BeTrue(); @@ -54,12 +54,12 @@ public class CommonSettingsModelValidatorTests public void CommonSettingsModelValidator_WhenThemeNotProvided_ShouldNotHaveValidationError() { // Arrange - var model = _fixture.Build() + CommonSettingsModel model = _fixture.Build() .With(x => x.Theme, string.Empty) .Create(); // Act - var result = _validator.Validate(model); + FluentValidation.Results.ValidationResult result = _validator.Validate(model); // Assert result.IsValid.Should().BeFalse(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs index 9146523d..91f39926 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics.CodeAnalysis; using AutoFixture; using AutoFixture.AutoNSubstitute; using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Validators; -using Lumina.Infrastructure.Common.Errors; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Infrastructure.UnitTests.Common.Validators; @@ -37,12 +37,12 @@ public class DatabaseSettingsModelValidatorTests public void DatabaseSettingsModelValidator_WhenDefaultConnectionProvided_ShouldNotHaveValidationError() { // Arrange - var model = _fixture.Build() + DatabaseSettingsModel model = _fixture.Build() .With(x => x.DefaultConnection, "dummy-connection-string") .Create(); // Act - var result = _validator.Validate(model); + FluentValidation.Results.ValidationResult result = _validator.Validate(model); // Assert result.IsValid.Should().BeTrue(); @@ -53,12 +53,12 @@ public class DatabaseSettingsModelValidatorTests public void DatabaseSettingsModelValidator_WhenDefaultConnectionNotProvided_ShouldHaveValidationError() { // Arrange - var model = _fixture.Build() + DatabaseSettingsModel model = _fixture.Build() .With(x => x.DefaultConnection, string.Empty) .Create(); // Act - var result = _validator.Validate(model); + FluentValidation.Results.ValidationResult result = _validator.Validate(model); // Assert result.IsValid.Should().BeFalse();