diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0e6020c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,273 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = false +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true +dotnet_style_prefer_collection_expression = when_types_loosely_match +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true +dotnet_style_prefer_conditional_expression_over_return = true +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +dotnet_style_readonly_field = true + +# Parameter preferences +dotnet_code_quality_unused_parameters = all + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = true +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = false:silent +csharp_style_var_when_type_is_apparent = false:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_local_function = true:suggestion +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = false:none +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_throw_expression = 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 + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_embedded_statements_on_same_line_experimental = true: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 = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +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, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +# Spell check + +spelling_languages = en-us,ru-RU +spelling_exclusion_path = exclusion.dic + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = 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_code_quality_unused_parameters = all:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true: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 +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_style_readonly_field = true:suggestion +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent \ No newline at end of file diff --git a/Persistence.API/Controllers/ChangeLogController.cs b/Persistence.API/Controllers/ChangeLogController.cs index 52a68dd..72f0b08 100644 --- a/Persistence.API/Controllers/ChangeLogController.cs +++ b/Persistence.API/Controllers/ChangeLogController.cs @@ -12,7 +12,7 @@ namespace Persistence.API.Controllers; [Route("api/[controller]")] public class ChangeLogController : ControllerBase, IChangeLogApi { - private IChangeLogRepository repository; + private readonly IChangeLogRepository repository; public ChangeLogController(IChangeLogRepository repository) { diff --git a/Persistence.API/Controllers/DataSaubController.cs b/Persistence.API/Controllers/DataSaubController.cs index 202e527..715b1ef 100644 --- a/Persistence.API/Controllers/DataSaubController.cs +++ b/Persistence.API/Controllers/DataSaubController.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Persistence.Models; using Persistence.Repositories; -using Persistence.Repository.Data; namespace Persistence.API.Controllers; diff --git a/Persistence.API/Controllers/SetpointController.cs b/Persistence.API/Controllers/SetpointController.cs index cb8d479..0ff6878 100644 --- a/Persistence.API/Controllers/SetpointController.cs +++ b/Persistence.API/Controllers/SetpointController.cs @@ -1,8 +1,8 @@ -using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Repositories; +using System.Net; namespace Persistence.API.Controllers; @@ -14,98 +14,98 @@ namespace Persistence.API.Controllers; [Route("api/[controller]")] public class SetpointController : ControllerBase, ISetpointApi { - private readonly ISetpointRepository setpointRepository; + private readonly ISetpointRepository setpointRepository; - public SetpointController(ISetpointRepository setpointRepository) - { - this.setpointRepository = setpointRepository; - } + public SetpointController(ISetpointRepository setpointRepository) + { + this.setpointRepository = setpointRepository; + } - /// - /// Получить актуальные значения уставок - /// - /// - /// - /// - [HttpGet("current")] - public async Task>> GetCurrent([FromQuery] IEnumerable setpointKeys, CancellationToken token) - { - var result = await setpointRepository.GetCurrent(setpointKeys, token); + /// + /// Получить актуальные значения уставок + /// + /// + /// + /// + [HttpGet("current")] + public async Task>> GetCurrent([FromQuery] IEnumerable setpointKeys, CancellationToken token) + { + var result = await setpointRepository.GetCurrent(setpointKeys, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить значения уставок за определенный момент времени - /// - /// - /// - /// - /// - [HttpGet("history")] - public async Task>> GetHistory([FromQuery] IEnumerable setpointKeys, [FromQuery] DateTimeOffset historyMoment, CancellationToken token) - { - var result = await setpointRepository.GetHistory(setpointKeys, historyMoment, token); + /// + /// Получить значения уставок за определенный момент времени + /// + /// + /// + /// + /// + [HttpGet("history")] + public async Task>> GetHistory([FromQuery] IEnumerable setpointKeys, [FromQuery] DateTimeOffset historyMoment, CancellationToken token) + { + var result = await setpointRepository.GetHistory(setpointKeys, historyMoment, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить историю изменений значений уставок - /// - /// - /// - /// - [HttpGet("log")] - public async Task>>> GetLog([FromQuery] IEnumerable setpointKeys, CancellationToken token) - { - var result = await setpointRepository.GetLog(setpointKeys, token); + /// + /// Получить историю изменений значений уставок + /// + /// + /// + /// + [HttpGet("log")] + public async Task>>> GetLog([FromQuery] IEnumerable setpointKeys, CancellationToken token) + { + var result = await setpointRepository.GetLog(setpointKeys, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - [HttpGet("range")] - public async Task> GetDatesRangeAsync(CancellationToken token) - { - var result = await setpointRepository.GetDatesRangeAsync(token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + [HttpGet("range")] + public async Task> GetDatesRangeAsync(CancellationToken token) + { + var result = await setpointRepository.GetDatesRangeAsync(token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - [HttpGet("part")] - public async Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) - { - var result = await setpointRepository.GetPart(dateBegin, take, token); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + [HttpGet("part")] + public async Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var result = await setpointRepository.GetPart(dateBegin, take, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Сохранить уставку - /// - /// - /// - /// - /// - [HttpPost] - [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] - public async Task Add(Guid setpointKey, object newValue, CancellationToken token) - { - var userId = User.GetUserId(); - await setpointRepository.Add(setpointKey, newValue, userId, token); + /// + /// Сохранить уставку + /// + /// + /// + /// + /// + [HttpPost] + [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] + public async Task Add(Guid setpointKey, object newValue, CancellationToken token) + { + var userId = User.GetUserId(); + await setpointRepository.Add(setpointKey, newValue, userId, token); - return CreatedAtAction(nameof(Add), true); - } + return CreatedAtAction(nameof(Add), true); + } } diff --git a/Persistence.API/Controllers/TechMessagesController.cs b/Persistence.API/Controllers/TechMessagesController.cs index a7b0094..10efb04 100644 --- a/Persistence.API/Controllers/TechMessagesController.cs +++ b/Persistence.API/Controllers/TechMessagesController.cs @@ -1,129 +1,129 @@ -using System.Net; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Models.Requests; using Persistence.Repositories; +using System.Net; namespace Persistence.API.Controllers; /// -/// Работа с состояниями систем автобурения (АБ) +/// Работа с технологическими сообщениями систем автобурения (АБ) /// [ApiController] [Authorize] [Route("api/[controller]")] public class TechMessagesController : ControllerBase { - private readonly ITechMessagesRepository techMessagesRepository; - private static readonly Dictionary categories = new Dictionary() - { - { 0, "System" }, - { 1, "Авария" }, - { 2, "Предупреждение" }, - { 3, "Инфо" }, - { 4, "Прочее" } - }; + private readonly ITechMessagesRepository techMessagesRepository; + private static readonly Dictionary categories = new() + { + { 0, "System" }, + { 1, "Авария" }, + { 2, "Предупреждение" }, + { 3, "Инфо" }, + { 4, "Прочее" } + }; - public TechMessagesController(ITechMessagesRepository techMessagesRepository) - { - this.techMessagesRepository = techMessagesRepository; - } + public TechMessagesController(ITechMessagesRepository techMessagesRepository) + { + this.techMessagesRepository = techMessagesRepository; + } - /// - /// Получить список технологических сообщений в виде страницы - /// - /// - /// - /// - [HttpGet] - public async Task>> GetPage([FromQuery] PaginationRequest request, CancellationToken token) - { - var result = await techMessagesRepository.GetPage(request, token); + /// + /// Получить список технологических сообщений в виде страницы + /// + /// + /// + /// + [HttpGet] + public async Task>> GetPage([FromQuery] PaginationRequest request, CancellationToken token) + { + var result = await techMessagesRepository.GetPage(request, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить статистику по системам - /// - /// - /// - /// - /// - [HttpGet("statistics")] - public async Task>> GetStatistics([FromQuery] IEnumerable autoDrillingSystem, [FromQuery] IEnumerable categoryIds, CancellationToken token) - { - var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token); + /// + /// Получить статистику по системам + /// + /// + /// + /// + /// + [HttpGet("statistics")] + public async Task>> GetStatistics([FromQuery] IEnumerable autoDrillingSystem, [FromQuery] IEnumerable categoryIds, CancellationToken token) + { + var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить список всех систем - /// - /// - /// - [HttpGet("systems")] - public async Task>> GetSystems(CancellationToken token) - { - var result = await techMessagesRepository.GetSystems(token); + /// + /// Получить список всех систем + /// + /// + /// + [HttpGet("systems")] + public async Task>> GetSystems(CancellationToken token) + { + var result = await techMessagesRepository.GetSystems(token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - [HttpGet("range")] - public async Task> GetDatesRangeAsync(CancellationToken token) - { - var result = await techMessagesRepository.GetDatesRangeAsync(token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + [HttpGet("range")] + public async Task> GetDatesRangeAsync(CancellationToken token) + { + var result = await techMessagesRepository.GetDatesRangeAsync(token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - [HttpGet("part")] - public async Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) - { - var result = await techMessagesRepository.GetPart(dateBegin, take, token); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + [HttpGet("part")] + public async Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var result = await techMessagesRepository.GetPart(dateBegin, take, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Добавить новые технологические сообщения - /// - /// - /// - /// - [HttpPost] - [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] - public async Task AddRange([FromBody] IEnumerable dtos, CancellationToken token) - { - var userId = User.GetUserId(); + /// + /// Добавить новые технологические сообщения + /// + /// + /// + /// + [HttpPost] + [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] + public async Task AddRange([FromBody] IEnumerable dtos, CancellationToken token) + { + var userId = User.GetUserId(); var result = await techMessagesRepository.AddRange(dtos, userId, token); - return CreatedAtAction(nameof(AddRange), result); - } + return CreatedAtAction(nameof(AddRange), result); + } - /// - /// Получить словарь категорий - /// - /// - [HttpGet("categories")] - public ActionResult> GetImportantCategories() - { - return Ok(categories); - } + /// + /// Получить словарь категорий + /// + /// + [HttpGet("categories")] + public ActionResult> GetImportantCategories() + { + return Ok(categories); + } } \ No newline at end of file diff --git a/Persistence.API/Controllers/TimeSeriesController.cs b/Persistence.API/Controllers/TimeSeriesController.cs index 6991759..f13c641 100644 --- a/Persistence.API/Controllers/TimeSeriesController.cs +++ b/Persistence.API/Controllers/TimeSeriesController.cs @@ -11,20 +11,20 @@ namespace Persistence.API.Controllers; public class TimeSeriesController : ControllerBase, ITimeSeriesDataApi where TDto : class, ITimeSeriesAbstractDto, new() { - private ITimeSeriesDataRepository timeSeriesDataRepository; + private readonly ITimeSeriesDataRepository timeSeriesDataRepository; - public TimeSeriesController(ITimeSeriesDataRepository timeSeriesDataRepository) - { - this.timeSeriesDataRepository = timeSeriesDataRepository; + public TimeSeriesController(ITimeSeriesDataRepository timeSeriesDataRepository) + { + this.timeSeriesDataRepository = timeSeriesDataRepository; } - /// - /// Получить список объектов, удовлетворяющий диапазону дат - /// - /// - /// - /// - [HttpGet] + /// + /// Получить список объектов, удовлетворяющий диапазону дат + /// + /// + /// + /// + [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public async Task Get(DateTimeOffset dateBegin, CancellationToken token) { @@ -32,40 +32,40 @@ public class TimeSeriesController : ControllerBase, ITimeSeriesDataApi - /// Получить диапазон дат, для которых есть данные в репозиторие - /// - /// - /// - [HttpGet("datesRange")] + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + [HttpGet("datesRange")] public async Task GetDatesRange(CancellationToken token) { var result = await timeSeriesDataRepository.GetDatesRange(token); return Ok(result); } - /// - /// Получить список объектов с прореживанием, удовлетворяющий диапазону дат - /// - /// - /// - /// - /// - /// - [HttpGet("resampled")] + /// + /// Получить список объектов с прореживанием, удовлетворяющий диапазону дат + /// + /// + /// + /// + /// + /// + [HttpGet("resampled")] public async Task GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) { var result = await timeSeriesDataRepository.GetResampledData(dateBegin, intervalSec, approxPointsCount, token); return Ok(result); } - /// - /// Добавить записи - /// - /// - /// - /// - [HttpPost] + /// + /// Добавить записи + /// + /// + /// + /// + [HttpPost] public async Task AddRange(IEnumerable dtos, CancellationToken token) { var result = await timeSeriesDataRepository.AddRange(dtos, token); diff --git a/Persistence.API/Controllers/TimestampedSetController.cs b/Persistence.API/Controllers/TimestampedSetController.cs index bd0e97e..4687e72 100644 --- a/Persistence.API/Controllers/TimestampedSetController.cs +++ b/Persistence.API/Controllers/TimestampedSetController.cs @@ -13,7 +13,7 @@ namespace Persistence.API.Controllers; [ApiController] [Authorize] [Route("api/[controller]/{idDiscriminator}")] -public class TimestampedSetController : ControllerBase +public class TimestampedSetController : ControllerBase { private readonly ITimestampedSetRepository repository; @@ -32,7 +32,7 @@ public class TimestampedSetController : ControllerBase /// кол-во затронутых записей [HttpPost] [ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)] - public async Task AddRange([FromRoute]Guid idDiscriminator, [FromBody]IEnumerable sets, CancellationToken token) + public async Task AddRange([FromRoute] Guid idDiscriminator, [FromBody] IEnumerable sets, CancellationToken token) { var result = await repository.AddRange(idDiscriminator, sets, token); return Ok(result); @@ -50,7 +50,7 @@ public class TimestampedSetController : ControllerBase /// Фильтрованный набор данных с сортировкой по отметке времени [HttpGet] [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)] - public async Task Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, [FromQuery]IEnumerable? columnNames, int skip, int take, CancellationToken token) + public async Task Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, [FromQuery] IEnumerable? columnNames, int skip, int take, CancellationToken token) { var result = await repository.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token); return Ok(result); @@ -66,7 +66,7 @@ public class TimestampedSetController : ControllerBase /// Фильтрованный набор данных с сортировкой по отметке времени [HttpGet("last")] [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)] - public async Task GetLast(Guid idDiscriminator, [FromQuery]IEnumerable? columnNames, int take, CancellationToken token) + public async Task GetLast(Guid idDiscriminator, [FromQuery] IEnumerable? columnNames, int take, CancellationToken token) { var result = await repository.GetLast(idDiscriminator, columnNames, take, token); return Ok(result); diff --git a/Persistence.API/Controllers/WitsDataController.cs b/Persistence.API/Controllers/WitsDataController.cs index 741b35c..9e855b7 100644 --- a/Persistence.API/Controllers/WitsDataController.cs +++ b/Persistence.API/Controllers/WitsDataController.cs @@ -1,8 +1,8 @@ -using System.Net; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Services.Interfaces; +using System.Net; namespace Persistence.API.Controllers; @@ -14,73 +14,73 @@ namespace Persistence.API.Controllers; [Route("api/[controller]")] public class WitsDataController : ControllerBase, IWitsDataApi { - private readonly IWitsDataService witsDataService; + private readonly IWitsDataService witsDataService; - public WitsDataController(IWitsDataService witsDataService) - { - this.witsDataService = witsDataService; - } + public WitsDataController(IWitsDataService witsDataService) + { + this.witsDataService = witsDataService; + } - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - /// - [HttpGet("{discriminatorId}/datesRange")] - public async Task> GetDatesRangeAsync([FromRoute] Guid discriminatorId, CancellationToken token) - { - var result = await witsDataService.GetDatesRangeAsync(discriminatorId, token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + /// + [HttpGet("{discriminatorId}/datesRange")] + public async Task> GetDatesRangeAsync([FromRoute] Guid discriminatorId, CancellationToken token) + { + var result = await witsDataService.GetDatesRangeAsync(discriminatorId, token); - return result == null ? NoContent() : Ok(result); - } + return result == null ? NoContent() : Ok(result); + } - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - /// - [HttpGet("{discriminatorId}/part")] - public async Task>> GetPart([FromRoute] Guid discriminatorId, [FromQuery] DateTimeOffset dateBegin, [FromQuery] int take, CancellationToken token) - { - var result = await witsDataService.GetPart(discriminatorId, dateBegin, take, token); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + /// + [HttpGet("{discriminatorId}/part")] + public async Task>> GetPart([FromRoute] Guid discriminatorId, [FromQuery] DateTimeOffset dateBegin, [FromQuery] int take, CancellationToken token) + { + var result = await witsDataService.GetPart(discriminatorId, dateBegin, take, token); - return Ok(result); - } + return Ok(result); + } - /// - /// Получить набор параметров (Wits) для построения графика - /// - /// Дискриминатор системы - /// Начало временного интервала - /// Конец временного интервала - /// Количество точек - /// - /// - [HttpGet("{discriminatorId}/graph")] - public async Task>> GetValuesForGraph([FromRoute] Guid discriminatorId, - [FromQuery] DateTimeOffset dateFrom, [FromQuery] DateTimeOffset dateTo, [FromQuery] int approxPointsCount, CancellationToken token) - { - var result = await witsDataService.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token); - - return Ok(result); - } + /// + /// Получить набор параметров (Wits) для построения графика + /// + /// Дискриминатор системы + /// Начало временного интервала + /// Конец временного интервала + /// Количество точек + /// + /// + [HttpGet("{discriminatorId}/graph")] + public async Task>> GetValuesForGraph([FromRoute] Guid discriminatorId, + [FromQuery] DateTimeOffset dateFrom, [FromQuery] DateTimeOffset dateTo, [FromQuery] int approxPointsCount, CancellationToken token) + { + var result = await witsDataService.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token); - /// - /// Сохранить набор параметров (Wits) - /// - /// - /// - /// - [HttpPost] - [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] - public async Task AddRange([FromBody] IEnumerable dtos, CancellationToken token) - { - var result = await witsDataService.AddRange(dtos, token); + return Ok(result); + } - return CreatedAtAction(nameof(AddRange), result); - } + /// + /// Сохранить набор параметров (Wits) + /// + /// + /// + /// + [HttpPost] + [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] + public async Task AddRange([FromBody] IEnumerable dtos, CancellationToken token) + { + var result = await witsDataService.AddRange(dtos, token); + + return CreatedAtAction(nameof(AddRange), result); + } } diff --git a/Persistence.API/DependencyInjection.cs b/Persistence.API/DependencyInjection.cs index 622a93b..d2960af 100644 --- a/Persistence.API/DependencyInjection.cs +++ b/Persistence.API/DependencyInjection.cs @@ -30,12 +30,11 @@ public static class DependencyInjection c.MapType(() => new OpenApiSchema { Type = "string", Format = "date" }); c.MapType(() => new OpenApiSchema { - AnyOf = new OpenApiSchema[] - { + AnyOf = [ new OpenApiSchema {Type = "string", Format = "string" }, new OpenApiSchema {Type = "number", Format = "int32" }, - new OpenApiSchema {Type = "number", Format = "float" }, - } + new OpenApiSchema {Type = "number", Format = "float" } + ] }); c.CustomOperationIds(e => @@ -47,8 +46,8 @@ public static class DependencyInjection var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get(); if (needUseKeyCloak) - c.AddKeycloackSecurity(configuration); - else c.AddDefaultSecurity(configuration); + c.AddKeycloakSecurity(configuration); + else c.AddDefaultSecurity(); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); @@ -57,13 +56,13 @@ public static class DependencyInjection }); } - public static void AddServices(this IServiceCollection services) - { - services.AddTransient(); - } + public static void AddServices(this IServiceCollection services) + { + services.AddTransient(); + } - #region Authentication - public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) + #region Authentication + public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) { var needUseKeyCloak = configuration .GetSection("NeedUseKeyCloak") @@ -108,7 +107,7 @@ public static class DependencyInjection { OnMessageReceived = context => { - var accessToken = context.Request.Headers["Authorization"] + var accessToken = context.Request.Headers.Authorization .ToString() .Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty) .Trim(); @@ -141,12 +140,12 @@ public static class DependencyInjection } #endregion - #region Security (Swagger) - private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration) + #region Keycloak + private static void AddKeycloakSecurity(this SwaggerGenOptions options, IConfiguration configuration) { - options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme + options.AddSecurityDefinition("Keycloak", new OpenApiSecurityScheme { - Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345token'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.OAuth2, @@ -167,7 +166,7 @@ public static class DependencyInjection Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, - Id = "Keycloack" + Id = "Keycloak" }, Scheme = "Bearer", Name = "Bearer", @@ -178,11 +177,11 @@ public static class DependencyInjection }); } - private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration) + private static void AddDefaultSecurity(this SwaggerGenOptions options) { options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { - Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", + Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345token'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, diff --git a/Persistence.API/Extensions.cs b/Persistence.API/Extensions.cs index 601a2f4..5fa9fd4 100644 --- a/Persistence.API/Extensions.cs +++ b/Persistence.API/Extensions.cs @@ -7,18 +7,15 @@ public static class Extensions { public static T GetUserId(this ClaimsPrincipal principal) { - if (principal == null) - throw new ArgumentNullException(nameof(principal)); + ArgumentNullException.ThrowIfNull(principal, nameof(principal)); var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier); - if (String.IsNullOrEmpty(loggedInUserId)) - throw new ArgumentNullException(nameof(loggedInUserId)); + ArgumentNullException.ThrowIfNullOrEmpty(loggedInUserId, nameof(loggedInUserId)); var result = TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(loggedInUserId); - if (result is null) - throw new ArgumentNullException(nameof(result)); + ArgumentNullException.ThrowIfNull(result, nameof(result)); return (T)result; diff --git a/Persistence.API/Persistence.API.csproj b/Persistence.API/Persistence.API.csproj index dfff363..fa3b7ad 100644 --- a/Persistence.API/Persistence.API.csproj +++ b/Persistence.API/Persistence.API.csproj @@ -9,6 +9,11 @@ $(NoWarn);1591 + + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + + diff --git a/Persistence.API/Persistence.API.http b/Persistence.API/Persistence.API.http deleted file mode 100644 index 0eba8fa..0000000 --- a/Persistence.API/Persistence.API.http +++ /dev/null @@ -1,6 +0,0 @@ -@Persistence.API_HostAddress = http://localhost:5032 - -GET {{Persistence.API_HostAddress}}/weatherforecast/ -Accept: application/json - -### diff --git a/Persistence.API/Program.cs b/Persistence.API/Program.cs index bc54d92..bb6e9a7 100644 --- a/Persistence.API/Program.cs +++ b/Persistence.API/Program.cs @@ -1,6 +1,3 @@ - -using Persistence.Models; - namespace Persistence.API; public class Program @@ -18,5 +15,5 @@ public class Program .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); - }); + }); } diff --git a/Persistence.API/Startup.cs b/Persistence.API/Startup.cs index 77b3e72..2b522bd 100644 --- a/Persistence.API/Startup.cs +++ b/Persistence.API/Startup.cs @@ -1,6 +1,6 @@ -using Persistence.Repository; -using Persistence.Database.Model; +using Persistence.Database.Model; using Persistence.Database.Postgres; +using Persistence.Repository; namespace Persistence.API; diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs index 3deae09..79135e1 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs @@ -1,4 +1,4 @@ -using Persistence.Models; +using Persistence.Models; using Refit; namespace Persistence.Client.Clients.Interfaces.Refit; diff --git a/Persistence.Client/Helpers/ApiTokenHelper.cs b/Persistence.Client/Helpers/ApiTokenHelper.cs index 32f1fe2..a2f632e 100644 --- a/Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/Persistence.Client/Helpers/ApiTokenHelper.cs @@ -1,31 +1,31 @@ -using System.IdentityModel.Tokens.Jwt; -using System.Net.Http.Headers; -using System.Security.Claims; -using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Persistence.Models.Configurations; using RestSharp; +using System.IdentityModel.Tokens.Jwt; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text.Json; namespace Persistence.Client.Helpers; public static class ApiTokenHelper { - public static void Authorize(this HttpClient httpClient, IConfiguration configuration) - { - var authUser = configuration - .GetSection(nameof(AuthUser)) - .Get()!; - var needUseKeyCloak = configuration - .GetSection("NeedUseKeyCloak") - .Get()!; - var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; + public static void Authorize(this HttpClient httpClient, IConfiguration configuration) + { + var authUser = configuration + .GetSection(nameof(AuthUser)) + .Get()!; + var needUseKeyCloak = configuration + .GetSection("NeedUseKeyCloak") + .Get()!; + var keycloakGetTokenUrl = configuration.GetSection("KeycloakGetTokenUrl").Get() ?? string.Empty; - var jwtToken = needUseKeyCloak - ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) - : authUser.CreateDefaultJwtToken(); + var jwtToken = needUseKeyCloak + ? authUser.CreateKeyCloakJwtToken(keycloakGetTokenUrl) + : authUser.CreateDefaultJwtToken(); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); - } + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); + } public static void Authorize(this HttpClient httpClient, string jwtToken) { @@ -45,36 +45,36 @@ public static class ApiTokenHelper new(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString()) }; - var tokenDescriptor = new SecurityTokenDescriptor - { - Issuer = JwtParams.Issuer, - Audience = JwtParams.Audience, - Subject = new ClaimsIdentity(claims), - Expires = DateTime.UtcNow.AddHours(1), - SigningCredentials = new SigningCredentials(JwtParams.SecurityKey, SecurityAlgorithms.HmacSha256Signature) - }; - var tokenHandler = new JwtSecurityTokenHandler(); - var token = tokenHandler.CreateToken(tokenDescriptor); - return tokenHandler.WriteToken(token); - } + var tokenDescriptor = new SecurityTokenDescriptor + { + Issuer = JwtParams.Issuer, + Audience = JwtParams.Audience, + Subject = new ClaimsIdentity(claims), + Expires = DateTime.UtcNow.AddHours(1), + SigningCredentials = new SigningCredentials(JwtParams.SecurityKey, SecurityAlgorithms.HmacSha256Signature) + }; + var tokenHandler = new JwtSecurityTokenHandler(); + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + } - private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) - { - var restClient = new RestClient(); + private static string CreateKeyCloakJwtToken(this AuthUser authUser, string keycloakGetTokenUrl) + { + var restClient = new RestClient(); - var request = new RestRequest(keycloakGetTokenUrl, Method.Post); - request.AddParameter("username", authUser.Username); - request.AddParameter("password", authUser.Password); - request.AddParameter("client_id", authUser.ClientId); - request.AddParameter("grant_type", authUser.GrantType); + var request = new RestRequest(keycloakGetTokenUrl, Method.Post); + request.AddParameter("username", authUser.Username); + request.AddParameter("password", authUser.Password); + request.AddParameter("client_id", authUser.ClientId); + request.AddParameter("grant_type", authUser.GrantType); - var keyCloackResponse = restClient.Post(request); - if (keyCloackResponse.IsSuccessful && !String.IsNullOrEmpty(keyCloackResponse.Content)) - { - var token = JsonSerializer.Deserialize(keyCloackResponse.Content)!; - return token.AccessToken; - } + var keycloakResponse = restClient.Post(request); + if (keycloakResponse.IsSuccessful && !String.IsNullOrEmpty(keycloakResponse.Content)) + { + var token = JsonSerializer.Deserialize(keycloakResponse.Content)!; + return token.AccessToken; + } - return String.Empty; - } + return String.Empty; + } } diff --git a/Persistence.Client/Persistence.Client.csproj b/Persistence.Client/Persistence.Client.csproj index b764e7a..7d81fc3 100644 --- a/Persistence.Client/Persistence.Client.csproj +++ b/Persistence.Client/Persistence.Client.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -38,6 +38,11 @@ Readme.md + + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + + diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index c77ac04..31b6fd9 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -1,4 +1,3 @@ -using System.Text.Json; using Microsoft.Extensions.Configuration; using Persistence.Client.Clients.Interfaces; using Persistence.Client.Clients; @@ -8,6 +7,7 @@ using Persistence.Factories; using Persistence.Client.Clients.Interfaces.Refit; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using System.Text.Json; namespace Persistence.Client { diff --git a/Persistence.Database.Postgres/DependencyInjection.cs b/Persistence.Database.Postgres/DependencyInjection.cs index b308629..e775952 100644 --- a/Persistence.Database.Postgres/DependencyInjection.cs +++ b/Persistence.Database.Postgres/DependencyInjection.cs @@ -1,7 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Npgsql; namespace Persistence.Database.Model; diff --git a/Persistence.Database.Postgres/DesignTimeDbContextFactory.cs b/Persistence.Database.Postgres/DesignTimeDbContextFactory.cs index 2123efd..b4fbd85 100644 --- a/Persistence.Database.Postgres/DesignTimeDbContextFactory.cs +++ b/Persistence.Database.Postgres/DesignTimeDbContextFactory.cs @@ -12,12 +12,14 @@ public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory(); diff --git a/Persistence.Database.Postgres/EFExtensionsInitialization.cs b/Persistence.Database.Postgres/EFExtensionsInitialization.cs index 99d3f5d..a876f7a 100644 --- a/Persistence.Database.Postgres/EFExtensionsInitialization.cs +++ b/Persistence.Database.Postgres/EFExtensionsInitialization.cs @@ -1,11 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Persistence.Database.Postgres; public static class EFExtensionsInitialization diff --git a/Persistence.Database.Postgres/Migrations/20241118052225_SetpointMigration.cs b/Persistence.Database.Postgres/Migrations/20241118052225_SetpointMigration.cs index ea6fccf..fac75d8 100644 --- a/Persistence.Database.Postgres/Migrations/20241118052225_SetpointMigration.cs +++ b/Persistence.Database.Postgres/Migrations/20241118052225_SetpointMigration.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/Persistence.Database.Postgres/Migrations/20241126071115_Add_ChangeLog.cs b/Persistence.Database.Postgres/Migrations/20241126071115_Add_ChangeLog.cs index 0802b00..4750bc3 100644 --- a/Persistence.Database.Postgres/Migrations/20241126071115_Add_ChangeLog.cs +++ b/Persistence.Database.Postgres/Migrations/20241126071115_Add_ChangeLog.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/Persistence.Database.Postgres/Migrations/20241126100631_Init.cs b/Persistence.Database.Postgres/Migrations/20241126100631_Init.cs index ceca42c..74a549e 100644 --- a/Persistence.Database.Postgres/Migrations/20241126100631_Init.cs +++ b/Persistence.Database.Postgres/Migrations/20241126100631_Init.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs b/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs index ccf18d4..41ef8cb 100644 --- a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs +++ b/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/Persistence.Database.Postgres/Migrations/20241203120141_ParameterDataMigration.cs b/Persistence.Database.Postgres/Migrations/20241203120141_ParameterDataMigration.cs index 7e9bde6..8d44be9 100644 --- a/Persistence.Database.Postgres/Migrations/20241203120141_ParameterDataMigration.cs +++ b/Persistence.Database.Postgres/Migrations/20241203120141_ParameterDataMigration.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; #nullable disable diff --git a/Persistence.Database.Postgres/PersistencePostgresContext.cs b/Persistence.Database.Postgres/PersistencePostgresContext.cs index 862b247..6016a1d 100644 --- a/Persistence.Database.Postgres/PersistencePostgresContext.cs +++ b/Persistence.Database.Postgres/PersistencePostgresContext.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure.Internal; namespace Persistence.Database.Model; @@ -10,7 +9,7 @@ public partial class PersistencePostgresContext : PersistenceDbContext { public PersistencePostgresContext(DbContextOptions options) : base(options) - {} + { } protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Persistence.Database/EFExtensions.cs b/Persistence.Database/EFExtensions.cs index d60d768..decdb39 100644 --- a/Persistence.Database/EFExtensions.cs +++ b/Persistence.Database/EFExtensions.cs @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; -using System.Text.Json.Serialization; using System.Text.Json; +using System.Text.Json.Serialization; namespace Persistence.Database; diff --git a/Persistence.Database/Entity/ChangeLog.cs b/Persistence.Database/Entity/ChangeLog.cs index 9a8001b..edffb52 100644 --- a/Persistence.Database/Entity/ChangeLog.cs +++ b/Persistence.Database/Entity/ChangeLog.cs @@ -1,8 +1,8 @@  -using System.ComponentModel.DataAnnotations.Schema; -using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; using Persistence.Models; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace Persistence.Database.Model; diff --git a/Persistence.Database/Entity/DataSaub.cs b/Persistence.Database/Entity/DataSaub.cs index fecda5a..ee18d40 100644 --- a/Persistence.Database/Entity/DataSaub.cs +++ b/Persistence.Database/Entity/DataSaub.cs @@ -1,5 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Persistence.Database.Model; diff --git a/Persistence.Database/Entity/DrillingSystem.cs b/Persistence.Database/Entity/DrillingSystem.cs index 6588fb0..dc52ce7 100644 --- a/Persistence.Database/Entity/DrillingSystem.cs +++ b/Persistence.Database/Entity/DrillingSystem.cs @@ -1,16 +1,16 @@ -using System.ComponentModel.DataAnnotations; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using Microsoft.EntityFrameworkCore; namespace Persistence.Database.Entity; public class DrillingSystem { - [Key, Comment("Id системы автобурения")] - public Guid SystemId { get; set; } + [Key, Comment("Id системы автобурения")] + public Guid SystemId { get; set; } - [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")] - public required string Name { get; set; } + [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")] + public required string Name { get; set; } - [Comment("Описание системы автобурения")] - public string? Description { get; set; } + [Comment("Описание системы автобурения")] + public string? Description { get; set; } } diff --git a/Persistence.Database/Entity/ParameterData.cs b/Persistence.Database/Entity/ParameterData.cs index f8257de..eb4fa4c 100644 --- a/Persistence.Database/Entity/ParameterData.cs +++ b/Persistence.Database/Entity/ParameterData.cs @@ -1,21 +1,21 @@ -using System.ComponentModel.DataAnnotations; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using Microsoft.EntityFrameworkCore; namespace Persistence.Database.Entity; [PrimaryKey(nameof(DiscriminatorId), nameof(ParameterId), nameof(Timestamp))] public class ParameterData { - [Required, Comment("Дискриминатор системы")] - public Guid DiscriminatorId { get; set; } + [Required, Comment("Дискриминатор системы")] + public Guid DiscriminatorId { get; set; } - [Comment("Id параметра")] - public int ParameterId { get; set; } + [Comment("Id параметра")] + public int ParameterId { get; set; } - [Column(TypeName = "varchar(256)"), Comment("Значение параметра в виде строки")] - public required string Value { get; set; } + [Column(TypeName = "varchar(256)"), Comment("Значение параметра в виде строки")] + public required string Value { get; set; } - [Comment("Временная отметка")] - public DateTimeOffset Timestamp { get; set; } + [Comment("Временная отметка")] + public DateTimeOffset Timestamp { get; set; } } diff --git a/Persistence.Database/Entity/Setpoint.cs b/Persistence.Database/Entity/Setpoint.cs index 6ca2c27..968bdd7 100644 --- a/Persistence.Database/Entity/Setpoint.cs +++ b/Persistence.Database/Entity/Setpoint.cs @@ -1,21 +1,21 @@ -using System.ComponentModel.DataAnnotations.Schema; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; namespace Persistence.Database.Model { - [PrimaryKey(nameof(Key), nameof(Created))] - public class Setpoint - { - [Comment("Ключ")] - public Guid Key { get; set; } + [PrimaryKey(nameof(Key), nameof(Created))] + public class Setpoint + { + [Comment("Ключ")] + public Guid Key { get; set; } - [Column(TypeName = "jsonb"), Comment("Значение уставки")] - public required object Value { get; set; } + [Column(TypeName = "jsonb"), Comment("Значение уставки")] + public required object Value { get; set; } - [Comment("Дата создания уставки")] - public DateTimeOffset Created { get; set; } + [Comment("Дата создания уставки")] + public DateTimeOffset Created { get; set; } - [Comment("Id автора последнего изменения")] - public Guid IdUser { get; set; } - } + [Comment("Id автора последнего изменения")] + public Guid IdUser { get; set; } + } } diff --git a/Persistence.Database/Entity/TechMessage.cs b/Persistence.Database/Entity/TechMessage.cs index ea29cc2..8051415 100644 --- a/Persistence.Database/Entity/TechMessage.cs +++ b/Persistence.Database/Entity/TechMessage.cs @@ -1,33 +1,33 @@ -using System.ComponentModel.DataAnnotations; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using Microsoft.EntityFrameworkCore; namespace Persistence.Database.Entity { - public class TechMessage - { - [Key, Comment("Id события")] - public Guid EventId { get; set; } + public class TechMessage + { + [Key, Comment("Id события")] + public Guid EventId { get; set; } - [Comment("Id Категории важности")] - public int CategoryId { get; set; } + [Comment("Id Категории важности")] + public int CategoryId { get; set; } - [Comment("Дата возникновения")] - public DateTimeOffset Timestamp { get; set; } + [Comment("Дата возникновения")] + public DateTimeOffset Timestamp { get; set; } - [Comment("Глубина забоя")] - public double? Depth { get; set; } + [Comment("Глубина забоя")] + public double? Depth { get; set; } - [Column(TypeName = "varchar(512)"), Comment("Текст сообщения")] - public required string MessageText { get; set; } + [Column(TypeName = "varchar(512)"), Comment("Текст сообщения")] + public required string MessageText { get; set; } - [Required, Comment("Id системы автобурения, к которой относится сообщение")] - public required Guid SystemId { get; set; } + [Required, Comment("Id системы автобурения, к которой относится сообщение")] + public required Guid SystemId { get; set; } - [Required, ForeignKey(nameof(SystemId)), Comment("Система автобурения, к которой относится сообщение")] - public virtual required DrillingSystem System { get; set; } + [Required, ForeignKey(nameof(SystemId)), Comment("Система автобурения, к которой относится сообщение")] + public virtual required DrillingSystem System { get; set; } - [Comment("Id пользователя за пультом бурильщика")] - public Guid UserId { get; set; } - } + [Comment("Id пользователя за пультом бурильщика")] + public Guid UserId { get; set; } + } } diff --git a/Persistence.Database/Entity/TimestampedSet.cs b/Persistence.Database/Entity/TimestampedSet.cs index c9a0dda..09a50ee 100644 --- a/Persistence.Database/Entity/TimestampedSet.cs +++ b/Persistence.Database/Entity/TimestampedSet.cs @@ -6,6 +6,6 @@ namespace Persistence.Database.Entity; [Comment("Общая таблица данных временных рядов")] [PrimaryKey(nameof(IdDiscriminator), nameof(Timestamp))] public record TimestampedSet( - [property: Comment("Дискриминатор ссылка на тип сохраняемых данных")] Guid IdDiscriminator, - [property: Comment("Отметка времени, строго в UTC")] DateTimeOffset Timestamp, + [property: Comment("Дискриминатор ссылка на тип сохраняемых данных")] Guid IdDiscriminator, + [property: Comment("Отметка времени, строго в UTC")] DateTimeOffset Timestamp, [property: Column(TypeName = "jsonb"), Comment("Набор сохраняемых данных")] IDictionary Set); diff --git a/Persistence.Database/PersistenceDbContext.cs b/Persistence.Database/PersistenceDbContext.cs index 849865d..a61ea31 100644 --- a/Persistence.Database/PersistenceDbContext.cs +++ b/Persistence.Database/PersistenceDbContext.cs @@ -17,11 +17,11 @@ public class PersistenceDbContext : DbContext public DbSet ChangeLog => Set(); - public DbSet TechMessage => Set(); + public DbSet TechMessage => Set(); - public DbSet ParameterData => Set(); + public DbSet ParameterData => Set(); - public PersistenceDbContext(DbContextOptions options) + public PersistenceDbContext(DbContextOptions options) : base(options) { diff --git a/Persistence.IntegrationTests/BaseIntegrationTest.cs b/Persistence.IntegrationTests/BaseIntegrationTest.cs index 0f1152d..9cc68ab 100644 --- a/Persistence.IntegrationTests/BaseIntegrationTest.cs +++ b/Persistence.IntegrationTests/BaseIntegrationTest.cs @@ -1,12 +1,10 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Database; using Persistence.Database.Model; using Xunit; namespace Persistence.IntegrationTests; -public abstract class BaseIntegrationTest : IClassFixture, - IDisposable +public abstract class BaseIntegrationTest : IClassFixture, IDisposable { protected readonly IServiceScope scope; @@ -23,5 +21,6 @@ public abstract class BaseIntegrationTest : IClassFixture, { scope.Dispose(); dbContext.Dispose(); + GC.SuppressFinalize(this); } } diff --git a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs index 6513e7c..51edebd 100644 --- a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs @@ -13,7 +13,7 @@ namespace Persistence.IntegrationTests.Controllers; public class ChangeLogControllerTest : BaseIntegrationTest { private readonly IChangeLogClient client; - private static Random generatorRandomDigits = new Random(); + private static readonly Random generatorRandomDigits = new(); public ChangeLogControllerTest(WebAppFactoryFixture factory) : base(factory) { @@ -26,11 +26,11 @@ public class ChangeLogControllerTest : BaseIntegrationTest [Fact] public async Task ClearAndInsertRange_InEmptyDb() { - // arrange - dbContext.CleanupDbSet(); + // arrange + dbContext.CleanupDbSet(); - var idDiscriminator = Guid.NewGuid(); - var dtos = Generate(2, DateTimeOffset.UtcNow); + var idDiscriminator = Guid.NewGuid(); + var dtos = Generate(2); // act var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken()); @@ -61,7 +61,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest // arrange var count = 1; var idDiscriminator = Guid.NewGuid(); - var dtos = Generate(count, DateTimeOffset.UtcNow); + var dtos = Generate(count); var dto = dtos.FirstOrDefault()!; // act @@ -77,7 +77,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest // arrange var count = 3; var idDiscriminator = Guid.NewGuid(); - var dtos = Generate(count, DateTimeOffset.UtcNow); + var dtos = Generate(count); // act var result = await client.AddRange(idDiscriminator, dtos, new CancellationToken()); @@ -89,11 +89,11 @@ public class ChangeLogControllerTest : BaseIntegrationTest [Fact] public async Task Update_returns_success() { - // arrange - dbContext.CleanupDbSet(); + // arrange + dbContext.CleanupDbSet(); - var idDiscriminator = Guid.NewGuid(); - var dtos = Generate(1, DateTimeOffset.UtcNow); + var idDiscriminator = Guid.NewGuid(); + var dtos = Generate(1); var dto = dtos.FirstOrDefault()!; var result = await client.Add(idDiscriminator, dto, new CancellationToken()); @@ -101,7 +101,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest .Where(x => x.IdDiscriminator == idDiscriminator) .FirstOrDefault(); dto = entity.Adapt(); - dto.DepthEnd = dto.DepthEnd + 10; + dto.DepthEnd += 10; // act result = await client.Update(dto, new CancellationToken()); @@ -138,7 +138,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest { // arrange var count = 2; - var dtos = Generate(count, DateTimeOffset.UtcNow); + var dtos = Generate(count); var entities = dtos.Select(d => d.Adapt()).ToArray(); dbContext.ChangeLog.AddRange(entities); dbContext.SaveChanges(); @@ -163,7 +163,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest public async Task Delete_returns_success() { // arrange - var dtos = Generate(1, DateTimeOffset.UtcNow); + var dtos = Generate(1); var dto = dtos.FirstOrDefault()!; var entity = dto.Adapt(); dbContext.ChangeLog.Add(entity); @@ -181,7 +181,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest { // arrange var count = 10; - var dtos = Generate(count, DateTimeOffset.UtcNow); + var dtos = Generate(count); var entities = dtos.Select(d => d.Adapt()).ToArray(); dbContext.ChangeLog.AddRange(entities); dbContext.SaveChanges(); @@ -223,11 +223,11 @@ public class ChangeLogControllerTest : BaseIntegrationTest [Fact] public async Task GetByDate_returns_success() { - // arrange - dbContext.CleanupDbSet(); + // arrange + dbContext.CleanupDbSet(); - //создаем записи - var count = 5; + //создаем записи + var count = 5; var changeLogItems = CreateChangeLogItems(count, (-15, 15)); var idDiscriminator = changeLogItems.Item1; var entities = changeLogItems.Item2; @@ -241,8 +241,8 @@ public class ChangeLogControllerTest : BaseIntegrationTest var filterRequest = new SectionPartRequest() { - DepthStart = 0, - DepthEnd = 1000, + DepthStart = 0, + DepthEnd = 1000, }; var paginationRequest = new PaginationRequest() @@ -276,11 +276,11 @@ public class ChangeLogControllerTest : BaseIntegrationTest int daysAfterNowFilter, int changeLogCount) { - // arrange - dbContext.CleanupDbSet(); + // arrange + dbContext.CleanupDbSet(); - //создаем записи - var count = insertedCount; + //создаем записи + var count = insertedCount; var daysRange = (daysBeforeNowChangeLog, daysAfterNowChangeLog); var changeLogItems = CreateChangeLogItems(count, daysRange); var idDiscriminator = changeLogItems.Item1; @@ -288,7 +288,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest foreach (var entity in entities) { - entity.DepthEnd = entity.DepthEnd + 10; + entity.DepthEnd += 10; } var dtos = entities.Select(e => e.Adapt()).ToArray(); await client.UpdateRange(dtos, new CancellationToken()); @@ -304,7 +304,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest } - private static IEnumerable Generate(int count, DateTimeOffset from) + private static IEnumerable Generate(int count) { for (int i = 0; i < count; i++) yield return new DataWithWellDepthAndSectionDto() @@ -326,8 +326,8 @@ public class ChangeLogControllerTest : BaseIntegrationTest var minDayCount = daysRange.Item1; var maxDayCount = daysRange.Item2; - var idDiscriminator = Guid.NewGuid(); - var dtos = Generate(count, DateTimeOffset.UtcNow); + Guid idDiscriminator = Guid.NewGuid(); + var dtos = Generate(count); var entities = dtos.Select(d => { var entity = d.Adapt(); diff --git a/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs b/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs index 9febbb5..49365a8 100644 --- a/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs @@ -1,12 +1,11 @@ -using Persistence.Client; -using Persistence.Database.Model; -using Persistence.Repository.Data; +using Persistence.Database.Model; +using Persistence.Models; using Xunit; namespace Persistence.IntegrationTests.Controllers; public class DataSaubControllerTest : TimeSeriesBaseControllerTest { - private readonly DataSaubDto dto = new DataSaubDto() + private readonly DataSaubDto dto = new() { AxialLoad = 1, BitDepth = 2, @@ -29,7 +28,7 @@ public class DataSaubControllerTest : TimeSeriesBaseControllerTest(); + public class SetpointControllerTest : BaseIntegrationTest + { + private readonly ISetpointClient setpointClient; + private class TestObject + { + public string? Value1 { get; set; } + public int? Value2 { get; set; } + } + public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory) + { + var scope = factory.Services.CreateScope(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); setpointClient = persistenceClientFactory.GetSetpointClient(); } - [Fact] - public async Task GetCurrent_returns_success() - { - //arrange - var setpointKeys = new List() - { - Guid.NewGuid(), - Guid.NewGuid() - }; + [Fact] + public async Task GetCurrent_returns_success() + { + //arrange + var setpointKeys = new List() + { + Guid.NewGuid(), + Guid.NewGuid() + }; //act var response = await setpointClient.GetCurrent(setpointKeys, new CancellationToken()); @@ -41,11 +42,11 @@ namespace Persistence.IntegrationTests.Controllers Assert.Empty(response); } - [Fact] - public async Task GetCurrent_AfterSave_returns_success() - { - //arrange - var setpointKey = await Add(); + [Fact] + public async Task GetCurrent_AfterSave_returns_success() + { + //arrange + var setpointKey = await Add(); //act var response = await setpointClient.GetCurrent([setpointKey], new CancellationToken()); @@ -56,16 +57,16 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(setpointKey, response.FirstOrDefault()?.Key); } - [Fact] - public async Task GetHistory_returns_success() - { - //arrange - var setpointKeys = new List() - { - Guid.NewGuid(), - Guid.NewGuid() - }; - var historyMoment = DateTimeOffset.UtcNow; + [Fact] + public async Task GetHistory_returns_success() + { + //arrange + var setpointKeys = new List() + { + Guid.NewGuid(), + Guid.NewGuid() + }; + var historyMoment = DateTimeOffset.UtcNow; //act var response = await setpointClient.GetHistory(setpointKeys, historyMoment, new CancellationToken()); @@ -75,13 +76,13 @@ namespace Persistence.IntegrationTests.Controllers Assert.Empty(response); } - [Fact] - public async Task GetHistory_AfterSave_returns_success() - { - //arrange - var setpointKey = await Add(); - var historyMoment = DateTimeOffset.UtcNow; - historyMoment = historyMoment.AddDays(1); + [Fact] + public async Task GetHistory_AfterSave_returns_success() + { + //arrange + var setpointKey = await Add(); + var historyMoment = DateTimeOffset.UtcNow; + historyMoment = historyMoment.AddDays(1); //act var response = await setpointClient.GetHistory([setpointKey], historyMoment, new CancellationToken()); @@ -92,15 +93,15 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(setpointKey, response.FirstOrDefault()?.Key); } - [Fact] - public async Task GetLog_returns_success() - { - //arrange - var setpointKeys = new List() - { - Guid.NewGuid(), - Guid.NewGuid() - }; + [Fact] + public async Task GetLog_returns_success() + { + //arrange + var setpointKeys = new List() + { + Guid.NewGuid(), + Guid.NewGuid() + }; //act var response = await setpointClient.GetLog(setpointKeys, new CancellationToken()); @@ -110,11 +111,11 @@ namespace Persistence.IntegrationTests.Controllers Assert.Empty(response); } - [Fact] - public async Task GetLog_AfterSave_returns_success() - { - //arrange - var setpointKey = await Add(); + [Fact] + public async Task GetLog_AfterSave_returns_success() + { + //arrange + var setpointKey = await Add(); //act var response = await setpointClient.GetLog([setpointKey], new CancellationToken()); @@ -125,11 +126,11 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(setpointKey, response.FirstOrDefault().Key); } - [Fact] - public async Task GetDatesRange_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetDatesRange_returns_success() + { + //arrange + dbContext.CleanupDbSet(); //act var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None); @@ -140,13 +141,13 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(DateTimeOffset.MaxValue, response!.To); } - [Fact] - public async Task GetDatesRange_AfterSave_returns_success() - { - //arrange - dbContext.CleanupDbSet(); - - await Add(); + [Fact] + public async Task GetDatesRange_AfterSave_returns_success() + { + //arrange + dbContext.CleanupDbSet(); + + await Add(); var dateBegin = DateTimeOffset.MinValue; var take = 1; @@ -170,12 +171,12 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(expectedValue, actualValueTo); } - [Fact] - public async Task GetPart_returns_success() - { - //arrange - var dateBegin = DateTimeOffset.UtcNow; - var take = 2; + [Fact] + public async Task GetPart_returns_success() + { + //arrange + var dateBegin = DateTimeOffset.UtcNow; + var take = 2; //act var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None); @@ -185,13 +186,13 @@ namespace Persistence.IntegrationTests.Controllers Assert.Empty(response); } - [Fact] - public async Task GetPart_AfterSave_returns_success() - { - //arrange - var dateBegin = DateTimeOffset.UtcNow; - var take = 1; - await Add(); + [Fact] + public async Task GetPart_AfterSave_returns_success() + { + //arrange + var dateBegin = DateTimeOffset.UtcNow; + var take = 1; + await Add(); //act var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None); @@ -201,21 +202,21 @@ namespace Persistence.IntegrationTests.Controllers Assert.NotEmpty(response); } - [Fact] - public async Task Save_returns_success() - { - await Add(); - } + [Fact] + public async Task Save_returns_success() + { + await Add(); + } - private async Task Add() - { - //arrange - var setpointKey = Guid.NewGuid(); - var setpointValue = new TestObject() - { - value1 = "1", - value2 = 2 - }; + private async Task Add() + { + //arrange + var setpointKey = Guid.NewGuid(); + var setpointValue = new TestObject() + { + Value1 = "1", + Value2 = 2 + }; //act await setpointClient.Add(setpointKey, setpointValue, new CancellationToken()); diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index 3501f87..3ec7fce 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -5,42 +5,43 @@ using Persistence.Client.Clients.Interfaces; using Persistence.Database.Entity; using Persistence.Models; using Persistence.Models.Requests; +using System.Net; using Xunit; namespace Persistence.IntegrationTests.Controllers { - public class TechMessagesControllerTest : BaseIntegrationTest - { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; - private readonly ITechMessagesClient techMessagesClient; - private readonly IMemoryCache memoryCache; - public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory) - { - var scope = factory.Services.CreateScope(); - var persistenceClientFactory = scope.ServiceProvider - .GetRequiredService(); + public class TechMessagesControllerTest : BaseIntegrationTest + { + private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; + private readonly ITechMessagesClient techMessagesClient; + private readonly IMemoryCache memoryCache; + public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory) + { + var scope = factory.Services.CreateScope(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); techMessagesClient = persistenceClientFactory.GetTechMessagesClient(); memoryCache = scope.ServiceProvider.GetRequiredService(); } - [Fact] - public async Task GetPage_returns_success() - { - //arrange - memoryCache.Remove(SystemCacheKey); - dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + [Fact] + public async Task GetPage_returns_success() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - var requestDto = new PaginationRequest() - { - Skip = 1, - Take = 2, - SortSettings = nameof(TechMessage.CategoryId) - }; + var requestDto = new PaginationRequest() + { + Skip = 1, + Take = 2, + SortSettings = nameof(TechMessage.CategoryId) + }; - //act - var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); + //act + var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); //assert Assert.NotNull(response); @@ -49,32 +50,32 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(requestDto.Take, response.Take); } - [Fact] - public async Task GetPage_AfterSave_returns_success() - { - //arrange - var dtos = await InsertRange(); - var dtosCount = dtos.Count(); - var requestDto = new PaginationRequest() - { - Skip = 0, - Take = 2, - SortSettings = nameof(TechMessage.CategoryId) - }; + [Fact] + public async Task GetPage_AfterSave_returns_success() + { + //arrange + var dtos = await InsertRange(); + var dtosCount = dtos.Count(); + var requestDto = new PaginationRequest() + { + Skip = 0, + Take = 2, + SortSettings = nameof(TechMessage.CategoryId) + }; - //act - var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); + //act + var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); //assert Assert.NotNull(response); Assert.Equal(dtosCount, response.Count); } - [Fact] - public async Task InsertRange_returns_success() - { - await InsertRange(); - } + [Fact] + public async Task InsertRange_returns_success() + { + await InsertRange(); + } [Fact] public async Task InsertRange_returns_BadRequest() @@ -88,12 +89,12 @@ namespace Persistence.IntegrationTests.Controllers EventId = Guid.NewGuid(), CategoryId = -1, // < 0 Timestamp = DateTimeOffset.UtcNow, - Depth = -1, // < 0 + Depth = -1, // < 0 MessageText = string.Empty, // length < 0 System = string.Concat(Enumerable.Repeat(nameof(TechMessageDto.System), 100)), // length > 256 UserId = Guid.NewGuid() - } - }; + } + }; try { @@ -107,34 +108,34 @@ namespace Persistence.IntegrationTests.Controllers } } - [Fact] - public async Task GetSystems_returns_success() - { - //arrange - memoryCache.Remove(SystemCacheKey); - dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + [Fact] + public async Task GetSystems_returns_success() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - //act - var response = await techMessagesClient.GetSystems(CancellationToken.None); + //act + var response = await techMessagesClient.GetSystems(CancellationToken.None); //assert Assert.NotNull(response); Assert.Empty(response); } - [Fact] - public async Task GetSystems_AfterSave_returns_success() - { - //arrange - var dtos = await InsertRange(); - var systems = dtos - .Select(e => e.System) - .Distinct() - .ToArray(); + [Fact] + public async Task GetSystems_AfterSave_returns_success() + { + //arrange + var dtos = await InsertRange(); + var systems = dtos + .Select(e => e.System) + .Distinct() + .ToArray(); - //act - var response = await techMessagesClient.GetSystems(CancellationToken.None); + //act + var response = await techMessagesClient.GetSystems(CancellationToken.None); //assert Assert.NotNull(response); @@ -142,36 +143,36 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(systems, content); } - [Fact] - public async Task GetStatistics_returns_success() - { - //arrange - memoryCache.Remove(SystemCacheKey); - dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + [Fact] + public async Task GetStatistics_returns_success() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - var imortantId = 1; - var autoDrillingSystem = nameof(TechMessageDto.System); + var importantId = 1; + var autoDrillingSystem = nameof(TechMessageDto.System); - //act - var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, CancellationToken.None); + //act + var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None); //assert Assert.NotNull(response); Assert.Empty(response); } - [Fact] - public async Task GetStatistics_AfterSave_returns_success() - { - //arrange - var imortantId = 0; - var autoDrillingSystem = nameof(TechMessageDto.System); - var dtos = await InsertRange(); - var filteredDtos = dtos.Where(e => e.CategoryId == imortantId && e.System == autoDrillingSystem); + [Fact] + public async Task GetStatistics_AfterSave_returns_success() + { + //arrange + var importantId = 0; + var autoDrillingSystem = nameof(TechMessageDto.System); + var dtos = await InsertRange(); + var filteredDtos = dtos.Where(e => e.CategoryId == importantId && e.System == autoDrillingSystem); - //act - var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, CancellationToken.None); + //act + var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None); //assert Assert.NotNull(response); @@ -198,14 +199,14 @@ namespace Persistence.IntegrationTests.Controllers Assert.Equal(DateTimeOffset.MaxValue, response?.To); } - [Fact] - public async Task GetDatesRange_AfterSave_returns_success() - { - //arrange - await InsertRange(); + [Fact] + public async Task GetDatesRange_AfterSave_returns_success() + { + //arrange + await InsertRange(); - //act - var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); + //act + var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); //assert Assert.NotNull(response); @@ -213,76 +214,76 @@ namespace Persistence.IntegrationTests.Controllers Assert.NotNull(response?.To); } - [Fact] - public async Task GetPart_returns_success() - { - //arrange - var dateBegin = DateTimeOffset.UtcNow; - var take = 2; + [Fact] + public async Task GetPart_returns_success() + { + //arrange + var dateBegin = DateTimeOffset.UtcNow; + var take = 2; - //act - var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); + //act + var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); //assert Assert.NotNull(response); Assert.Empty(response); } - [Fact] - public async Task GetPart_AfterSave_returns_success() - { - //arrange - var dateBegin = DateTimeOffset.UtcNow; - var take = 1; - await InsertRange(); + [Fact] + public async Task GetPart_AfterSave_returns_success() + { + //arrange + var dateBegin = DateTimeOffset.UtcNow; + var take = 1; + await InsertRange(); - //act - var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); + //act + var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); //assert Assert.NotNull(response); Assert.NotEmpty(response); } - private async Task> InsertRange() - { - //arrange - memoryCache.Remove(SystemCacheKey); - dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + private async Task> InsertRange() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - var dtos = new List() - { - new TechMessageDto() - { - EventId = Guid.NewGuid(), - CategoryId = 1, - Timestamp = DateTimeOffset.UtcNow, - Depth = 1.11, - MessageText = nameof(TechMessageDto.MessageText), - System = nameof(TechMessageDto.System).ToLower(), - UserId = Guid.NewGuid() - }, - new TechMessageDto() - { - EventId = Guid.NewGuid(), - CategoryId = 2, - Timestamp = DateTimeOffset.UtcNow, - Depth = 2.22, - MessageText = nameof(TechMessageDto.MessageText), - System = nameof(TechMessageDto.System).ToLower(), - UserId = Guid.NewGuid() - } - }; + var dtos = new List() + { + new() + { + EventId = Guid.NewGuid(), + CategoryId = 1, + Timestamp = DateTimeOffset.UtcNow, + Depth = 1.11, + MessageText = nameof(TechMessageDto.MessageText), + System = nameof(TechMessageDto.System).ToLower(), + UserId = Guid.NewGuid() + }, + new() + { + EventId = Guid.NewGuid(), + CategoryId = 2, + Timestamp = DateTimeOffset.UtcNow, + Depth = 2.22, + MessageText = nameof(TechMessageDto.MessageText), + System = nameof(TechMessageDto.System).ToLower(), + UserId = Guid.NewGuid() + } + }; - //act - var response = await techMessagesClient.AddRange(dtos, CancellationToken.None); + //act + var response = await techMessagesClient.AddRange(dtos, CancellationToken.None); //assert Assert.Equal(dtos.Count, response); - return dtos; - } - } + return dtos; + } + } } diff --git a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs index ca9536f..ef43a10 100644 --- a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs @@ -1,25 +1,26 @@ -using System.Net; using Mapster; using Microsoft.Extensions.DependencyInjection; using Persistence.Client; using Persistence.Client.Clients.Interfaces; using Persistence.Database.Model; +using System.Net; using Xunit; namespace Persistence.IntegrationTests.Controllers; + public abstract class TimeSeriesBaseControllerTest : BaseIntegrationTest where TEntity : class, ITimestampedData, new() where TDto : class, new() { - private ITimeSeriesClient timeSeriesClient; + private readonly ITimeSeriesClient timeSeriesClient; public TimeSeriesBaseControllerTest(WebAppFactoryFixture factory) : base(factory) { dbContext.CleanupDbSet(); - var scope = factory.Services.CreateScope(); - var persistenceClientFactory = scope.ServiceProvider - .GetRequiredService(); + var scope = factory.Services.CreateScope(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); timeSeriesClient = persistenceClientFactory.GetTimeSeriesClient(); } @@ -100,7 +101,7 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat //assert Assert.NotNull(response); - var ratio = entities.Count() / approxPointsCount; + var ratio = entities.Count / approxPointsCount; if (ratio > 1) { var expectedResampledCount = entities diff --git a/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs index 2d52a49..f3546f5 100644 --- a/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Client; using Persistence.Client.Clients.Interfaces; using Persistence.Models; @@ -25,7 +25,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest IEnumerable testSets = Generate(10, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); // act - var response = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + var response = await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // assert Assert.Equal(testSets.Count(), response); @@ -38,10 +38,10 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act - var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue, new CancellationToken()); + var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue, CancellationToken.None); // assert Assert.NotNull(response); @@ -55,7 +55,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); string[] props = ["A"]; // act @@ -64,13 +64,13 @@ public class TimestampedSetControllerTest : BaseIntegrationTest // assert Assert.NotNull(response); Assert.Equal(count, response.Count()); - foreach ( var item in response ) - { - Assert.Single(item.Set); - var kv = item.Set.First(); - Assert.Equal("A", kv.Key); - } - } + foreach (var item in response) + { + Assert.Single(item.Set); + var kv = item.Set.First(); + Assert.Equal("A", kv.Key); + } + } [Fact] public async Task Get_geDate() @@ -80,15 +80,15 @@ public class TimestampedSetControllerTest : BaseIntegrationTest int count = 10; var dateMin = DateTimeOffset.Now; var dateMax = DateTimeOffset.Now.AddSeconds(count); - IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7))); + var insertResponse = await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var tail = testSets.OrderBy(t => t.Timestamp).Skip(count / 2).Take(int.MaxValue); var geDate = tail.First().Timestamp; var tolerance = TimeSpan.FromSeconds(1); var expectedCount = tail.Count(); // act - var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue, new CancellationToken()); + var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue, CancellationToken.None); // assert Assert.NotNull(response); @@ -104,7 +104,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var expectedCount = count / 2; // act @@ -124,7 +124,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest var expectedCount = 1; int count = 10 + expectedCount; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act var response = await client.Get(idDiscriminator, null, null, count - expectedCount, count, new CancellationToken()); @@ -141,7 +141,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var expectedCount = 8; // act @@ -159,9 +159,9 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; var dateMin = DateTimeOffset.Now; - var dateMax = DateTimeOffset.Now.AddSeconds(count-1); + var dateMax = DateTimeOffset.Now.AddSeconds(count - 1); IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var tolerance = TimeSpan.FromSeconds(1); // act @@ -180,7 +180,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 144; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken()); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act var response = await client.Count(idDiscriminator, new CancellationToken()); diff --git a/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs b/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs index 9795a2d..731ec9e 100644 --- a/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs @@ -1,98 +1,99 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Client; using Persistence.Client.Clients; using Persistence.Client.Clients.Interfaces; using Persistence.Database.Entity; using Persistence.Models; +using System.Net; using Xunit; namespace Persistence.IntegrationTests.Controllers; public class WitsDataControllerTest : BaseIntegrationTest { - private IWitsDataClient witsDataClient; + private IWitsDataClient witsDataClient; - public WitsDataControllerTest(WebAppFactoryFixture factory) : base(factory) - { - var scope = factory.Services.CreateScope(); - var persistenceClientFactory = scope.ServiceProvider - .GetRequiredService(); + public WitsDataControllerTest(WebAppFactoryFixture factory) : base(factory) + { + var scope = factory.Services.CreateScope(); + var persistenceClientFactory = scope.ServiceProvider + .GetRequiredService(); witsDataClient = persistenceClientFactory.GetWitsDataClient(); } - [Fact] - public async Task GetDatesRangeAsync_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetDatesRangeAsync_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var discriminatorId = Guid.NewGuid(); + var discriminatorId = Guid.NewGuid(); - //act - var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); + //act + var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); //assert Assert.NotNull(response); } - [Fact] - public async Task GetPart_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetPart_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var discriminatorId = Guid.NewGuid(); - var dateBegin = DateTimeOffset.UtcNow; - var take = 1; + var discriminatorId = Guid.NewGuid(); + var dateBegin = DateTimeOffset.UtcNow; + var take = 1; - //act - var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); + //act + var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); //assert Assert.NotNull(response); Assert.Empty(response); } - [Fact] - public async Task InsertRange_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task InsertRange_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - //act - await AddRange(); - } + //act + await AddRange(); + } - [Fact] - public async Task GetValuesForGraph_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetValuesForGraph_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var discriminatorId = Guid.NewGuid(); - var dateFrom = DateTimeOffset.UtcNow; - var dateTo = DateTimeOffset.UtcNow; - var approxPointCount = 12; + var discriminatorId = Guid.NewGuid(); + var dateFrom = DateTimeOffset.UtcNow; + var dateTo = DateTimeOffset.UtcNow; + var approxPointCount = 12; - //act - var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); + //act + var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); //assert Assert.NotNull(response); Assert.Empty(response); } - [Fact] - public async Task GetDatesRangeAsync_AfterSave_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetDatesRangeAsync_AfterSave_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var dtos = await AddRange(); - var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; + var dtos = await AddRange(); + var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; - //act - var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); + //act + var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); //assert Assert.NotNull(response); @@ -114,19 +115,19 @@ public class WitsDataControllerTest : BaseIntegrationTest Assert.Equal(expectedDateTo, actualDateTo); } - [Fact] - public async Task GetPart_AfterSave_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetPart_AfterSave_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var dtos = await AddRange(); - var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; - var dateBegin = dtos.FirstOrDefault()!.Timestamped; - var take = 1; + var dtos = await AddRange(); + var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; + var dateBegin = dtos.FirstOrDefault()!.Timestamped; + var take = 1; - //act - var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); + //act + var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); //assert Assert.NotNull(response); @@ -137,26 +138,26 @@ public class WitsDataControllerTest : BaseIntegrationTest var actualDto = response.FirstOrDefault(); Assert.Equal(expectedDto?.DiscriminatorId, actualDto?.DiscriminatorId); - var expectedValueDto = expectedDto?.Values.FirstOrDefault(); - var actualValueDto = actualDto?.Values.FirstOrDefault(); - Assert.Equal(expectedValueDto?.ItemId, actualValueDto?.ItemId); - Assert.Equal(expectedValueDto?.RecordId, actualValueDto?.RecordId); - } + var expectedValueDto = expectedDto?.Values.FirstOrDefault(); + var actualValueDto = actualDto?.Values.FirstOrDefault(); + Assert.Equal(expectedValueDto?.ItemId, actualValueDto?.ItemId); + Assert.Equal(expectedValueDto?.RecordId, actualValueDto?.RecordId); + } - [Fact] - public async Task GetValuesForGraph_AfterSave_returns_success() - { - //arrange - dbContext.CleanupDbSet(); + [Fact] + public async Task GetValuesForGraph_AfterSave_returns_success() + { + //arrange + dbContext.CleanupDbSet(); - var dtos = await AddRange(37); - var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; - var dateFrom = dtos.Select(e => e.Timestamped).Min(); - var dateTo = dtos.Select(e => e.Timestamped).Max(); - var approxPointCount = 12; + var dtos = await AddRange(37); + var discriminatorId = dtos.FirstOrDefault()!.DiscriminatorId; + var dateFrom = dtos.Select(e => e.Timestamped).Min(); + var dateTo = dtos.Select(e => e.Timestamped).Max(); + var approxPointCount = 12; - //act - var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); + //act + var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); //assert Assert.NotNull(response); @@ -181,10 +182,10 @@ public class WitsDataControllerTest : BaseIntegrationTest RecordId = -1, // < 0 ItemId = 101, // > 100 Value = string.Empty - } - } - } - }; + } + } + } + }; try { @@ -198,37 +199,37 @@ public class WitsDataControllerTest : BaseIntegrationTest } } - private async Task> AddRange(int countToCreate = 10) - { - var dtos = new List(); - var discriminatorId = Guid.NewGuid(); - var timestamped = DateTimeOffset.UtcNow; - for (var i = 0; i < countToCreate; i++) - { - var random = new Random(); - dtos.Add(new WitsDataDto() - { - DiscriminatorId = discriminatorId, - Timestamped = timestamped.AddSeconds(i), - Values = new List() - { - new WitsValueDto() - { - RecordId = i + 1, - ItemId = i + 1, - Value = random.Next(1, 100) - } - } - }); - } + private async Task> AddRange(int countToCreate = 10) + { + var dtos = new List(); + var discriminatorId = Guid.NewGuid(); + var timestamped = DateTimeOffset.UtcNow; + for (var i = 0; i < countToCreate; i++) + { + var random = new Random(); + dtos.Add(new WitsDataDto() + { + DiscriminatorId = discriminatorId, + Timestamped = timestamped.AddSeconds(i), + Values = new List() + { + new WitsValueDto() + { + RecordId = i + 1, + ItemId = i + 1, + Value = random.Next(1, 100) + } + } + }); + } - //act - var response = await witsDataClient.AddRange(dtos, CancellationToken.None); + //act + var response = await witsDataClient.AddRange(dtos, CancellationToken.None); //assert var count = dtos.SelectMany(e => e.Values).Count(); Assert.Equal(count, response); - return dtos; - } + return dtos; + } } diff --git a/Persistence.IntegrationTests/DbConnection.cs b/Persistence.IntegrationTests/DbConnection.cs index f9c7623..ac733fa 100644 --- a/Persistence.IntegrationTests/DbConnection.cs +++ b/Persistence.IntegrationTests/DbConnection.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Persistence.IntegrationTests; +namespace Persistence.IntegrationTests; public class DbConnection { public string Host { get; set; } = null!; diff --git a/Persistence.IntegrationTests/EFCoreExtensions.cs b/Persistence.IntegrationTests/EFCoreExtensions.cs index b41b2d6..4e20423 100644 --- a/Persistence.IntegrationTests/EFCoreExtensions.cs +++ b/Persistence.IntegrationTests/EFCoreExtensions.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Persistence.Database.Model; namespace Persistence.IntegrationTests; public static class EFCoreExtensions diff --git a/Persistence.IntegrationTests/Extensions/EFCoreExtensions.cs b/Persistence.IntegrationTests/Extensions/EFCoreExtensions.cs deleted file mode 100644 index c068a30..0000000 --- a/Persistence.IntegrationTests/Extensions/EFCoreExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Persistence.Database; -using Persistence.Database.Model; - -namespace Persistence.IntegrationTests.Extensions; - -public static class EFCoreExtensions -{ - public static void CleanupDbSet(this PersistenceDbContext dbContext) - where T : class - { - var dbset = dbContext.Set(); - dbset.RemoveRange(dbset); - dbContext.SaveChanges(); - } -} diff --git a/Persistence.IntegrationTests/TestHttpClientFactory.cs b/Persistence.IntegrationTests/TestHttpClientFactory.cs index 287498d..a158b10 100644 --- a/Persistence.IntegrationTests/TestHttpClientFactory.cs +++ b/Persistence.IntegrationTests/TestHttpClientFactory.cs @@ -1,19 +1,19 @@ namespace Persistence.IntegrationTests { - /// - /// Фабрика HTTP клиентов для интеграционных тестов - /// - public class TestHttpClientFactory : IHttpClientFactory - { - private readonly WebAppFactoryFixture factory; + /// + /// Фабрика HTTP клиентов для интеграционных тестов + /// + public class TestHttpClientFactory : IHttpClientFactory + { + private readonly WebAppFactoryFixture factory; - public TestHttpClientFactory(WebAppFactoryFixture factory) - { - this.factory = factory; - } - public HttpClient CreateClient(string name) - { - return factory.CreateClient(); - } - } + public TestHttpClientFactory(WebAppFactoryFixture factory) + { + this.factory = factory; + } + public HttpClient CreateClient(string name) + { + return factory.CreateClient(); + } + } } diff --git a/Persistence.IntegrationTests/WebAppFactoryFixture.cs b/Persistence.IntegrationTests/WebAppFactoryFixture.cs index e557034..535236f 100644 --- a/Persistence.IntegrationTests/WebAppFactoryFixture.cs +++ b/Persistence.IntegrationTests/WebAppFactoryFixture.cs @@ -17,16 +17,16 @@ public class WebAppFactoryFixture : WebApplicationFactory private string connectionString = string.Empty; protected override void ConfigureWebHost(IWebHostBuilder builder) - { + { builder.ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.Tests.json"); - var dbConnection = config.Build().GetSection("DbConnection").Get()!; - connectionString = dbConnection.GetConnectionString(); - }); + var dbConnection = config.Build().GetSection("DbConnection").Get()!; + connectionString = dbConnection.GetConnectionString(); + }); - builder.ConfigureServices(services => + builder.ConfigureServices(services => { var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); if (descriptor != null) @@ -45,7 +45,7 @@ public class WebAppFactoryFixture : WebApplicationFactory services.AddSingleton(); - var serviceProvider = services.BuildServiceProvider(); + var serviceProvider = services.BuildServiceProvider(); using var scope = serviceProvider.CreateScope(); var scopedServices = scope.ServiceProvider; @@ -53,7 +53,7 @@ public class WebAppFactoryFixture : WebApplicationFactory var dbContext = scopedServices.GetRequiredService(); dbContext.Database.EnsureCreatedAndMigrated(); dbContext.SaveChanges(); - }); + }); } public override async ValueTask DisposeAsync() @@ -64,5 +64,7 @@ public class WebAppFactoryFixture : WebApplicationFactory .Options); await dbContext.Database.EnsureDeletedAsync(); + + GC.SuppressFinalize(this); } } diff --git a/Persistence.Repository/CyclicArray.cs b/Persistence.Repository/CyclicArray.cs index fa6d074..1de7a5b 100644 --- a/Persistence.Repository/CyclicArray.cs +++ b/Persistence.Repository/CyclicArray.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections; namespace Persistence.Repository; /// @@ -134,20 +129,20 @@ public class CyclicArray : IEnumerable /// public IEnumerator GetEnumerator() - => new CyclycListEnumerator(array, current, used); + => new CyclicListEnumerator(array, current, used); /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - class CyclycListEnumerator : IEnumerator + class CyclicListEnumerator : IEnumerator { private readonly Te[] array; private readonly int used; private readonly int first; private int current = -1; - public CyclycListEnumerator(Te[] array, int first, int used) + public CyclicListEnumerator(Te[] array, int first, int used) { this.array = new Te[array.Length]; array.CopyTo(this.array, 0); diff --git a/Persistence.Repository/DependencyInjection.cs b/Persistence.Repository/DependencyInjection.cs index 7a96217..bb2f799 100644 --- a/Persistence.Repository/DependencyInjection.cs +++ b/Persistence.Repository/DependencyInjection.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection; using Persistence.Database.Model; using Persistence.Models; using Persistence.Repositories; -using Persistence.Repository.Data; using Persistence.Repository.Repositories; namespace Persistence.Repository; @@ -33,7 +32,7 @@ public static class DependencyInjection services.AddTransient, TimeSeriesDataCachedRepository>(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); return services; diff --git a/Persistence.Repository/Extensions/EFExtensionsSortBy.cs b/Persistence.Repository/Extensions/EFExtensionsSortBy.cs index 03b9c65..97ca992 100644 --- a/Persistence.Repository/Extensions/EFExtensionsSortBy.cs +++ b/Persistence.Repository/Extensions/EFExtensionsSortBy.cs @@ -44,7 +44,7 @@ public static class EFExtensionsSortBy var name = propertyInfo.Name.ToLower(); ParameterExpression arg = Expression.Parameter(type, "x"); MemberExpression property = Expression.Property(arg, propertyInfo.Name); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); + var selector = Expression.Lambda(property, [arg]); var typeAccessor = new TypeAccessor { KeySelector = selector, @@ -200,7 +200,7 @@ public static class EFExtensionsSortBy : orderByAscending; var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, lambdaExpression })!; + .Invoke(genericMethod, [query, lambdaExpression])!; return newQuery; } @@ -226,7 +226,6 @@ public static class EFExtensionsSortBy LambdaExpression? lambdaExpression = null; - // TODO: Устранить дублирование кода if (propertyName.Contains('.')) { Type type = rootType; @@ -261,7 +260,7 @@ public static class EFExtensionsSortBy : orderByAscending; var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, lambdaExpression })!; + .Invoke(genericMethod, [query, lambdaExpression])!; return newQuery; } } \ No newline at end of file diff --git a/Persistence.Repository/QueryBuilders.cs b/Persistence.Repository/QueryBuilders.cs index 6070a8a..a0e17be 100644 --- a/Persistence.Repository/QueryBuilders.cs +++ b/Persistence.Repository/QueryBuilders.cs @@ -29,7 +29,7 @@ public static class QueryBuilders return query; } - public static IQueryable Apply(this IQueryable query,DateTimeOffset momentUtc) + public static IQueryable Apply(this IQueryable query, DateTimeOffset momentUtc) where TEntity : class, IChangeLog { momentUtc = momentUtc.ToUniversalTime(); @@ -40,7 +40,7 @@ public static class QueryBuilders return query; } - + public static async Task> ApplyPagination( this IQueryable query, diff --git a/Persistence.Repository/Repositories/ChangeLogRepository.cs b/Persistence.Repository/Repositories/ChangeLogRepository.cs index dc3f5eb..aecb62c 100644 --- a/Persistence.Repository/Repositories/ChangeLogRepository.cs +++ b/Persistence.Repository/Repositories/ChangeLogRepository.cs @@ -9,7 +9,7 @@ using UuidExtensions; namespace Persistence.Repository.Repositories; public class ChangeLogRepository : IChangeLogRepository { - private DbContext db; + private readonly DbContext db; public ChangeLogRepository(DbContext db) { @@ -123,11 +123,11 @@ public class ChangeLogRepository : IChangeLogRepository return result; - + } public async Task> GetByDate( - Guid idDiscriminator, + Guid idDiscriminator, DateTimeOffset momentUtc, SectionPartRequest filterRequest, PaginationRequest paginationRequest, @@ -195,7 +195,7 @@ public class ChangeLogRepository : IChangeLogRepository return datesOnly; } - private ChangeLog CreateEntityFromDto(Guid idAuthor, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto) + private static ChangeLog CreateEntityFromDto(Guid idAuthor, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto) { var entity = new ChangeLog() { diff --git a/Persistence.Repository/Repositories/ParameterRepository.cs b/Persistence.Repository/Repositories/ParameterRepository.cs index 325c08c..38f3ef0 100644 --- a/Persistence.Repository/Repositories/ParameterRepository.cs +++ b/Persistence.Repository/Repositories/ParameterRepository.cs @@ -1,6 +1,5 @@ using Mapster; using Microsoft.EntityFrameworkCore; -using Newtonsoft.Json.Linq; using Persistence.Database.Entity; using Persistence.Models; using Persistence.Repositories; @@ -8,80 +7,80 @@ using Persistence.Repositories; namespace Persistence.Repository.Repositories; public class ParameterRepository : IParameterRepository { - private DbContext db; + private DbContext db; - public ParameterRepository(DbContext db) - { - this.db = db; - } + public ParameterRepository(DbContext db) + { + this.db = db; + } - protected virtual IQueryable GetQueryReadOnly() => db.Set(); + protected virtual IQueryable GetQueryReadOnly() => db.Set(); - public async Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token) - { - var query = GetQueryReadOnly() - .Where(e => e.DiscriminatorId == idDiscriminator) - .GroupBy(e => 1) - .Select(group => new - { - Min = group.Min(e => e.Timestamp), - Max = group.Max(e => e.Timestamp), - }); - var values = await query.FirstOrDefaultAsync(token); - var result = new DatesRangeDto() - { - From = values?.Min ?? DateTimeOffset.MinValue, - To = values?.Max ?? DateTimeOffset.MaxValue - }; + public async Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token) + { + var query = GetQueryReadOnly() + .Where(e => e.DiscriminatorId == idDiscriminator) + .GroupBy(e => 1) + .Select(group => new + { + Min = group.Min(e => e.Timestamp), + Max = group.Max(e => e.Timestamp), + }); + var values = await query.FirstOrDefaultAsync(token); + var result = new DatesRangeDto() + { + From = values?.Min ?? DateTimeOffset.MinValue, + To = values?.Max ?? DateTimeOffset.MaxValue + }; - return result; - } + return result; + } - public async Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token) - { - var query = GetQueryReadOnly(); - var universalDate = dateBegin.ToUniversalTime(); - var entities = await query - .Where(e => e.DiscriminatorId == idDiscriminator && e.Timestamp >= universalDate) - .Take(take) - .ToArrayAsync(token); - var dtos = entities.Select(e => e.Adapt()); + public async Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token) + { + var query = GetQueryReadOnly(); + var universalDate = dateBegin.ToUniversalTime(); + var entities = await query + .Where(e => e.DiscriminatorId == idDiscriminator && e.Timestamp >= universalDate) + .Take(take) + .ToArrayAsync(token); + var dtos = entities.Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, - int approxPointsCount, int? ratio, CancellationToken token) - { - var query = db.Set().AsNoTracking(); - var universalDateFrom = dateFrom.ToUniversalTime(); - var universalDateTo = dateTo.ToUniversalTime(); + public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, + int approxPointsCount, int? ratio, CancellationToken token) + { + var query = db.Set().AsNoTracking(); + var universalDateFrom = dateFrom.ToUniversalTime(); + var universalDateTo = dateTo.ToUniversalTime(); - query = query - .Where(e => e.DiscriminatorId == discriminatorId) - .Where(e => e.Timestamp >= universalDateFrom && e.Timestamp <= universalDateTo) - .OrderBy(e => e.Timestamp); - if (ratio != null) - { - query = query.Where(e => ((int) (e.Timestamp - dateFrom).TotalSeconds) % ratio == 0); - } + query = query + .Where(e => e.DiscriminatorId == discriminatorId) + .Where(e => e.Timestamp >= universalDateFrom && e.Timestamp <= universalDateTo) + .OrderBy(e => e.Timestamp); + if (ratio != null) + { + query = query.Where(e => ((int)(e.Timestamp - dateFrom).TotalSeconds) % ratio == 0); + } - var entities = await query - .Take((int)(2.5 * approxPointsCount)) - .ToArrayAsync(token); + var entities = await query + .Take((int)(2.5 * approxPointsCount)) + .ToArrayAsync(token); - var dtos = entities.Select(e => e.Adapt()); + var dtos = entities.Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task AddRange(IEnumerable dtos, CancellationToken token) - { - var entities = dtos.Select(e => e.Adapt()); + public async Task AddRange(IEnumerable dtos, CancellationToken token) + { + var entities = dtos.Select(e => e.Adapt()); - await db.Set().AddRangeAsync(entities, token); - var result = await db.SaveChangesAsync(token); + await db.Set().AddRangeAsync(entities, token); + var result = await db.SaveChangesAsync(token); - return result; - } + return result; + } } diff --git a/Persistence.Repository/Repositories/SetpointRepository.cs b/Persistence.Repository/Repositories/SetpointRepository.cs index f0e921f..800d7fa 100644 --- a/Persistence.Repository/Repositories/SetpointRepository.cs +++ b/Persistence.Repository/Repositories/SetpointRepository.cs @@ -6,100 +6,100 @@ using Persistence.Repositories; namespace Persistence.Repository.Repositories { - public class SetpointRepository : ISetpointRepository - { - private DbContext db; - public SetpointRepository(DbContext db) - { - this.db = db; - } + public class SetpointRepository : ISetpointRepository + { + private readonly DbContext db; + public SetpointRepository(DbContext db) + { + this.db = db; + } - protected virtual IQueryable GetQueryReadOnly() => db.Set(); + protected virtual IQueryable GetQueryReadOnly() => db.Set(); - public async Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token) - { - var query = GetQueryReadOnly(); - var entities = await query - .Where(e => setpointKeys.Contains(e.Key)) - .ToArrayAsync(token); - var dtos = entities.Select(e => e.Adapt()); + public async Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token) + { + var query = GetQueryReadOnly(); + var entities = await query + .Where(e => setpointKeys.Contains(e.Key)) + .ToArrayAsync(token); + var dtos = entities.Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) - { - var query = GetQueryReadOnly(); - var entities = await query - .Where(e => setpointKeys.Contains(e.Key)) - .ToArrayAsync(token); - var filteredEntities = entities - .GroupBy(e => e.Key) - .Select(e => e.OrderBy(o => o.Created)) - .Select(e => e.Where(e => e.Created <= historyMoment).Last()); - var dtos = filteredEntities - .Select(e => e.Adapt()); + public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) + { + var query = GetQueryReadOnly(); + var entities = await query + .Where(e => setpointKeys.Contains(e.Key)) + .ToArrayAsync(token); + var filteredEntities = entities + .GroupBy(e => e.Key) + .Select(e => e.OrderBy(o => o.Created)) + .Select(e => e.Where(e => e.Created <= historyMoment).Last()); + var dtos = filteredEntities + .Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) - { - var query = GetQueryReadOnly(); - var entities = await query - .Where(e => e.Created >= dateBegin) - .Take(take) - .ToArrayAsync(token); - var dtos = entities - .Select(e => e.Adapt()); + public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var query = GetQueryReadOnly(); + var entities = await query + .Where(e => e.Created >= dateBegin) + .Take(take) + .ToArrayAsync(token); + var dtos = entities + .Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task GetDatesRangeAsync(CancellationToken token) - { - var query = GetQueryReadOnly() - .GroupBy(e => 1) - .Select(group => new - { - Min = group.Min(e => e.Created), - Max = group.Max(e => e.Created), - }); - var values = await query.FirstOrDefaultAsync(token); - var result = new DatesRangeDto() - { - From = values?.Min ?? DateTimeOffset.MinValue, - To = values?.Max ?? DateTimeOffset.MaxValue - }; + public async Task GetDatesRangeAsync(CancellationToken token) + { + var query = GetQueryReadOnly() + .GroupBy(e => 1) + .Select(group => new + { + Min = group.Min(e => e.Created), + Max = group.Max(e => e.Created), + }); + var values = await query.FirstOrDefaultAsync(token); + var result = new DatesRangeDto() + { + From = values?.Min ?? DateTimeOffset.MinValue, + To = values?.Max ?? DateTimeOffset.MaxValue + }; - return result; - } + return result; + } - public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) - { - var query = GetQueryReadOnly(); - var entities = await query - .Where(e => setpointKeys.Contains(e.Key)) - .ToArrayAsync(token); - var dtos = entities - .GroupBy(e => e.Key) - .ToDictionary(e => e.Key, v => v.Select(z => z.Adapt())); + public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) + { + var query = GetQueryReadOnly(); + var entities = await query + .Where(e => setpointKeys.Contains(e.Key)) + .ToArrayAsync(token); + var dtos = entities + .GroupBy(e => e.Key) + .ToDictionary(e => e.Key, v => v.Select(z => z.Adapt())); - return dtos; - } + return dtos; + } - public async Task Add(Guid setpointKey, object newValue, Guid idUser, CancellationToken token) - { - var entity = new Setpoint() - { - Key = setpointKey, - Value = newValue, - IdUser = idUser, - Created = DateTimeOffset.UtcNow - }; + public async Task Add(Guid setpointKey, object newValue, Guid idUser, CancellationToken token) + { + var entity = new Setpoint() + { + Key = setpointKey, + Value = newValue, + IdUser = idUser, + Created = DateTimeOffset.UtcNow + }; - await db.Set().AddAsync(entity, token); - await db.SaveChangesAsync(token); - } - } + await db.Set().AddAsync(entity, token); + await db.SaveChangesAsync(token); + } + } } diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index 4659da0..db59f63 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -1,178 +1,178 @@ -using Mapster; +using Mapster; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Persistence.Database.Entity; using Persistence.Models; using Persistence.Models.Requests; using Persistence.Repositories; -using Persistence.Repository.Extensions; +using UuidExtensions; namespace Persistence.Repository.Repositories { - public class TechMessagesRepository : ITechMessagesRepository - { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; - private const int CacheExpirationInMinutes = 60; - private readonly IMemoryCache memoryCache; - private DbContext db; + public class TechMessagesRepository : ITechMessagesRepository + { + private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; + private const int CacheExpirationInMinutes = 60; + private readonly IMemoryCache memoryCache; + private readonly DbContext db; - public TechMessagesRepository(DbContext db, IMemoryCache memoryCache) - { - this.memoryCache = memoryCache; - this.db = db; - } + public TechMessagesRepository(DbContext db, IMemoryCache memoryCache) + { + this.memoryCache = memoryCache; + this.db = db; + } - protected virtual IQueryable GetQueryReadOnly() => db.Set() - .Include(e => e.System); + protected virtual IQueryable GetQueryReadOnly() => db.Set() + .Include(e => e.System); - public async Task> GetPage(PaginationRequest request, CancellationToken token) - { - var query = GetQueryReadOnly(); - var count = await query.CountAsync(token); + public async Task> GetPage(PaginationRequest request, CancellationToken token) + { + var query = GetQueryReadOnly(); + var count = await query.CountAsync(token); - var sort = request.SortSettings != string.Empty - ? request.SortSettings - : nameof(TechMessage.Timestamp); - var entities = await query - .SortBy(request.SortSettings!) - .Skip(request.Skip) - .Take(request.Take) - .ToArrayAsync(token); + var sort = request.SortSettings != string.Empty + ? request.SortSettings! + : nameof(TechMessage.Timestamp); + var entities = await query + .SortBy(sort) + .Skip(request.Skip) + .Take(request.Take) + .ToArrayAsync(token); - var dto = new PaginationContainer() - { - Skip = request.Skip, - Take = request.Take, - Count = count, - Items = entities.Select(e => e.Adapt()) - }; + var dto = new PaginationContainer() + { + Skip = request.Skip, + Take = request.Take, + Count = count, + Items = entities.Select(e => e.Adapt()) + }; - return dto; - } + return dto; + } - public async Task> GetStatistics(IEnumerable autoDrillingSystem, IEnumerable categoryIds, CancellationToken token) - { - var query = GetQueryReadOnly(); - var systems = autoDrillingSystem.Select(s => s.ToLower().Trim()); - var result = await query - .Where(e => systems.Count() == 0 || systems.Contains(e.System.Name.ToLower().Trim())) - .GroupBy(e => e.System.Name, (key, group) => new - { - System = key, - Categories = group - .Where(g => categoryIds.Count() == 0 || categoryIds.Contains(g.CategoryId)) - }) - .ToArrayAsync(token); + public async Task> GetStatistics(IEnumerable autoDrillingSystem, IEnumerable categoryIds, CancellationToken token) + { + var query = GetQueryReadOnly(); + var systems = autoDrillingSystem.Select(s => s.ToLower().Trim()); + var result = await query + .Where(e => !systems.Any() || systems.Contains(e.System.Name.ToLower().Trim())) + .GroupBy(e => e.System.Name, (key, group) => new + { + System = key, + Categories = group + .Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId)) + }) + .ToArrayAsync(token); - var entities = new List(); - foreach (var e in result) - { - var categories = e.Categories - .GroupBy(g => g.CategoryId) - .ToDictionary(c => c.Key, v => v.Count()); - var entity = new MessagesStatisticDto() - { - System = e.System, - Categories = categories - }; - entities.Add(entity); - } + var entities = new List(); + foreach (var e in result) + { + var categories = e.Categories + .GroupBy(g => g.CategoryId) + .ToDictionary(c => c.Key, v => v.Count()); + var entity = new MessagesStatisticDto() + { + System = e.System, + Categories = categories + }; + entities.Add(entity); + } - return entities; - } + return entities; + } - public async Task> GetSystems(CancellationToken token) - { - var entities = await GetDrillingSystems(token); - var result = entities.Select(e => e.Name); + public async Task> GetSystems(CancellationToken token) + { + var entities = await GetDrillingSystems(token); + var result = entities.Select(e => e.Name); - return result; - } + return result; + } - public async Task AddRange(IEnumerable dtos, Guid userId, CancellationToken token) - { + public async Task AddRange(IEnumerable dtos, Guid userId, CancellationToken token) + { - var entities = new List(); - foreach (var dto in dtos) - { - var entity = dto.Adapt(); - var systems = await GetDrillingSystems(token); - var systemId = systems.FirstOrDefault(e => e.Name.ToLower().Trim() == dto.System.ToLower().Trim())?.SystemId - ?? await CreateDrillingSystem(dto.System, token); + var entities = new List(); + foreach (var dto in dtos) + { + var entity = dto.Adapt(); + var systems = await GetDrillingSystems(token); + var systemId = systems.FirstOrDefault(e => e.Name.ToLower().Trim() == dto.System.ToLower().Trim())?.SystemId + ?? await CreateDrillingSystem(dto.System, token); - entity.SystemId = systemId; - entity.UserId = userId; + entity.SystemId = systemId; + entity.UserId = userId; - entities.Add(entity); - } + entities.Add(entity); + } - await db.Set().AddRangeAsync(entities, token); - var result = await db.SaveChangesAsync(token); + await db.Set().AddRangeAsync(entities, token); + var result = await db.SaveChangesAsync(token); - return result; - } + return result; + } - public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) - { - var query = GetQueryReadOnly(); - var entities = await query - .Where(e => e.Timestamp >= dateBegin) - .Take(take) - .ToArrayAsync(token); - var dtos = entities - .Select(e => e.Adapt()); + public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var query = GetQueryReadOnly(); + var entities = await query + .Where(e => e.Timestamp >= dateBegin) + .Take(take) + .ToArrayAsync(token); + var dtos = entities + .Select(e => e.Adapt()); - return dtos; - } + return dtos; + } - public async Task GetDatesRangeAsync(CancellationToken token) - { - var query = GetQueryReadOnly() - .GroupBy(e => 1) - .Select(group => new - { - Min = group.Min(e => e.Timestamp), - Max = group.Max(e => e.Timestamp), - }); - var values = await query.FirstOrDefaultAsync(token); - var result = new DatesRangeDto() - { - From = values?.Min ?? DateTimeOffset.MinValue, - To = values?.Max ?? DateTimeOffset.MaxValue - }; + public async Task GetDatesRangeAsync(CancellationToken token) + { + var query = GetQueryReadOnly() + .GroupBy(e => 1) + .Select(group => new + { + Min = group.Min(e => e.Timestamp), + Max = group.Max(e => e.Timestamp), + }); + var values = await query.FirstOrDefaultAsync(token); + var result = new DatesRangeDto() + { + From = values?.Min ?? DateTimeOffset.MinValue, + To = values?.Max ?? DateTimeOffset.MaxValue + }; - return result; - } + return result; + } - private async Task> GetDrillingSystems(CancellationToken token) - { - var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => - { - f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + private async Task> GetDrillingSystems(CancellationToken token) + { + var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + { + f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); - var query = db.Set(); - var entities = await query.ToListAsync(token); - var dtos = entities.Select(e => e.Adapt()); + var query = db.Set(); + var entities = await query.ToListAsync(token); + var dtos = entities.Select(e => e.Adapt()); - return dtos; - }); + return dtos; + }); - return systems!; - } - private async Task CreateDrillingSystem(string name, CancellationToken token) - { - memoryCache.Remove(SystemCacheKey); + return systems!; + } + private async Task CreateDrillingSystem(string name, CancellationToken token) + { + memoryCache.Remove(SystemCacheKey); - var entity = new Database.Entity.DrillingSystem() - { - SystemId = default, - Name = name.ToLower().Trim() - }; + var entity = new DrillingSystem() + { + SystemId = Uuid7.Guid(), + Name = name.ToLower().Trim() + }; - await db.Set().AddAsync(entity); - await db.SaveChangesAsync(token); + await db.Set().AddAsync(entity, token); + await db.SaveChangesAsync(token); - return entity.SystemId; - } - } + return entity.SystemId; + } + } } diff --git a/Persistence.Repository/Repositories/TimeSeriesDataCachedRepository.cs b/Persistence.Repository/Repositories/TimeSeriesDataCachedRepository.cs index 2037f09..2690c09 100644 --- a/Persistence.Repository/Repositories/TimeSeriesDataCachedRepository.cs +++ b/Persistence.Repository/Repositories/TimeSeriesDataCachedRepository.cs @@ -1,6 +1,4 @@ -using Mapster; -using Microsoft.EntityFrameworkCore; -using Newtonsoft.Json.Linq; +using Microsoft.EntityFrameworkCore; using Persistence.Database.Model; using Persistence.Models; @@ -24,19 +22,19 @@ public class TimeSeriesDataCachedRepository : TimeSeriesDataRepos { return; } - + FirstByDate = firstDateItem; var dtos = await base.GetLastAsync(CacheItemsCount, CancellationToken.None); - dtos = dtos.OrderBy(d => d.Date); - LastData.AddRange(dtos); + dtos = dtos.OrderBy(d => d.Date); + LastData.AddRange(dtos); }).Wait(); } public override async Task> GetGtDate(DateTimeOffset dateBegin, CancellationToken token) { - if (LastData.Count() == 0 || LastData[0].Date > dateBegin) + if (LastData.Count == 0 || LastData[0].Date > dateBegin) { var dtos = await base.GetGtDate(dateBegin, token); return dtos; @@ -53,7 +51,7 @@ public class TimeSeriesDataCachedRepository : TimeSeriesDataRepos var result = await base.AddRange(dtos, token); if (result > 0) { - + dtos = dtos.OrderBy(x => x.Date); FirstByDate = dtos.First(); @@ -75,12 +73,12 @@ public class TimeSeriesDataCachedRepository : TimeSeriesDataRepos From = FirstByDate.Date, To = LastData[^1].Date }; - }); + }); } public override async Task> GetResampledData( - DateTimeOffset dateBegin, - double intervalSec = 600d, + DateTimeOffset dateBegin, + double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) { diff --git a/Persistence.Repository/Repositories/TimeSeriesDataRepository.cs b/Persistence.Repository/Repositories/TimeSeriesDataRepository.cs index 0e58c76..ba60f27 100644 --- a/Persistence.Repository/Repositories/TimeSeriesDataRepository.cs +++ b/Persistence.Repository/Repositories/TimeSeriesDataRepository.cs @@ -9,7 +9,7 @@ public class TimeSeriesDataRepository : ITimeSeriesDataRepository where TEntity : class, ITimestampedData, new() where TDto : class, ITimeSeriesAbstractDto, new() { - private DbContext db; + private readonly DbContext db; public TimeSeriesDataRepository(DbContext db) { @@ -78,8 +78,8 @@ public class TimeSeriesDataRepository : ITimeSeriesDataRepository } public async virtual Task> GetResampledData( - DateTimeOffset dateBegin, - double intervalSec = 600d, + DateTimeOffset dateBegin, + double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) { diff --git a/Persistence.Repository/Repositories/TimestampedSetRepository.cs b/Persistence.Repository/Repositories/TimestampedSetRepository.cs index a67b823..158bfd7 100644 --- a/Persistence.Repository/Repositories/TimestampedSetRepository.cs +++ b/Persistence.Repository/Repositories/TimestampedSetRepository.cs @@ -77,12 +77,12 @@ public class TimestampedSetRepository : ITimestampedSetRepository { var query = db.Set() .GroupBy(entity => entity.IdDiscriminator) - .Select(group => new - { + .Select(group => new + { Min = group.Min(entity => entity.Timestamp), Max = group.Max(entity => entity.Timestamp), }); - + var item = await query.FirstOrDefaultAsync(token); if (item is null) return null; diff --git a/Persistence/API/IChangeLogApi.cs b/Persistence/API/IChangeLogApi.cs index 4a548bf..25b5158 100644 --- a/Persistence/API/IChangeLogApi.cs +++ b/Persistence/API/IChangeLogApi.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Models.Requests; @@ -50,13 +49,13 @@ public interface IChangeLogApi : ISyncWithDiscriminatorApi Task GetChangeLogForDate(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); - /// - /// Добавить одну запись - /// - /// - /// - /// - /// + /// + /// Добавить одну запись + /// + /// + /// + /// + /// Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token); /// diff --git a/Persistence/API/IDictionaryElementApi.cs b/Persistence/API/IDictionaryElementApi.cs deleted file mode 100644 index fac7870..0000000 --- a/Persistence/API/IDictionaryElementApi.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Microsoft.AspNetCore.Mvc; - -namespace Persistence.API; - -/// -/// Интерфейс для API, предназначенного для работы с элементами справочников -/// -public interface IDictionaryElementApi where TDto : class, new() -{ - /// - /// Получить все данные справочника - /// - /// ключ справочника - /// - /// - Task>> Get(Guid dictionaryKey, CancellationToken token); - - /// - /// Добавить элемент в справочник - /// - /// ключ справочника - /// - /// - /// - Task> Add(Guid dictionaryKey, TDto dto, CancellationToken token); - - /// - /// Изменить одну запись - /// - /// ключ справочника - /// ключ элемента в справочнике - /// - /// - /// - Task> Update(Guid dictionaryKey, Guid dictionaryElementKey, TDto dto, CancellationToken token); - - /// - /// Удалить одну запись - /// - /// ключ справочника - /// ключ элемента в справочнике - /// - /// - Task> Delete(Guid dictionaryKey, Guid dictionaryElementKey, CancellationToken token); -} diff --git a/Persistence/API/ISetpointApi.cs b/Persistence/API/ISetpointApi.cs index b1504a2..9be553e 100644 --- a/Persistence/API/ISetpointApi.cs +++ b/Persistence/API/ISetpointApi.cs @@ -33,12 +33,12 @@ public interface ISetpointApi : ISyncApi /// Task>>> GetLog(IEnumerable setpoitKeys, CancellationToken token); - /// - /// Метод сохранения уставки - /// - /// ключ уставки - /// значение - /// - /// - Task Add(Guid setpointKey, object newValue, CancellationToken token); + /// + /// Метод сохранения уставки + /// + /// ключ уставки + /// значение + /// + /// + Task Add(Guid setpointKey, object newValue, CancellationToken token); } diff --git a/Persistence/API/ISyncWithDiscriminatorApi.cs b/Persistence/API/ISyncWithDiscriminatorApi.cs index 224b8df..eb74533 100644 --- a/Persistence/API/ISyncWithDiscriminatorApi.cs +++ b/Persistence/API/ISyncWithDiscriminatorApi.cs @@ -8,21 +8,21 @@ namespace Persistence.API; /// public interface ISyncWithDiscriminatorApi { - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// количество записей - /// - /// - Task>> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take = 24 * 60 * 60, CancellationToken token = default); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// количество записей + /// + /// + Task>> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take = 24 * 60 * 60, CancellationToken token = default); - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - /// - Task> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + /// + Task> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); } \ No newline at end of file diff --git a/Persistence/API/ITableDataApi.cs b/Persistence/API/ITableDataApi.cs deleted file mode 100644 index e5611a4..0000000 --- a/Persistence/API/ITableDataApi.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Persistence.Models; -using Persistence.Models.Requests; - -namespace Persistence.API; - -/// Интерфейс для API, предназначенного для работы с табличными данными -public interface ITableDataApi - where TDto : class, new() - where TRequest : PaginationRequest -{ - /// - /// Получить страницу списка объектов - /// - /// параметры фильтрации - /// - /// - Task>> GetPage(TRequest request, CancellationToken token); -} diff --git a/Persistence/API/ITimeSeriesBaseDataApi.cs b/Persistence/API/ITimeSeriesBaseDataApi.cs index 480f145..8f80acb 100644 --- a/Persistence/API/ITimeSeriesBaseDataApi.cs +++ b/Persistence/API/ITimeSeriesBaseDataApi.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Mvc; -using Persistence.Models; namespace Persistence.API; @@ -16,9 +15,9 @@ public interface ITimeSeriesBaseDataApi /// /// Task GetResampledData( - DateTimeOffset dateBegin, - double intervalSec = 600d, - int approxPointsCount = 1024, + DateTimeOffset dateBegin, + double intervalSec = 600d, + int approxPointsCount = 1024, CancellationToken token = default); /// diff --git a/Persistence/API/ITimeSeriesDataApi.cs b/Persistence/API/ITimeSeriesDataApi.cs index 51b9332..9dc39a4 100644 --- a/Persistence/API/ITimeSeriesDataApi.cs +++ b/Persistence/API/ITimeSeriesDataApi.cs @@ -1,10 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Persistence.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Persistence.API; diff --git a/Persistence/API/IWitsDataApi.cs b/Persistence/API/IWitsDataApi.cs index a8e5de8..5f41b4b 100644 --- a/Persistence/API/IWitsDataApi.cs +++ b/Persistence/API/IWitsDataApi.cs @@ -8,23 +8,23 @@ namespace Persistence.API; /// public interface IWitsDataApi : ISyncWithDiscriminatorApi { - /// - /// Получить набор параметров (Wits) для построения графика - /// - /// - /// - /// - /// - /// - /// - Task>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, - int approxPointsCount, CancellationToken token); + /// + /// Получить набор параметров (Wits) для построения графика + /// + /// + /// + /// + /// + /// + /// + Task>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, + int approxPointsCount, CancellationToken token); - /// - /// Сохранить набор параметров (Wits) - /// - /// - /// - /// - Task AddRange(IEnumerable dtos, CancellationToken token); + /// + /// Сохранить набор параметров (Wits) + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); } diff --git a/Persistence/EFExtensions.cs b/Persistence/EFExtensions.cs index 00474cc..425e52a 100644 --- a/Persistence/EFExtensions.cs +++ b/Persistence/EFExtensions.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace Persistence; public static class EFExtensions { - struct TypeAcessor + struct TypeAccessor { public LambdaExpression KeySelector { get; set; } public MethodInfo OrderBy { get; set; } @@ -25,7 +20,7 @@ public static class EFExtensions private static readonly MethodInfo methodThenBy = GetExtOrderMethod("ThenBy"); private static readonly MethodInfo methodThenByDescending = GetExtOrderMethod("ThenByDescending"); - private static ConcurrentDictionary> TypePropSelectors { get; set; } = new(); + private static ConcurrentDictionary> TypePropSelectors { get; set; } = new(); private static MethodInfo GetExtOrderMethod(string methodName) => typeof(System.Linq.Queryable) @@ -35,17 +30,17 @@ public static class EFExtensions m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType.IsAssignableTo(typeof(LambdaExpression))) .Single(); - private static Dictionary MakeTypeAcessors(Type type) + private static Dictionary MakeTypeAccessors(Type type) { - var propContainer = new Dictionary(); + var propContainer = new Dictionary(); var properties = type.GetProperties(); foreach (var propertyInfo in properties) { var name = propertyInfo.Name.ToLower(); ParameterExpression arg = Expression.Parameter(type, "x"); MemberExpression property = Expression.Property(arg, propertyInfo.Name); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); - var typeAccessor = new TypeAcessor + var selector = Expression.Lambda(property, [arg]); + var typeAccessor = new TypeAccessor { KeySelector = selector, OrderBy = methodOrderBy.MakeGenericMethod(type, propertyInfo.PropertyType), @@ -99,16 +94,16 @@ public static class EFExtensions string propertyName, bool isDesc) { - var typePropSelector = TypePropSelectors.GetOrAdd(typeof(TSource), MakeTypeAcessors); - var propertyNamelower = propertyName.ToLower(); - var typeAccessor = typePropSelector[propertyNamelower]; + var typePropSelector = TypePropSelectors.GetOrAdd(typeof(TSource), MakeTypeAccessors); + var propertyNameLower = propertyName.ToLower(); + var typeAccessor = typePropSelector[propertyNameLower]; var genericMethod = isDesc ? typeAccessor.OrderByDescending : typeAccessor.OrderBy; var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, typeAccessor.KeySelector })!; + .Invoke(genericMethod, [query, typeAccessor.KeySelector])!; return newQuery; } } diff --git a/Persistence/Models/Configurations/AuthUser.cs b/Persistence/Models/Configurations/AuthUser.cs index 86f11c5..94f65b7 100644 --- a/Persistence/Models/Configurations/AuthUser.cs +++ b/Persistence/Models/Configurations/AuthUser.cs @@ -5,8 +5,8 @@ /// public class AuthUser { - public required string Username { get; set; } - public required string Password { get; set; } - public required string ClientId { get; set; } - public required string GrantType { get; set; } + public required string Username { get; set; } + public required string Password { get; set; } + public required string ClientId { get; set; } + public required string GrantType { get; set; } } diff --git a/Persistence/Models/Configurations/JwtParams.cs b/Persistence/Models/Configurations/JwtParams.cs index d8b7b72..44436ed 100644 --- a/Persistence/Models/Configurations/JwtParams.cs +++ b/Persistence/Models/Configurations/JwtParams.cs @@ -1,18 +1,18 @@ -using System.Text; -using Microsoft.IdentityModel.Tokens; +using Microsoft.IdentityModel.Tokens; +using System.Text; namespace Persistence.Models.Configurations { - public static class JwtParams - { - private static readonly string KeyValue = "супер секретный ключ для шифрования"; - public static SymmetricSecurityKey SecurityKey - { - get { return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(KeyValue)); } - } + public static class JwtParams + { + private static readonly string KeyValue = "супер секретный ключ для шифрования"; + public static SymmetricSecurityKey SecurityKey + { + get { return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(KeyValue)); } + } - public static readonly string Issuer = "a"; + public static readonly string Issuer = "a"; - public static readonly string Audience = "a"; - } + public static readonly string Audience = "a"; + } } diff --git a/Persistence/Models/Configurations/JwtToken.cs b/Persistence/Models/Configurations/JwtToken.cs index f787cc3..ff19aa9 100644 --- a/Persistence/Models/Configurations/JwtToken.cs +++ b/Persistence/Models/Configurations/JwtToken.cs @@ -2,9 +2,9 @@ namespace Persistence.Models.Configurations { - public class JwtToken - { - [JsonPropertyName("access_token")] - public required string AccessToken { get; set; } - } + public class JwtToken + { + [JsonPropertyName("access_token")] + public required string AccessToken { get; set; } + } } diff --git a/Persistence/Models/Configurations/WitsInfo.cs b/Persistence/Models/Configurations/WitsInfo.cs index f096d11..76b2a51 100644 --- a/Persistence/Models/Configurations/WitsInfo.cs +++ b/Persistence/Models/Configurations/WitsInfo.cs @@ -7,9 +7,9 @@ namespace Persistence.Models.Configurations; /// public class WitsInfo { - public int RecordId { get; set; } + public int RecordId { get; set; } - public int ItemId { get; set; } + public int ItemId { get; set; } - public WitsType ValueType { get; set; } + public WitsType ValueType { get; set; } } \ No newline at end of file diff --git a/Persistence.Repository/Data/DataSaubDto.cs b/Persistence/Models/DataSaubDto.cs similarity index 88% rename from Persistence.Repository/Data/DataSaubDto.cs rename to Persistence/Models/DataSaubDto.cs index 518380b..cd547da 100644 --- a/Persistence.Repository/Data/DataSaubDto.cs +++ b/Persistence/Models/DataSaubDto.cs @@ -1,7 +1,4 @@ -using Persistence.Models; -using System.ComponentModel.DataAnnotations.Schema; - -namespace Persistence.Repository.Data; +namespace Persistence.Models; public class DataSaubDto : ITimeSeriesAbstractDto { public DateTimeOffset Date { get; set; } = DateTimeOffset.UtcNow; diff --git a/Persistence/Models/DataWithWellDepthAndSectionDto.cs b/Persistence/Models/DataWithWellDepthAndSectionDto.cs index 7939dd0..033ddb8 100644 --- a/Persistence/Models/DataWithWellDepthAndSectionDto.cs +++ b/Persistence/Models/DataWithWellDepthAndSectionDto.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Persistence.Models; +namespace Persistence.Models; /// /// Dto для хранения записей, содержащих начальную и конечную глубину забоя, а также секцию diff --git a/Persistence/Models/DatesRangeDto.cs b/Persistence/Models/DatesRangeDto.cs index b8f278e..1df7369 100644 --- a/Persistence/Models/DatesRangeDto.cs +++ b/Persistence/Models/DatesRangeDto.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Persistence.Models; +namespace Persistence.Models; /// /// Диапазон дат diff --git a/Persistence/Models/DrillingSystemDto.cs b/Persistence/Models/DrillingSystemDto.cs index c2e7abc..ad71ee8 100644 --- a/Persistence/Models/DrillingSystemDto.cs +++ b/Persistence/Models/DrillingSystemDto.cs @@ -5,18 +5,18 @@ /// public class DrillingSystemDto { - /// - /// Ключ - /// - public Guid SystemId { get; set; } + /// + /// Ключ + /// + public Guid SystemId { get; set; } - /// - /// Наименование - /// - public required string Name { get; set; } + /// + /// Наименование + /// + public required string Name { get; set; } - /// - /// Описание - /// - public string? Description { get; set; } + /// + /// Описание + /// + public string? Description { get; set; } } diff --git a/Persistence/Models/MessagesStatisticDto.cs b/Persistence/Models/MessagesStatisticDto.cs index 08f0edd..2e1e419 100644 --- a/Persistence/Models/MessagesStatisticDto.cs +++ b/Persistence/Models/MessagesStatisticDto.cs @@ -5,13 +5,13 @@ /// public class MessagesStatisticDto { - /// - /// Система бурения - /// - public required string System { get; set; } + /// + /// Система бурения + /// + public required string System { get; set; } - /// - /// Количество сообщений в соответствии с категориями важности - /// - public required Dictionary Categories { get; set; } + /// + /// Количество сообщений в соответствии с категориями важности + /// + public required Dictionary Categories { get; set; } } diff --git a/Persistence/Models/PaginationContainer.cs b/Persistence/Models/PaginationContainer.cs index a0c64b2..7054b2c 100644 --- a/Persistence/Models/PaginationContainer.cs +++ b/Persistence/Models/PaginationContainer.cs @@ -11,7 +11,7 @@ public class PaginationContainer /// public PaginationContainer() { - Items = Enumerable.Empty(); + Items = []; } /// diff --git a/Persistence/Models/ParameterDto.cs b/Persistence/Models/ParameterDto.cs index 63a4660..9413a79 100644 --- a/Persistence/Models/ParameterDto.cs +++ b/Persistence/Models/ParameterDto.cs @@ -7,25 +7,25 @@ namespace Persistence.Models; /// public class ParameterDto { - /// - /// Дискриминатор системы - /// - public Guid DiscriminatorId { get; set; } + /// + /// Дискриминатор системы + /// + public Guid DiscriminatorId { get; set; } - /// - /// Id параметра - /// - [Range(0, int.MaxValue, ErrorMessage = "Id параметра не может быть меньше 0")] - public int ParameterId { get; set; } + /// + /// Id параметра + /// + [Range(0, int.MaxValue, ErrorMessage = "Id параметра не может быть меньше 0")] + public int ParameterId { get; set; } - /// - /// Значение параметра в виде строки - /// - [StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина значения параметра от 1 до 256 символов")] - public required string Value { get; set; } + /// + /// Значение параметра в виде строки + /// + [StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина значения параметра от 1 до 256 символов")] + public required string Value { get; set; } - /// - /// Временная отметка - /// - public DateTimeOffset Timestamp { get; set; } + /// + /// Временная отметка + /// + public DateTimeOffset Timestamp { get; set; } } diff --git a/Persistence/Models/SetpointLogDto.cs b/Persistence/Models/SetpointLogDto.cs index 4aa61b5..663bf30 100644 --- a/Persistence/Models/SetpointLogDto.cs +++ b/Persistence/Models/SetpointLogDto.cs @@ -9,7 +9,7 @@ public class SetpointLogDto : SetpointValueDto /// Дата сохранения уставки /// public DateTimeOffset Created { get; set; } - + /// /// Ключ пользователя /// diff --git a/Persistence/Models/SetpointValueDto.cs b/Persistence/Models/SetpointValueDto.cs index 06a2b3e..4cae4ff 100644 --- a/Persistence/Models/SetpointValueDto.cs +++ b/Persistence/Models/SetpointValueDto.cs @@ -9,7 +9,7 @@ public class SetpointValueDto /// /// public Guid Key { get; set; } - + /// /// Значение уставки /// diff --git a/Persistence/Models/TechMessageDto.cs b/Persistence/Models/TechMessageDto.cs index 84da656..927ba83 100644 --- a/Persistence/Models/TechMessageDto.cs +++ b/Persistence/Models/TechMessageDto.cs @@ -2,51 +2,51 @@ namespace Persistence.Models { - /// - /// Модель технологического сообщения - /// - public class TechMessageDto - { - /// - /// Id события - /// - [Required] - public Guid EventId { get; set; } + /// + /// Модель технологического сообщения + /// + public class TechMessageDto + { + /// + /// Id события + /// + [Required] + public Guid EventId { get; set; } - /// - /// Id Категории важности - /// - [Range(0, int.MaxValue, ErrorMessage = "Id Категории важности не может быть меньше 0")] - public int CategoryId { get; set; } + /// + /// Id Категории важности + /// + [Range(0, int.MaxValue, ErrorMessage = "Id Категории важности не может быть меньше 0")] + public int CategoryId { get; set; } - /// - /// Дата возникновения - /// - public DateTimeOffset Timestamp { get; set; } + /// + /// Дата возникновения + /// + public DateTimeOffset Timestamp { get; set; } - /// - /// Глубина забоя - /// - [Range(0, double.MaxValue, ErrorMessage = "Глубина забоя не может быть меньше 0")] - public double? Depth { get; set; } + /// + /// Глубина забоя + /// + [Range(0, double.MaxValue, ErrorMessage = "Глубина забоя не может быть меньше 0")] + public double? Depth { get; set; } - /// - /// Текст сообщения - /// - [Required] - [StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")] - public required string MessageText { get; set; } + /// + /// Текст сообщения + /// + [Required] + [StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")] + public required string MessageText { get; set; } - /// - /// Система автобурения, к которой относится сообщение - /// - [Required] - [StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина наименования системы АБ от 1 до 256 символов")] - public required string System { get; set; } + /// + /// Система автобурения, к которой относится сообщение + /// + [Required] + [StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина наименования системы АБ от 1 до 256 символов")] + public required string System { get; set; } - /// - /// Id пользователя за пультом бурильщика - /// - public Guid UserId { get; set; } - } + /// + /// Id пользователя за пультом бурильщика + /// + public Guid UserId { get; set; } + } } diff --git a/Persistence/Models/UserDto.cs b/Persistence/Models/UserDto.cs deleted file mode 100644 index cd1c192..0000000 --- a/Persistence/Models/UserDto.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace Persistence.Models; - -/// -/// Модель, описывающая пользователя -/// -public class UserDto -{ - /// - public int Id { get; set; } - - /// - /// логин - /// - public string Login { get; set; } = null!; - - /// - /// Имя - /// - public string? Name { get; set; } - - /// - /// Фамилия - /// - public string? Surname { get; set; } - - /// - /// Отчество - /// - public string? Patronymic { get; set; } - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// Phone - /// - public string? Phone { get; set; } - - /// - /// Должность - /// - public string? Position { get; set; } - - /// - /// Id компании - /// - public int IdCompany { get; set; } - - /// - /// Id состояния пользователя - /// 0 - не активен, - /// 1 - активен, - /// 2 - заблокирован - /// - public short IdState { get; set; } - - /// - /// Получение отображаемого имени - /// - /// -} diff --git a/Persistence/Models/WitsDataDto.cs b/Persistence/Models/WitsDataDto.cs index e224f6d..982df1f 100644 --- a/Persistence/Models/WitsDataDto.cs +++ b/Persistence/Models/WitsDataDto.cs @@ -1,24 +1,22 @@ -using System.ComponentModel.DataAnnotations; - -namespace Persistence.Models; +namespace Persistence.Models; /// /// Группа параметров Wits /// public class WitsDataDto { - /// - /// Временная отметка - /// - public required DateTimeOffset Timestamped { get; set; } + /// + /// Временная отметка + /// + public required DateTimeOffset Timestamped { get; set; } - /// - /// Дискриминатор системы - /// - public required Guid DiscriminatorId { get; set; } + /// + /// Дискриминатор системы + /// + public required Guid DiscriminatorId { get; set; } - /// - /// Параметры - /// - public IEnumerable Values { get; set; } = []; + /// + /// Параметры + /// + public IEnumerable Values { get; set; } = []; } diff --git a/Persistence/Models/WitsValueDto.cs b/Persistence/Models/WitsValueDto.cs index 0c68453..dcbd1cb 100644 --- a/Persistence/Models/WitsValueDto.cs +++ b/Persistence/Models/WitsValueDto.cs @@ -7,20 +7,20 @@ namespace Persistence.Models; /// public class WitsValueDto { - /// - /// Wits - Record Number - /// - [Range(1, 100, ErrorMessage = "Значение \"Record Number\" обязано находиться в диапозоне от 1 до 100")] - public int RecordId { get; set; } + /// + /// Wits - Record Number + /// + [Range(1, 100, ErrorMessage = "Значение \"Record Number\" обязано находиться в диапозоне от 1 до 100")] + public int RecordId { get; set; } - /// - /// Wits - Record Item - /// - [Range(1, 100, ErrorMessage = "Значение \"Wits Record Item\" обязано находиться в диапозоне от 1 до 100")] - public int ItemId { get; set; } + /// + /// Wits - Record Item + /// + [Range(1, 100, ErrorMessage = "Значение \"Wits Record Item\" обязано находиться в диапозоне от 1 до 100")] + public int ItemId { get; set; } - /// - /// Значение параметра - /// - public required object Value { get; set; } + /// + /// Значение параметра + /// + public required object Value { get; set; } } diff --git a/Persistence/Repositories/IParameterRepository.cs b/Persistence/Repositories/IParameterRepository.cs index c600898..6345708 100644 --- a/Persistence/Repositories/IParameterRepository.cs +++ b/Persistence/Repositories/IParameterRepository.cs @@ -3,41 +3,41 @@ namespace Persistence.Repositories; public interface IParameterRepository { - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token); - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); - /// - /// Получить набор параметров (Wits) для построения графика - /// - /// - /// - /// - /// - /// - /// - /// - Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, - int approxPointsCount, int? ratio, CancellationToken token); + /// + /// Получить набор параметров (Wits) для построения графика + /// + /// + /// + /// + /// + /// + /// + /// + Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, + int approxPointsCount, int? ratio, CancellationToken token); - /// - /// Сохранить набор параметров (Wits) - /// - /// - /// - /// - /// - Task AddRange(IEnumerable dtos, CancellationToken token); + /// + /// Сохранить набор параметров (Wits) + /// + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); } diff --git a/Persistence/Repositories/ISetpointRepository.cs b/Persistence/Repositories/ISetpointRepository.cs index 502b44a..272c9ec 100644 --- a/Persistence/Repositories/ISetpointRepository.cs +++ b/Persistence/Repositories/ISetpointRepository.cs @@ -1,4 +1,3 @@ -using Microsoft.AspNetCore.Mvc; using Persistence.Models; namespace Persistence.Repositories; @@ -16,14 +15,14 @@ public interface ISetpointRepository /// Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token); - /// - /// Получить значения уставок за определенный момент времени - /// - /// - /// дата, на которую получаем данные - /// - /// - Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token); + /// + /// Получить значения уставок за определенный момент времени + /// + /// + /// дата, на которую получаем данные + /// + /// + Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token); /// /// Получить историю изменений значений уставок @@ -33,31 +32,31 @@ public interface ISetpointRepository /// Task>> GetLog(IEnumerable setpointKeys, CancellationToken token); - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - Task GetDatesRangeAsync(CancellationToken token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + Task GetDatesRangeAsync(CancellationToken token); - /// - /// Метод сохранения уставки - /// - /// ключ операции - /// ключ пользователя - /// значение - /// - /// - /// to do - /// id User учесть в соответствующем методе репозитория - Task Add(Guid setpointKey, object newValue, Guid idUser, CancellationToken token); + /// + /// Метод сохранения уставки + /// + /// ключ операции + /// ключ пользователя + /// значение + /// + /// + /// to do + /// id User учесть в соответствующем методе репозитория + Task Add(Guid setpointKey, object newValue, Guid idUser, CancellationToken token); } diff --git a/Persistence/Repositories/ITableDataRepository.cs b/Persistence/Repositories/ITableDataRepository.cs deleted file mode 100644 index 0ca1715..0000000 --- a/Persistence/Repositories/ITableDataRepository.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Persistence.Models.Requests; - -namespace Persistence.Repositories; - -/// -/// Интерфейс по работе с табличными данными -/// -public interface ITableDataRepository - where TDto : class, new() - where TRequest : PaginationRequest -{ - /// - /// Получить страницу списка объектов - /// - /// параметры фильтрации - /// - /// - Task> Get(TRequest request, CancellationToken token); -} diff --git a/Persistence/Repositories/ITimeSeriesBaseRepository.cs b/Persistence/Repositories/ITimeSeriesBaseRepository.cs index 26edf2f..abe6b05 100644 --- a/Persistence/Repositories/ITimeSeriesBaseRepository.cs +++ b/Persistence/Repositories/ITimeSeriesBaseRepository.cs @@ -1,6 +1,4 @@ -using Persistence.Models; - -namespace Persistence.Repositories; +namespace Persistence.Repositories; /// /// Интерфейс по работе с прореженными данными @@ -15,8 +13,8 @@ public interface ITimeSeriesBaseRepository /// /// Task> GetResampledData( - DateTimeOffset dateBegin, - double intervalSec = 600d, + DateTimeOffset dateBegin, + double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default); } diff --git a/Persistence/Services/Interfaces/ITimeSeriesDataObserverService.cs b/Persistence/Services/Interfaces/ITimeSeriesDataObserverService.cs deleted file mode 100644 index 9cbe04f..0000000 --- a/Persistence/Services/Interfaces/ITimeSeriesDataObserverService.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace Persistence.Services.Interfaces; - -public interface ITimeSeriesDataObserverService -{ -} diff --git a/Persistence/Services/Interfaces/IWitsDataService.cs b/Persistence/Services/Interfaces/IWitsDataService.cs index dea77ab..68c5851 100644 --- a/Persistence/Services/Interfaces/IWitsDataService.cs +++ b/Persistence/Services/Interfaces/IWitsDataService.cs @@ -7,40 +7,40 @@ namespace Persistence.Services.Interfaces; /// public interface IWitsDataService { - /// - /// Получить набор параметров для построения графика - /// - /// - /// - /// - Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); + /// + /// Получить набор параметров для построения графика + /// + /// + /// + /// + Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token); - /// - /// Получить порцию записей, начиная с заданной даты - /// - /// - /// - /// - /// - /// + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + /// Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token); - /// - /// Получить диапазон дат, для которых есть данные в репозитории - /// - /// - /// - /// - /// - /// - /// - Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token); + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + /// + /// + /// + /// + Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token); - /// - /// Сохранить набор параметров - /// - /// - /// - /// - Task AddRange(IEnumerable dtos, CancellationToken token); + /// + /// Сохранить набор параметров + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); } \ No newline at end of file diff --git a/Persistence/Services/Interfaces/TimeSeriesDataObserverService.cs b/Persistence/Services/Interfaces/TimeSeriesDataObserverService.cs deleted file mode 100644 index 7da510e..0000000 --- a/Persistence/Services/Interfaces/TimeSeriesDataObserverService.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace Persistence.Services.Interfaces; -public abstract class TimeSeriesDataObserverService : ITimeSeriesDataObserverService -{ -} diff --git a/Persistence/Services/WitsDataService.cs b/Persistence/Services/WitsDataService.cs index 3d99a3a..100bf56 100644 --- a/Persistence/Services/WitsDataService.cs +++ b/Persistence/Services/WitsDataService.cs @@ -1,174 +1,173 @@ -using System.Text.Json.Serialization; -using System.Text.Json; -using Microsoft.Extensions.Configuration; -using Persistence.Models; -using Persistence.Repositories; -using Persistence.Services.Interfaces; +using Persistence.Models; using Persistence.Models.Configurations; using Persistence.Models.Enumerations; +using Persistence.Repositories; +using Persistence.Services.Interfaces; using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Persistence.Services; public class WitsDataService : IWitsDataService { - private readonly IParameterRepository witsDataRepository; + private readonly IParameterRepository witsDataRepository; - private readonly WitsInfo[] witsInfo; + private readonly WitsInfo[] witsInfo; - private const int multiplier = 1000; - private const string witsConfigPath = "Persistence.Services.Config.WitsConfig.json"; + private const int multiplier = 1000; + private const string witsConfigPath = "Persistence.Services.Config.WitsConfig.json"; - public WitsDataService(IParameterRepository witsDataRepository) - { - this.witsDataRepository = witsDataRepository; + public WitsDataService(IParameterRepository witsDataRepository) + { + this.witsDataRepository = witsDataRepository; - this.witsInfo = GetWitsInfo(); - } + this.witsInfo = GetWitsInfo(); + } - public Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token) - { - var result = witsDataRepository.GetDatesRangeAsync(idDiscriminator, token); + public Task GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token) + { + var result = witsDataRepository.GetDatesRangeAsync(idDiscriminator, token); - return result; - } + return result; + } - public async Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token) - { - var dtos = await witsDataRepository.GetPart(idDiscriminator, dateBegin, take, token); - - var result = AdaptToWitsData(dtos); + public async Task> GetPart(Guid idDiscriminator, DateTimeOffset dateBegin, int take, CancellationToken token) + { + var dtos = await witsDataRepository.GetPart(idDiscriminator, dateBegin, take, token); - return result; - } + var result = AdaptToWitsData(dtos); - public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, - int approxPointsCount, CancellationToken token) - { - var intervalSec = (dateTo - dateFrom).TotalSeconds; + return result; + } - int? ratio = null; - if (intervalSec > 2 * approxPointsCount) - { - ratio = (int) intervalSec / approxPointsCount; - } + public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, + int approxPointsCount, CancellationToken token) + { + var intervalSec = (dateTo - dateFrom).TotalSeconds; - var dtos = await witsDataRepository.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, ratio, token); + int? ratio = null; + if (intervalSec > 2 * approxPointsCount) + { + ratio = (int)intervalSec / approxPointsCount; + } - var result = AdaptToWitsData(dtos); + var dtos = await witsDataRepository.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, ratio, token); - return result; - } + var result = AdaptToWitsData(dtos); - public async Task AddRange(IEnumerable dtos, CancellationToken token) - { - var parameterDtos = dtos.SelectMany(e => e.Values.Select(t => new ParameterDto() - { - DiscriminatorId = e.DiscriminatorId, - ParameterId = EncodeId(t.RecordId, t.ItemId), - Value = t.Value.ToString()!, - Timestamp = e.Timestamped - })); - var result = await witsDataRepository.AddRange(parameterDtos, token); + return result; + } - return result; - } + public async Task AddRange(IEnumerable dtos, CancellationToken token) + { + var parameterDtos = dtos.SelectMany(e => e.Values.Select(t => new ParameterDto() + { + DiscriminatorId = e.DiscriminatorId, + ParameterId = EncodeId(t.RecordId, t.ItemId), + Value = t.Value.ToString()!, + Timestamp = e.Timestamped + })); + var result = await witsDataRepository.AddRange(parameterDtos, token); - private int EncodeId(int recordId, int itemId) - { - var resultId = multiplier * recordId + itemId; - return resultId; - } + return result; + } - private int DecodeRecordId(int id) - { - var resultId = id / multiplier; + private int EncodeId(int recordId, int itemId) + { + var resultId = multiplier * recordId + itemId; + return resultId; + } - return resultId; - } + private int DecodeRecordId(int id) + { + var resultId = id / multiplier; - private int DecodeItemId(int id) - { - var resultId = id % multiplier; + return resultId; + } - return resultId; - } + private int DecodeItemId(int id) + { + var resultId = id % multiplier; - private IEnumerable AdaptToWitsData(IEnumerable dtos) - { - var result = new List(); - var witsGroup = dtos - .GroupBy(e => new { e.DiscriminatorId, e.Timestamp }); - foreach (var witsInGroup in witsGroup) - { - var witsDataDto = new WitsDataDto() - { - DiscriminatorId = witsInGroup.Key.DiscriminatorId, - Timestamped = witsInGroup.Key.Timestamp - }; + return resultId; + } - witsDataDto.Values = witsInGroup.Select(e => - { - var recordId = DecodeRecordId(e.ParameterId); - var itemId = DecodeItemId(e.ParameterId); + private IEnumerable AdaptToWitsData(IEnumerable dtos) + { + var result = new List(); + var witsGroup = dtos + .GroupBy(e => new { e.DiscriminatorId, e.Timestamp }); + foreach (var witsInGroup in witsGroup) + { + var witsDataDto = new WitsDataDto() + { + DiscriminatorId = witsInGroup.Key.DiscriminatorId, + Timestamped = witsInGroup.Key.Timestamp + }; - return new WitsValueDto() - { - RecordId = recordId, - ItemId = itemId, - Value = ConvertValue(recordId, itemId, e.Value) - }; - }); + witsDataDto.Values = witsInGroup.Select(e => + { + var recordId = DecodeRecordId(e.ParameterId); + var itemId = DecodeItemId(e.ParameterId); - result.Add(witsDataDto); - } + return new WitsValueDto() + { + RecordId = recordId, + ItemId = itemId, + Value = ConvertValue(recordId, itemId, e.Value) + }; + }); - return result; - } + result.Add(witsDataDto); + } - private object ConvertValue(int recordId, int itemId, string value) - { - var witsType = witsInfo.FirstOrDefault(e => e.ItemId == itemId - && e.RecordId == recordId)?.ValueType; + return result; + } - switch(witsType) - { - default: - { - return value; - } - case WitsType.S: - { - var result = Int16.Parse(value); + private object ConvertValue(int recordId, int itemId, string value) + { + var witsType = witsInfo.FirstOrDefault(e => e.ItemId == itemId + && e.RecordId == recordId)?.ValueType; - return result; - } - case WitsType.L: - { - var result = Int32.Parse(value); + switch (witsType) + { + default: + { + return value; + } + case WitsType.S: + { + var result = Int16.Parse(value); - return result; - } - case WitsType.F: - { - var result = float.Parse(value, CultureInfo.InvariantCulture); + return result; + } + case WitsType.L: + { + var result = Int32.Parse(value); - return result; - } - } - } + return result; + } + case WitsType.F: + { + var result = float.Parse(value, CultureInfo.InvariantCulture); - private WitsInfo[] GetWitsInfo() - { - var stream = System.Reflection.Assembly.GetExecutingAssembly() - .GetManifestResourceStream(witsConfigPath); - var options = new JsonSerializerOptions - { - Converters = - { - new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) - }, - }; - var records = JsonSerializer.Deserialize(stream!, options) ?? []; - return records; - } + return result; + } + } + } + + private WitsInfo[] GetWitsInfo() + { + var stream = System.Reflection.Assembly.GetExecutingAssembly() + .GetManifestResourceStream(witsConfigPath); + var options = new JsonSerializerOptions + { + Converters = + { + new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) + }, + }; + var records = JsonSerializer.Deserialize(stream!, options) ?? []; + return records; + } } diff --git a/exclusion.dic b/exclusion.dic new file mode 100644 index 0000000..9602d51 --- /dev/null +++ b/exclusion.dic @@ -0,0 +1,78 @@ +appsettings +autohold +Autostart +dd +dtos +HH +Impl +MM +mmss +modbus +noload +Saub +Toolface +yyyy +Автоудержание +макрооперации +Макрооперация +расхаживаний +расхаживания +Соотв +Noload +updatables +штропа +страгивания +updatables +MM +dd +HH +mmss +sqlite +Serializer +Auth +Saub +lightgray +appsettings +AutoScale +Hmmss +pinger +Desc +qwertyuiopasdfghjklzxcvbnm +Deserialize +Deserializer +Deserializers +Impl +Protobuf +сериализацию +param +tcpclient +tcpserver +tcplistener +serialport +bigendianunicode +Middlewares +Referer +бекапов +Encoderless +Безэнкодерный +безэнкодерного +энкодеру +автоудержания +дифф +энкодера +Коэфф +Миним +Проворот +вспом +Extrem +выкл +minidisplay +oauth +sbin +прога +yyyyMMdd_HHmmssfff +Serializers +keycloak +Params +Mapster +dest